-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlocalized-string-key-validator.ts
50 lines (43 loc) · 1.32 KB
/
localized-string-key-validator.ts
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
import WebpackError from 'webpack/lib/WebpackError.js';
import hasOwnProp from 'has-own-prop';
import type { NormalModule } from 'webpack5';
import type { Expression } from 'estree';
import { LocalizedStringKey } from '../types-internal.js';
import { name } from '../../package.json';
import { reportModuleWarning } from './webpack.js';
import type { LocaleData } from './load-locale-data.js';
export function localizedStringKeyValidator(
locales: LocaleData,
throwOnMissing?: boolean,
) {
const validatedKeys = new Set<LocalizedStringKey>();
return (
stringKey: LocalizedStringKey,
module: NormalModule,
node: Expression,
) => {
if (validatedKeys.has(stringKey)) {
return;
}
validatedKeys.add(stringKey);
const keyMissingFromLocales = locales.names.filter(
localeName => !hasOwnProp(locales.data[localeName], stringKey),
);
const isMissingFromLocales = keyMissingFromLocales.length > 0;
if (!isMissingFromLocales) {
return;
}
const location = node.loc!.start;
const error = new WebpackError(`[${name}] Missing localization for key "${stringKey}" used in ${module.resource}:${location.line}:${location.column} from locales: ${keyMissingFromLocales.join(', ')}`);
if (error) {
if (throwOnMissing) {
throw error;
} else {
reportModuleWarning(
module,
error,
);
}
}
};
}