/packages/angular_devkit/build_angular/src/utils/i18n-options.ts

https://github.com/angular/angular-cli · TypeScript · 396 lines · 315 code · 55 blank · 26 comment · 127 complexity · d0923bd8dffd03c1f6af097f4aeab22d MD5 · raw file

  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. import { BuilderContext } from '@angular-devkit/architect';
  9. import { json } from '@angular-devkit/core';
  10. import * as fs from 'fs';
  11. import * as os from 'os';
  12. import * as path from 'path';
  13. import * as rimraf from 'rimraf';
  14. import { Schema as BrowserBuilderSchema } from '../browser/schema';
  15. import { Schema as ServerBuilderSchema } from '../server/schema';
  16. import { readTsconfig } from '../utils/read-tsconfig';
  17. import { createTranslationLoader } from './load-translations';
  18. export interface I18nOptions {
  19. inlineLocales: Set<string>;
  20. sourceLocale: string;
  21. locales: Record<
  22. string,
  23. {
  24. files: { path: string; integrity?: string; format?: string }[];
  25. translation?: Record<string, unknown>;
  26. dataPath?: string;
  27. baseHref?: string;
  28. }
  29. >;
  30. flatOutput?: boolean;
  31. readonly shouldInline: boolean;
  32. veCompatLocale?: string;
  33. }
  34. function normalizeTranslationFileOption(
  35. option: json.JsonValue,
  36. locale: string,
  37. expectObjectInError: boolean,
  38. ): string[] {
  39. if (typeof option === 'string') {
  40. return [option];
  41. }
  42. if (Array.isArray(option) && option.every((element) => typeof element === 'string')) {
  43. return option as string[];
  44. }
  45. let errorMessage = `Project i18n locales translation field value for '${locale}' is malformed. `;
  46. if (expectObjectInError) {
  47. errorMessage += 'Expected a string, array of strings, or object.';
  48. } else {
  49. errorMessage += 'Expected a string or array of strings.';
  50. }
  51. throw new Error(errorMessage);
  52. }
  53. export function createI18nOptions(
  54. metadata: json.JsonObject,
  55. inline?: boolean | string[],
  56. ): I18nOptions {
  57. if (metadata.i18n !== undefined && !json.isJsonObject(metadata.i18n)) {
  58. throw new Error('Project i18n field is malformed. Expected an object.');
  59. }
  60. metadata = metadata.i18n || {};
  61. const i18n: I18nOptions = {
  62. inlineLocales: new Set<string>(),
  63. // en-US is the default locale added to Angular applications (https://angular.io/guide/i18n#i18n-pipes)
  64. sourceLocale: 'en-US',
  65. locales: {},
  66. get shouldInline() {
  67. return this.inlineLocales.size > 0;
  68. },
  69. };
  70. let rawSourceLocale;
  71. let rawSourceLocaleBaseHref;
  72. if (json.isJsonObject(metadata.sourceLocale)) {
  73. rawSourceLocale = metadata.sourceLocale.code;
  74. if (metadata.sourceLocale.baseHref !== undefined && typeof metadata.sourceLocale.baseHref !== 'string') {
  75. throw new Error('Project i18n sourceLocale baseHref field is malformed. Expected a string.');
  76. }
  77. rawSourceLocaleBaseHref = metadata.sourceLocale.baseHref;
  78. } else {
  79. rawSourceLocale = metadata.sourceLocale;
  80. }
  81. if (rawSourceLocale !== undefined) {
  82. if (typeof rawSourceLocale !== 'string') {
  83. throw new Error('Project i18n sourceLocale field is malformed. Expected a string.');
  84. }
  85. i18n.sourceLocale = rawSourceLocale;
  86. }
  87. i18n.locales[i18n.sourceLocale] = {
  88. files: [],
  89. baseHref: rawSourceLocaleBaseHref,
  90. };
  91. if (metadata.locales !== undefined && !json.isJsonObject(metadata.locales)) {
  92. throw new Error('Project i18n locales field is malformed. Expected an object.');
  93. } else if (metadata.locales) {
  94. for (const [locale, options] of Object.entries(metadata.locales)) {
  95. let translationFiles;
  96. let baseHref;
  97. if (json.isJsonObject(options)) {
  98. translationFiles = normalizeTranslationFileOption(options.translation, locale, false);
  99. if (typeof options.baseHref === 'string') {
  100. baseHref = options.baseHref;
  101. }
  102. } else {
  103. translationFiles = normalizeTranslationFileOption(options, locale, true);
  104. }
  105. if (locale === i18n.sourceLocale) {
  106. throw new Error(
  107. `An i18n locale ('${locale}') cannot both be a source locale and provide a translation.`,
  108. );
  109. }
  110. i18n.locales[locale] = {
  111. files: translationFiles.map((file) => ({ path: file })),
  112. baseHref,
  113. };
  114. }
  115. }
  116. if (inline === true) {
  117. i18n.inlineLocales.add(i18n.sourceLocale);
  118. Object.keys(i18n.locales).forEach(locale => i18n.inlineLocales.add(locale));
  119. } else if (inline) {
  120. for (const locale of inline) {
  121. if (!i18n.locales[locale] && i18n.sourceLocale !== locale) {
  122. throw new Error(`Requested locale '${locale}' is not defined for the project.`);
  123. }
  124. i18n.inlineLocales.add(locale);
  125. }
  126. }
  127. return i18n;
  128. }
  129. export async function configureI18nBuild<T extends BrowserBuilderSchema | ServerBuilderSchema>(
  130. context: BuilderContext,
  131. options: T,
  132. ): Promise<{
  133. buildOptions: T;
  134. i18n: I18nOptions;
  135. }> {
  136. if (!context.target) {
  137. throw new Error('The builder requires a target.');
  138. }
  139. const buildOptions = { ...options };
  140. const tsConfig = readTsconfig(buildOptions.tsConfig, context.workspaceRoot);
  141. const usingIvy = tsConfig.options.enableIvy !== false;
  142. const metadata = await context.getProjectMetadata(context.target);
  143. const i18n = createI18nOptions(metadata, buildOptions.localize);
  144. // Until 11.0, support deprecated i18n options when not using new localize option
  145. // i18nFormat is automatically calculated
  146. if (buildOptions.localize === undefined && usingIvy) {
  147. mergeDeprecatedI18nOptions(i18n, buildOptions.i18nLocale, buildOptions.i18nFile);
  148. } else if (buildOptions.localize !== undefined && !usingIvy) {
  149. if (
  150. buildOptions.localize === true ||
  151. (Array.isArray(buildOptions.localize) && buildOptions.localize.length > 1)
  152. ) {
  153. throw new Error(
  154. `Localization with multiple locales in one build is not supported with View Engine.`,
  155. );
  156. }
  157. for (const deprecatedOption of ['i18nLocale', 'i18nFormat', 'i18nFile']) {
  158. // tslint:disable-next-line: no-any
  159. if (typeof (buildOptions as any)[deprecatedOption] !== 'undefined') {
  160. context.logger.warn(
  161. `Option 'localize' and deprecated '${deprecatedOption}' found. Using 'localize'.`,
  162. );
  163. }
  164. }
  165. if (
  166. buildOptions.localize === false ||
  167. (Array.isArray(buildOptions.localize) && buildOptions.localize.length === 0)
  168. ) {
  169. buildOptions.i18nFile = undefined;
  170. buildOptions.i18nLocale = undefined;
  171. buildOptions.i18nFormat = undefined;
  172. }
  173. }
  174. // Clear deprecated options when using Ivy to prevent unintended behavior
  175. if (usingIvy) {
  176. buildOptions.i18nFile = undefined;
  177. buildOptions.i18nFormat = undefined;
  178. buildOptions.i18nLocale = undefined;
  179. }
  180. if (i18n.inlineLocales.size > 0) {
  181. const projectRoot = path.join(context.workspaceRoot, (metadata.root as string) || '');
  182. const localeDataBasePath = findLocaleDataBasePath(projectRoot);
  183. if (!localeDataBasePath) {
  184. throw new Error(
  185. `Unable to find locale data within '@angular/common'. Please ensure '@angular/common' is installed.`,
  186. );
  187. }
  188. // Load locales
  189. const loader = await createTranslationLoader();
  190. const usedFormats = new Set<string>();
  191. for (const [locale, desc] of Object.entries(i18n.locales)) {
  192. if (!i18n.inlineLocales.has(locale)) {
  193. continue;
  194. }
  195. let localeDataPath = findLocaleDataPath(locale, localeDataBasePath);
  196. if (!localeDataPath) {
  197. const [first] = locale.split('-');
  198. if (first) {
  199. localeDataPath = findLocaleDataPath(first.toLowerCase(), localeDataBasePath);
  200. if (localeDataPath) {
  201. context.logger.warn(
  202. `Locale data for '${locale}' cannot be found. Using locale data for '${first}'.`,
  203. );
  204. }
  205. }
  206. }
  207. if (!localeDataPath) {
  208. context.logger.warn(
  209. `Locale data for '${locale}' cannot be found. No locale data will be included for this locale.`,
  210. );
  211. } else {
  212. desc.dataPath = localeDataPath;
  213. }
  214. if (!desc.files.length) {
  215. continue;
  216. }
  217. for (const file of desc.files) {
  218. const loadResult = loader(path.join(context.workspaceRoot, file.path));
  219. for (const diagnostics of loadResult.diagnostics.messages) {
  220. if (diagnostics.type === 'error') {
  221. throw new Error(
  222. `Error parsing translation file '${file.path}': ${diagnostics.message}`,
  223. );
  224. } else {
  225. context.logger.warn(`WARNING [${file.path}]: ${diagnostics.message}`);
  226. }
  227. }
  228. if (loadResult.locale !== undefined && loadResult.locale !== locale) {
  229. context.logger.warn(
  230. `WARNING [${file.path}]: File target locale ('${loadResult.locale}') does not match configured locale ('${locale}')`,
  231. );
  232. }
  233. usedFormats.add(loadResult.format);
  234. if (usedFormats.size > 1 && tsConfig.options.enableI18nLegacyMessageIdFormat !== false) {
  235. // This limitation is only for legacy message id support (defaults to true as of 9.0)
  236. throw new Error(
  237. 'Localization currently only supports using one type of translation file format for the entire application.',
  238. );
  239. }
  240. file.format = loadResult.format;
  241. file.integrity = loadResult.integrity;
  242. if (desc.translation) {
  243. // Merge translations
  244. for (const [id, message] of Object.entries(loadResult.translations)) {
  245. if (desc.translation[id] !== undefined) {
  246. context.logger.warn(
  247. `WARNING [${file.path}]: Duplicate translations for message '${id}' when merging`,
  248. );
  249. }
  250. desc.translation[id] = message;
  251. }
  252. } else {
  253. // First or only translation file
  254. desc.translation = loadResult.translations;
  255. }
  256. }
  257. }
  258. // Legacy message id's require the format of the translations
  259. if (usedFormats.size > 0) {
  260. buildOptions.i18nFormat = [...usedFormats][0];
  261. }
  262. // Provide support for using the Ivy i18n options with VE
  263. if (!usingIvy) {
  264. i18n.veCompatLocale = buildOptions.i18nLocale = [...i18n.inlineLocales][0];
  265. if (buildOptions.i18nLocale !== i18n.sourceLocale) {
  266. if (i18n.locales[buildOptions.i18nLocale].files.length > 1) {
  267. throw new Error(
  268. 'Localization with View Engine only supports using a single translation file per locale.',
  269. );
  270. }
  271. buildOptions.i18nFile = i18n.locales[buildOptions.i18nLocale].files[0].path;
  272. }
  273. // Clear inline locales to prevent any new i18n related processing
  274. i18n.inlineLocales.clear();
  275. // Update the output path to include the locale to mimic Ivy localize behavior
  276. buildOptions.outputPath = path.join(buildOptions.outputPath, buildOptions.i18nLocale);
  277. }
  278. }
  279. // If inlining store the output in a temporary location to facilitate post-processing
  280. if (i18n.shouldInline) {
  281. const tempPath = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'angular-cli-i18n-'));
  282. buildOptions.outputPath = tempPath;
  283. // Remove temporary directory used for i18n processing
  284. process.on('exit', () => {
  285. try {
  286. rimraf.sync(tempPath);
  287. } catch {}
  288. });
  289. }
  290. return { buildOptions, i18n };
  291. }
  292. function mergeDeprecatedI18nOptions(
  293. i18n: I18nOptions,
  294. i18nLocale: string | undefined,
  295. i18nFile: string | undefined,
  296. ): I18nOptions {
  297. if (i18nFile !== undefined && i18nLocale === undefined) {
  298. throw new Error(`Option 'i18nFile' cannot be used without the 'i18nLocale' option.`);
  299. }
  300. if (i18nLocale !== undefined) {
  301. i18n.inlineLocales.clear();
  302. i18n.inlineLocales.add(i18nLocale);
  303. if (i18nFile !== undefined) {
  304. i18n.locales[i18nLocale] = { files: [{ path: i18nFile }], baseHref: '' };
  305. } else {
  306. // If no file, treat the locale as the source locale
  307. // This mimics deprecated behavior
  308. i18n.sourceLocale = i18nLocale;
  309. i18n.locales[i18nLocale] = { files: [], baseHref: '' };
  310. }
  311. i18n.flatOutput = true;
  312. }
  313. return i18n;
  314. }
  315. function findLocaleDataBasePath(projectRoot: string): string | null {
  316. try {
  317. const commonPath = path.dirname(
  318. require.resolve('@angular/common/package.json', { paths: [projectRoot] }),
  319. );
  320. const localesPath = path.join(commonPath, 'locales/global');
  321. if (!fs.existsSync(localesPath)) {
  322. return null;
  323. }
  324. return localesPath;
  325. } catch {
  326. return null;
  327. }
  328. }
  329. function findLocaleDataPath(locale: string, basePath: string): string | null {
  330. // Remove private use subtags
  331. const scrubbedLocale = locale.replace(/-x(-[a-zA-Z0-9]{1,8})+$/, '');
  332. const localeDataPath = path.join(basePath, scrubbedLocale + '.js');
  333. if (!fs.existsSync(localeDataPath)) {
  334. if (scrubbedLocale === 'en-US') {
  335. // fallback to known existing en-US locale data as of 9.0
  336. return findLocaleDataPath('en-US-POSIX', basePath);
  337. }
  338. return null;
  339. }
  340. return localeDataPath;
  341. }