-
-
Notifications
You must be signed in to change notification settings - Fork 629
/
Interpolator.js
168 lines (133 loc) · 5.52 KB
/
Interpolator.js
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
import * as utils from './utils.js';
import baseLogger from './logger.js';
class Interpolator {
constructor(options = {}) {
this.logger = baseLogger.create('interpolator');
this.init(options, true);
}
/* eslint no-param-reassign: 0 */
init(options = {}, reset) {
if (reset) {
this.options = options;
this.format = (options.interpolation && options.interpolation.format) || (value => value);
this.escape = (options.interpolation && options.interpolation.escape) || utils.escape;
}
if (!options.interpolation) options.interpolation = { escapeValue: true };
const iOpts = options.interpolation;
this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
this.prefix = iOpts.prefix ? utils.regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
this.suffix = iOpts.suffix ? utils.regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
this.nestingPrefix = iOpts.nestingPrefix ? utils.regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || utils.regexEscape('$t(');
this.nestingSuffix = iOpts.nestingSuffix ? utils.regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || utils.regexEscape(')');
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
// the regexp
this.resetRegExp();
}
reset() {
if (this.options) this.init(this.options);
}
resetRegExp() {
// the regexp
const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
this.regexp = new RegExp(regexpStr, 'g');
const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
}
interpolate(str, data, lng) {
let match;
let value;
let replaces;
function regexSafe(val) {
return val.replace(/\$/g, '$$$$');
}
const handleFormat = (key) => {
if (key.indexOf(this.formatSeparator) < 0) return utils.getPath(data, key);
const p = key.split(this.formatSeparator);
const k = p.shift().trim();
const f = p.join(this.formatSeparator).trim();
return this.format(utils.getPath(data, k), f, lng);
};
this.resetRegExp();
replaces = 0;
// unescape if has unescapePrefix/Suffix
/* eslint no-cond-assign: 0 */
while (match = this.regexpUnescape.exec(str)) {
value = handleFormat(match[1].trim());
str = str.replace(match[0], value);
this.regexpUnescape.lastIndex = 0;
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
replaces = 0;
// regular escape on demand
while (match = this.regexp.exec(str)) {
value = handleFormat(match[1].trim());
if (value === undefined) {
if (typeof this.options.missingInterpolationHandler === 'function') {
const temp = this.options.missingInterpolationHandler(str, match);
value = typeof temp === 'string' ? temp : '';
} else {
this.logger.warn(`missed to pass in variable ${match[1]} for interpolating ${str}`);
value = '';
}
} else if (typeof value !== 'string') {
value = utils.makeString(value);
}
value = this.escapeValue ? regexSafe(this.escape(value)) : regexSafe(value);
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
return str;
}
nest(str, fc, options = {}) {
let match;
let value;
let clonedOptions = { ...options };
clonedOptions.applyPostProcessor = false; // avoid post processing on nested lookup
// if value is something like "myKey": "lorem $(anotherKey, { "count": {{aValueInOptions}} })"
function handleHasOptions(key, inheritedOptions) {
if (key.indexOf(',') < 0) return key;
const p = key.split(',');
key = p.shift();
let optionsString = p.join(',');
optionsString = this.interpolate(optionsString, clonedOptions);
optionsString = optionsString.replace(/'/g, '"');
try {
clonedOptions = JSON.parse(optionsString);
if (inheritedOptions) clonedOptions = { ...inheritedOptions, ...clonedOptions };
} catch (e) {
this.logger.error(`failed parsing options string in nesting for key ${key}`, e);
}
return key;
}
// regular escape on demand
while (match = this.nestingRegexp.exec(str)) {
value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
// is only the nesting key (key1 = '$(key2)') return the value without stringify
if (value && match[0] === str && typeof value !== 'string') return value;
// no string to include or empty
if (typeof value !== 'string') value = utils.makeString(value);
if (!value) {
this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
value = '';
}
// Nested keys should not be escaped by default #854
// value = this.escapeValue ? regexSafe(utils.escape(value)) : regexSafe(value);
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
}
return str;
}
}
export default Interpolator;