-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathi18n-options.ts
332 lines (291 loc) · 10.4 KB
/
i18n-options.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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BuilderContext } from '@angular-devkit/architect';
import { json } from '@angular-devkit/core';
import fs from 'fs';
import module from 'module';
import os from 'os';
import path from 'path';
import { Schema as BrowserBuilderSchema, I18NTranslation } from '../builders/browser/schema';
import { Schema as ServerBuilderSchema } from '../builders/server/schema';
import { readTsconfig } from '../utils/read-tsconfig';
import { TranslationLoader, createTranslationLoader } from './load-translations';
/**
* The base module location used to search for locale specific data.
*/
const LOCALE_DATA_BASE_MODULE = '@angular/common/locales/global';
export interface LocaleDescription {
files: {
path: string;
integrity?: string;
format?: string;
}[];
translation?: Record<string, unknown>;
dataPath?: string;
baseHref?: string;
}
export interface I18nOptions {
inlineLocales: Set<string>;
sourceLocale: string;
locales: Record<string, LocaleDescription>;
flatOutput?: boolean;
readonly shouldInline: boolean;
hasDefinedSourceLocale?: boolean;
}
function normalizeTranslationFileOption(
option: json.JsonValue,
locale: string,
expectObjectInError: boolean,
): string[] {
if (typeof option === 'string') {
return [option];
}
if (Array.isArray(option) && option.every((element) => typeof element === 'string')) {
return option as string[];
}
let errorMessage = `Project i18n locales translation field value for '${locale}' is malformed. `;
if (expectObjectInError) {
errorMessage += 'Expected a string, array of strings, or object.';
} else {
errorMessage += 'Expected a string or array of strings.';
}
throw new Error(errorMessage);
}
export function createI18nOptions(
metadata: json.JsonObject,
inline?: boolean | string[],
): I18nOptions {
if (metadata.i18n !== undefined && !json.isJsonObject(metadata.i18n)) {
throw new Error('Project i18n field is malformed. Expected an object.');
}
metadata = metadata.i18n || {};
const i18n: I18nOptions = {
inlineLocales: new Set<string>(),
// en-US is the default locale added to Angular applications (https://angular.io/guide/i18n#i18n-pipes)
sourceLocale: 'en-US',
locales: {},
get shouldInline() {
return this.inlineLocales.size > 0;
},
};
let rawSourceLocale;
let rawSourceLocaleBaseHref;
if (json.isJsonObject(metadata.sourceLocale)) {
rawSourceLocale = metadata.sourceLocale.code;
if (
metadata.sourceLocale.baseHref !== undefined &&
typeof metadata.sourceLocale.baseHref !== 'string'
) {
throw new Error('Project i18n sourceLocale baseHref field is malformed. Expected a string.');
}
rawSourceLocaleBaseHref = metadata.sourceLocale.baseHref;
} else {
rawSourceLocale = metadata.sourceLocale;
}
if (rawSourceLocale !== undefined) {
if (typeof rawSourceLocale !== 'string') {
throw new Error('Project i18n sourceLocale field is malformed. Expected a string.');
}
i18n.sourceLocale = rawSourceLocale;
i18n.hasDefinedSourceLocale = true;
}
i18n.locales[i18n.sourceLocale] = {
files: [],
baseHref: rawSourceLocaleBaseHref,
};
if (metadata.locales !== undefined && !json.isJsonObject(metadata.locales)) {
throw new Error('Project i18n locales field is malformed. Expected an object.');
} else if (metadata.locales) {
for (const [locale, options] of Object.entries(metadata.locales)) {
let translationFiles;
let baseHref;
if (json.isJsonObject(options)) {
translationFiles = normalizeTranslationFileOption(options.translation, locale, false);
if (typeof options.baseHref === 'string') {
baseHref = options.baseHref;
}
} else {
translationFiles = normalizeTranslationFileOption(options, locale, true);
}
if (locale === i18n.sourceLocale) {
throw new Error(
`An i18n locale ('${locale}') cannot both be a source locale and provide a translation.`,
);
}
i18n.locales[locale] = {
files: translationFiles.map((file) => ({ path: file })),
baseHref,
};
}
}
if (inline === true) {
i18n.inlineLocales.add(i18n.sourceLocale);
Object.keys(i18n.locales).forEach((locale) => i18n.inlineLocales.add(locale));
} else if (inline) {
for (const locale of inline) {
if (!i18n.locales[locale] && i18n.sourceLocale !== locale) {
throw new Error(`Requested locale '${locale}' is not defined for the project.`);
}
i18n.inlineLocales.add(locale);
}
}
return i18n;
}
export async function configureI18nBuild<T extends BrowserBuilderSchema | ServerBuilderSchema>(
context: BuilderContext,
options: T,
): Promise<{
buildOptions: T;
i18n: I18nOptions;
}> {
if (!context.target) {
throw new Error('The builder requires a target.');
}
const buildOptions = { ...options };
const tsConfig = await readTsconfig(buildOptions.tsConfig, context.workspaceRoot);
const metadata = await context.getProjectMetadata(context.target);
const i18n = createI18nOptions(metadata, buildOptions.localize);
// No additional processing needed if no inlining requested and no source locale defined.
if (!i18n.shouldInline && !i18n.hasDefinedSourceLocale) {
return { buildOptions, i18n };
}
const projectRoot = path.join(context.workspaceRoot, (metadata.root as string) || '');
// The trailing slash is required to signal that the path is a directory and not a file.
const projectRequire = module.createRequire(projectRoot + '/');
const localeResolver = (locale: string) =>
projectRequire.resolve(path.join(LOCALE_DATA_BASE_MODULE, locale));
// Load locale data and translations (if present)
let loader;
const usedFormats = new Set<string>();
for (const [locale, desc] of Object.entries(i18n.locales)) {
if (!i18n.inlineLocales.has(locale) && locale !== i18n.sourceLocale) {
continue;
}
let localeDataPath = findLocaleDataPath(locale, localeResolver);
if (!localeDataPath) {
const [first] = locale.split('-');
if (first) {
localeDataPath = findLocaleDataPath(first.toLowerCase(), localeResolver);
if (localeDataPath) {
context.logger.warn(
`Locale data for '${locale}' cannot be found. Using locale data for '${first}'.`,
);
}
}
}
if (!localeDataPath) {
context.logger.warn(
`Locale data for '${locale}' cannot be found. No locale data will be included for this locale.`,
);
} else {
desc.dataPath = localeDataPath;
}
if (!desc.files.length) {
continue;
}
loader ??= await createTranslationLoader();
loadTranslations(
locale,
desc,
context.workspaceRoot,
loader,
{
warn(message) {
context.logger.warn(message);
},
error(message) {
throw new Error(message);
},
},
usedFormats,
buildOptions.i18nDuplicateTranslation,
);
if (usedFormats.size > 1 && tsConfig.options.enableI18nLegacyMessageIdFormat !== false) {
// This limitation is only for legacy message id support (defaults to true as of 9.0)
throw new Error(
'Localization currently only supports using one type of translation file format for the entire application.',
);
}
}
// If inlining store the output in a temporary location to facilitate post-processing
if (i18n.shouldInline) {
// TODO: we should likely save these in the .angular directory in the next major version.
// We'd need to do a migration to add the temp directory to gitignore.
const tempPath = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'angular-cli-i18n-'));
buildOptions.outputPath = tempPath;
process.on('exit', () => {
try {
fs.rmSync(tempPath, { force: true, recursive: true, maxRetries: 3 });
} catch {}
});
}
return { buildOptions, i18n };
}
function findLocaleDataPath(locale: string, resolver: (locale: string) => string): string | null {
// Remove private use subtags
const scrubbedLocale = locale.replace(/-x(-[a-zA-Z0-9]{1,8})+$/, '');
try {
return resolver(scrubbedLocale);
} catch {
// fallback to known existing en-US locale data as of 14.0
return scrubbedLocale === 'en-US' ? findLocaleDataPath('en', resolver) : null;
}
}
export function loadTranslations(
locale: string,
desc: LocaleDescription,
workspaceRoot: string,
loader: TranslationLoader,
logger: { warn: (message: string) => void; error: (message: string) => void },
usedFormats?: Set<string>,
duplicateTranslation?: I18NTranslation,
) {
let translations: Record<string, unknown> | undefined = undefined;
for (const file of desc.files) {
const loadResult = loader(path.join(workspaceRoot, file.path));
for (const diagnostics of loadResult.diagnostics.messages) {
if (diagnostics.type === 'error') {
logger.error(`Error parsing translation file '${file.path}': ${diagnostics.message}`);
} else {
logger.warn(`WARNING [${file.path}]: ${diagnostics.message}`);
}
}
if (loadResult.locale !== undefined && loadResult.locale !== locale) {
logger.warn(
`WARNING [${file.path}]: File target locale ('${loadResult.locale}') does not match configured locale ('${locale}')`,
);
}
usedFormats?.add(loadResult.format);
file.format = loadResult.format;
file.integrity = loadResult.integrity;
if (translations) {
// Merge translations
for (const [id, message] of Object.entries(loadResult.translations)) {
if (translations[id] !== undefined) {
const duplicateTranslationMessage = `[${file.path}]: Duplicate translations for message '${id}' when merging.`;
switch (duplicateTranslation) {
case I18NTranslation.Ignore:
break;
case I18NTranslation.Error:
logger.error(`ERROR ${duplicateTranslationMessage}`);
break;
case I18NTranslation.Warning:
default:
logger.warn(`WARNING ${duplicateTranslationMessage}`);
break;
}
}
translations[id] = message;
}
} else {
// First or only translation file
translations = loadResult.translations;
}
}
desc.translation = translations;
}