/
valid-message-syntax.js
229 lines (210 loc) · 5.13 KB
/
valid-message-syntax.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
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
const set = require('lodash.set');
const diff = require('jest-diff');
const isPlainObject = require('lodash.isplainobject');
const prettyFormat = require('pretty-format');
const icuValidator = require('./message-validators/icu');
const notEmpty = require('./message-validators/not-empty');
const isString = require('./message-validators/is-string');
const deepForOwn = require('./util/deep-for-own');
const requireNoCache = require('./util/require-no-cache');
const getTranslationFileSource = require('./util/get-translation-file-source');
/* Error tokens */
const EMPTY_OBJECT = Symbol.for('EMPTY_OBJECT');
const ARRAY = Symbol.for('ARRAY');
/* Formatting */
const ALL_BACKSLASHES = /[\\]/g;
const ALL_DOUBLE_QUOTES = /["]/g;
const prettyFormatTypePlugin = {
test(val) {
return typeof val === 'number' || typeof val === 'string';
},
serialize(val) {
return (
(typeof val === 'string' && `String(${`'${val}'`})`) || `Number(${val})`
);
}
};
const formatExpectedValue = ({ value }) => {
switch (value) {
case EMPTY_OBJECT:
case ARRAY:
return 'ObjectContaining<ValidMessages> | ValidMessage<String>';
default:
return 'ValidMessage<String>';
}
};
const formatReceivedValue = ({ value, error }) => {
const errorMessage = error.message
.replace(ALL_BACKSLASHES, '')
.replace(ALL_DOUBLE_QUOTES, "'");
switch (value) {
case EMPTY_OBJECT:
return `${prettyFormat({})} ===> ${error}`;
case ARRAY:
return `${prettyFormat([])} ===> ${error}`;
default:
return `${prettyFormat(value, {
plugins: [prettyFormatTypePlugin]
})} ===> ${errorMessage}`;
}
};
const createValidator = (syntax) => {
// each syntax type defined here must have a case!
if (['icu', 'non-empty-string'].includes(syntax)) {
return (value) => {
switch (syntax) {
case 'icu':
notEmpty(value);
isString(value);
icuValidator(value);
break;
default:
notEmpty(value);
isString(value);
}
};
}
// custom validator
const customValidator = requireNoCache(syntax);
return (value, key) => {
customValidator(value, key);
};
};
const validMessageSyntax = (context, source) => {
const { options, settings = {} } = context;
let { syntax } = options[0] || {};
syntax = syntax && syntax.trim();
let translations = null;
const invalidMessages = [];
if (!syntax) {
return [
{
message: '"syntax" not specified in rule option.',
loc: {
start: {
line: 0,
col: 0
}
}
}
];
}
try {
translations = JSON.parse(source);
} catch (e) {
return [];
}
let validate;
try {
validate = createValidator(syntax);
} catch (e) {
return [
{
message: `Error configuring syntax validator. Rule option specified: ${syntax}. ${e}`,
loc: {
start: {
line: 0,
col: 0
}
}
}
];
}
const ignorePaths = settings['i18n-json/ignore-keys'] || [];
deepForOwn(
translations,
(value, key, path) => {
// empty object itself is an error
if (isPlainObject(value)) {
if (Object.keys(value).length === 0) {
invalidMessages.push({
value: EMPTY_OBJECT,
key,
path,
error: new SyntaxError('Empty object.')
});
}
} else if (Array.isArray(value)) {
invalidMessages.push({
value: ARRAY,
key,
path,
error: new TypeError('An Array cannot be a translation value.')
});
} else {
try {
validate(value, key);
} catch (validationError) {
invalidMessages.push({
value,
key,
path,
error: validationError
});
}
}
},
{
ignorePaths
}
);
if (invalidMessages.length > 0) {
const expected = {};
const received = {};
invalidMessages.forEach((invalidMessage) => {
set(expected, invalidMessage.path, formatExpectedValue(invalidMessage));
set(received, invalidMessage.path, formatReceivedValue(invalidMessage));
});
return [
{
message: `\n${diff(expected, received)}`,
loc: {
start: {
line: 0,
col: 0
}
}
}
];
}
// no errors
return [];
};
module.exports = {
meta: {
docs: {
category: 'Validation',
description:
'Validates message syntax for each translation key in the file.',
recommended: true
},
schema: [
{
properties: {
syntax: {
type: ['string']
}
},
type: 'object',
additionalProperties: false
}
]
},
create(context) {
return {
Program(node) {
const { valid, source } = getTranslationFileSource({
context,
node
});
if (!valid) {
return;
}
const errors = validMessageSyntax(context, source);
errors.forEach((error) => {
context.report(error);
});
}
};
}
};