• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

i18next / i18next / #12468

19 Apr 2018 07:07AM UTC coverage: 87.36% (+1.9%) from 85.448%
#12468

push

jamuhl
rebuild

933 of 1068 relevant lines covered (87.36%)

38.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.87
/src/Interpolator.js
1
import * as utils from './utils.js';
2
import baseLogger from './logger.js';
3

1✔
4
class Interpolator {
5
  constructor(options = {}) {
6
    this.logger = baseLogger.create('interpolator');
7

160✔
8
    this.init(options, true);
9
  }
1✔
10

11
  /* eslint no-param-reassign: 0 */
1✔
12
  init(options = {}, reset) {
13
    if (reset) {
1✔
14
      this.options = options;
15
      this.format = (options.interpolation && options.interpolation.format) || (value => value);
1✔
16
      this.escape = (options.interpolation && options.interpolation.escape) || utils.escape;
17
    }
1✔
18
    if (!options.interpolation) options.interpolation = { escapeValue: true };
19

1✔
20
    const iOpts = options.interpolation;
21

40✔
22
    this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
23

1✔
24
    this.prefix = iOpts.prefix ? utils.regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
1✔
25
    this.suffix = iOpts.suffix ? utils.regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
40✔
26

27
    this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
40✔
28

29
    this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
40✔
30
    this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
31

40✔
32
    this.nestingPrefix = iOpts.nestingPrefix ? utils.regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || utils.regexEscape('$t(');
33
    this.nestingSuffix = iOpts.nestingSuffix ? utils.regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || utils.regexEscape(')');
34

35
    this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
36

37
    // the regexp
1✔
38
    this.resetRegExp();
42✔
39
  }
42✔
40

41
  reset() {
42✔
42
    if (this.options) this.init(this.options);
40✔
43
  }
40✔
44

×
45
  resetRegExp() {
46
    // the regexp
40✔
47
    const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
48
    this.regexp = new RegExp(regexpStr, 'g');
42✔
49

50
    const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
42✔
51
    this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
52

42✔
53
    const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
54
    this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
42✔
55
  }
42✔
56

57
  interpolate(str, data, lng) {
42✔
58
    let match;
59
    let value;
42✔
60
    let replaces;
42✔
61

62
    function regexSafe(val) {
42✔
63
      return val.replace(/\$/g, '$$$$');
42✔
64
    }
65

42✔
66
    const handleFormat = (key) => {
67
      if (key.indexOf(this.formatSeparator) < 0) return utils.getPath(data, key);
68

42✔
69
      const p = key.split(this.formatSeparator);
70
      const k = p.shift().trim();
71
      const f = p.join(this.formatSeparator).trim();
1✔
72

1✔
73
      return this.format(utils.getPath(data, k), f, lng);
74
    };
75

1✔
76
    this.resetRegExp();
77

169✔
78
    replaces = 0;
169✔
79
    // unescape if has unescapePrefix/Suffix
80
    /* eslint no-cond-assign: 0 */
169✔
81
    while (match = this.regexpUnescape.exec(str)) {
169✔
82
      value = handleFormat(match[1].trim());
83
      str = str.replace(match[0], value);
169✔
84
      this.regexpUnescape.lastIndex = 0;
169✔
85
      replaces++;
86
      if (replaces >= this.maxReplaces) {
87
        break;
1✔
88
      }
127✔
89
    }
90

127✔
91
    replaces = 0;
92
    // regular escape on demand
93
    while (match = this.regexp.exec(str)) {
127✔
94
      value = handleFormat(match[1].trim());
×
95
      if (value === undefined) {
96
        if (typeof this.options.missingInterpolationHandler === 'function') {
97
          const temp = this.options.missingInterpolationHandler(str, match);
127✔
98
          value = typeof temp === 'string' ? temp : '';
127✔
99
        } else {
127✔
100
          this.logger.warn(`missed to pass in variable ${match[1]} for interpolating ${str}`);
101
          value = '';
1✔
102
        }
46✔
103
      } else if (typeof value !== 'string') {
104
        value = utils.makeString(value);
105
      }
127✔
106
      value = this.escapeValue ? regexSafe(this.escape(value)) : regexSafe(value);
52✔
107
      str = str.replace(match[0], value);
108
      this.regexp.lastIndex = 0;
5✔
109
      replaces++;
5✔
110
      if (replaces >= this.maxReplaces) {
5✔
111
        break;
112
      }
5✔
113
    }
114
    return str;
115
  }
127✔
116

117
  nest(str, fc, options = {}) {
127✔
118
    let match;
119
    let value;
120

127✔
121
    let clonedOptions = { ...options };
5✔
122
    clonedOptions.applyPostProcessor = false; // avoid post processing on nested lookup
5✔
123

5✔
124
    // if value is something like "myKey": "lorem $(anotherKey, { "count": {{aValueInOptions}} })"
5✔
125
    function handleHasOptions(key, inheritedOptions) {
5✔
126
      if (key.indexOf(',') < 0) return key;
×
127

128
      const p = key.split(',');
129
      key = p.shift();
130
      let optionsString = p.join(',');
127✔
131
      optionsString = this.interpolate(optionsString, clonedOptions);
132
      optionsString = optionsString.replace(/'/g, '"');
127✔
133

47✔
134
      try {
46✔
135
        clonedOptions = JSON.parse(optionsString);
6✔
136

2✔
137
        if (inheritedOptions) clonedOptions = { ...inheritedOptions, ...clonedOptions };
2✔
138
      } catch (e) {
139
        this.logger.error(`failed parsing options string in nesting for key ${key}`, e);
4✔
140
      }
4✔
141

142
      return key;
40✔
143
    }
2✔
144

145
    // regular escape on demand
46✔
146
    while (match = this.nestingRegexp.exec(str)) {
46✔
147
      value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
46✔
148

46✔
149
      // is only the nesting key (key1 = '$(key2)') return the value without stringify
46✔
150
      if (value && match[0] === str && typeof value !== 'string') return value;
1✔
151

152
      // no string to include or empty
153
      if (typeof value !== 'string') value = utils.makeString(value);
126✔
154
      if (!value) {
155
        this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
156
        value = '';
1✔
157
      }
99✔
158
      // Nested keys should not be escaped by default #854
159
      // value = this.escapeValue ? regexSafe(utils.escape(value)) : regexSafe(value);
99✔
160
      str = str.replace(match[0], value);
99✔
161
      this.regexp.lastIndex = 0;
162
    }
99✔
163
    return str;
99✔
164
  }
165
}
166

1✔
167

6✔
168
export default Interpolator;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc