forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n-options.ts
More file actions
293 lines (251 loc) · 9.39 KB
/
Copy pathi18n-options.ts
File metadata and controls
293 lines (251 loc) · 9.39 KB
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
/**
* @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.dev/license
*/
import path from 'node:path';
import type { TranslationLoader } from './load-translations';
export interface LocaleDescription {
files: {
path: string;
integrity?: string;
format?: string;
}[];
translation?: Record<string, unknown>;
dataPath?: string;
baseHref?: string;
subPath: string;
}
export interface I18nOptions {
inlineLocales: Set<string>;
sourceLocale: string;
locales: Record<string, LocaleDescription>;
flatOutput?: boolean;
readonly shouldInline: boolean;
hasDefinedSourceLocale?: boolean;
}
function normalizeTranslationFileOption(
option: unknown,
locale: string,
expectObjectInError: boolean,
): string[] {
if (typeof option === 'string') {
return [option];
}
if (Array.isArray(option) && option.every((element) => typeof element === 'string')) {
return option;
}
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);
}
function ensureObject(value: unknown, name: string): asserts value is Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`Project field '${name}' is malformed. Expected an object.`);
}
}
function ensureString(value: unknown, name: string): asserts value is string {
if (typeof value !== 'string') {
throw new Error(`Project field '${name}' is malformed. Expected a string.`);
}
}
function ensureValidSubPath(value: unknown, name: string): asserts value is string {
ensureString(value, name);
if (!/^[\w-]*$/.test(value)) {
throw new Error(
`Project field '${name}' is invalid. It can only contain letters, numbers, hyphens, and underscores.`,
);
}
}
export function createI18nOptions(
projectMetadata: { i18n?: unknown },
inline?: boolean | string[],
logger?: {
warn(message: string): void;
},
ssrEnabled?: boolean,
): I18nOptions {
const { i18n: metadata = {} } = projectMetadata;
ensureObject(metadata, 'i18n');
const i18n: I18nOptions = {
inlineLocales: new Set<string>(),
// en-US is the default locale added to Angular applications (https://angular.dev/guide/i18n/format-data-locale)
sourceLocale: 'en-US',
locales: {},
get shouldInline() {
return this.inlineLocales.size > 0;
},
};
let rawSourceLocale: string | undefined;
let rawSourceLocaleBaseHref: string | undefined;
let rawsubPath: string | undefined;
if (typeof metadata.sourceLocale === 'string') {
rawSourceLocale = metadata.sourceLocale;
} else if (metadata.sourceLocale !== undefined) {
ensureObject(metadata.sourceLocale, 'i18n.sourceLocale');
if (metadata.sourceLocale.code !== undefined) {
ensureString(metadata.sourceLocale.code, 'i18n.sourceLocale.code');
rawSourceLocale = metadata.sourceLocale.code;
}
if (metadata.sourceLocale.baseHref !== undefined) {
ensureString(metadata.sourceLocale.baseHref, 'i18n.sourceLocale.baseHref');
if (ssrEnabled) {
logger?.warn(
`'baseHref' in 'i18n.sourceLocale' may lead to undefined behavior when used with SSR. ` +
`Consider using 'subPath' instead.\n\n` +
`Note: 'subPath' specifies the URL segment for the locale, serving as both the HTML base HREF ` +
`and the output directory name.\nBy default, if not explicitly set, 'subPath' defaults to the locale code.`,
);
}
rawSourceLocaleBaseHref = metadata.sourceLocale.baseHref;
}
if (metadata.sourceLocale.subPath !== undefined) {
ensureValidSubPath(metadata.sourceLocale.subPath, 'i18n.sourceLocale.subPath');
rawsubPath = metadata.sourceLocale.subPath;
}
if (rawsubPath !== undefined && rawSourceLocaleBaseHref !== undefined) {
throw new Error(
`'i18n.sourceLocale.subPath' and 'i18n.sourceLocale.baseHref' cannot be used together.`,
);
}
}
if (rawSourceLocale !== undefined) {
i18n.sourceLocale = rawSourceLocale;
i18n.hasDefinedSourceLocale = true;
}
i18n.locales[i18n.sourceLocale] = {
files: [],
baseHref: rawSourceLocaleBaseHref,
subPath: rawsubPath ?? i18n.sourceLocale,
};
if (metadata.locales !== undefined) {
ensureObject(metadata.locales, 'i18n locales');
for (const [locale, options] of Object.entries(metadata.locales)) {
let translationFiles: string[] | undefined;
let baseHref: string | undefined;
let subPath: string | undefined;
if (options && typeof options === 'object' && 'translation' in options) {
translationFiles = normalizeTranslationFileOption(options.translation, locale, false);
if ('baseHref' in options) {
ensureString(options.baseHref, `i18n.locales.${locale}.baseHref`);
if (ssrEnabled) {
logger?.warn(
`'baseHref' in 'i18n.locales.${locale}' may lead to undefined behavior when used with SSR. ` +
`Consider using 'subPath' instead.\n\n` +
`Note: 'subPath' specifies the URL segment for the locale, serving as both the HTML base HREF ` +
`and the output directory name.\nBy default, if not explicitly set, 'subPath' defaults to the locale code.`,
);
}
baseHref = options.baseHref;
}
if ('subPath' in options) {
ensureValidSubPath(options.subPath, `i18n.locales.${locale}.subPath`);
subPath = options.subPath;
}
if (subPath !== undefined && baseHref !== undefined) {
throw new Error(
`'i18n.locales.${locale}.subPath' and 'i18n.locales.${locale}.baseHref' cannot be used together.`,
);
}
} 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,
subPath: subPath ?? locale,
};
}
}
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);
}
}
// Check that subPaths are unique only the locales that we are inlining.
const localesData = Object.entries(i18n.locales).filter(([locale]) =>
i18n.inlineLocales.has(locale),
);
for (let i = 0; i < localesData.length; i++) {
const [localeA, { subPath: subPathA }] = localesData[i];
for (let j = i + 1; j < localesData.length; j++) {
const [localeB, { subPath: subPathB }] = localesData[j];
if (subPathA === subPathB) {
throw new Error(
`Invalid i18n configuration: Locales '${localeA}' and '${localeB}' cannot have the same subPath: '${subPathB}'.`,
);
}
}
}
return i18n;
}
export function loadTranslations(
locale: string,
desc: LocaleDescription,
workspaceRoot: string,
loader: TranslationLoader,
logger: { warn: (message: string) => void; error: (message: string) => void },
usedFormats?: Set<string>,
duplicateTranslation?: 'ignore' | 'error' | 'warning',
) {
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 'ignore':
break;
case 'error':
logger.error(`ERROR ${duplicateTranslationMessage}`);
break;
case 'warning':
default:
logger.warn(`WARNING ${duplicateTranslationMessage}`);
break;
}
}
translations[id] = message;
}
} else {
// First or only translation file
translations = loadResult.translations;
}
}
desc.translation = translations;
}