-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Expand file tree
/
Copy pathsetup.ts
More file actions
275 lines (248 loc) · 9.2 KB
/
setup.ts
File metadata and controls
275 lines (248 loc) · 9.2 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
import express from 'express';
import { dirname, resolve } from 'node:path';
import { getGlobalVariable } from '../../utils/env';
import { appendToFile, copyFile, createDir, replaceInFile, writeFile } from '../../utils/fs';
import { installPackage } from '../../utils/packages';
import { updateJsonFile } from '../../utils/project';
import { readNgVersion } from '../../utils/version';
import { Server } from 'node:http';
import { AddressInfo } from 'node:net';
import type { Page } from 'puppeteer';
// Configurations for each locale.
const translationFile = 'src/locale/messages.xlf';
export const baseDir = 'dist/test-project/browser';
export const langTranslations = [
{
lang: 'en-US',
outputPath: `${baseDir}/en-US`,
translation: {
helloPartial: 'Hello',
hello: 'Hello i18n!',
plural: 'Updated 3 minutes ago',
date: 'January',
},
},
{
lang: 'fr',
outputPath: `${baseDir}/fr`,
translation: {
helloPartial: 'Bonjour',
hello: 'Bonjour i18n!',
plural: 'Mis à jour il y a 3 minutes',
date: 'janvier',
},
translationReplacements: [
['Hello', 'Bonjour'],
['Updated', 'Mis à jour'],
['just now', 'juste maintenant'],
['one minute ago', 'il y a une minute'],
[/other {/g, 'other {il y a '],
['minutes ago', 'minutes'],
],
},
{
lang: 'de',
outputPath: `${baseDir}/de`,
translation: {
helloPartial: 'Hallo',
hello: 'Hallo i18n!',
plural: 'Aktualisiert vor 3 Minuten',
date: 'Januar',
},
translationReplacements: [
['Hello', 'Hallo'],
['Updated', 'Aktualisiert'],
['just now', 'gerade jetzt'],
['one minute ago', 'vor einer Minute'],
[/other {/g, 'other {vor '],
['minutes ago', 'Minuten'],
],
},
];
export const sourceLocale = langTranslations[0].lang;
export async function browserCheck(page: Page, lang: string) {
const translation = langTranslations.find((t) => t.lang === lang)?.translation;
if (!translation) {
throw new Error(`Could not find translation for language '${lang}'`);
}
const getParagraph = async (id: string) => page.$eval(`p#${id}`, (el) => el.textContent?.trim());
const hello = await getParagraph('hello');
if (hello !== translation.hello) {
throw new Error(`Expected 'hello' to be '${translation.hello}', but got '${hello}'.`);
}
const locale = await getParagraph('locale');
if (locale !== lang) {
throw new Error(`Expected 'locale' to be '${lang}', but got '${locale}'.`);
}
const date = await getParagraph('date');
if (date !== translation.date) {
throw new Error(`Expected 'date' to be '${translation.date}', but got '${date}'.`);
}
const plural = await getParagraph('plural');
if (plural !== translation.plural) {
throw new Error(`Expected 'plural' to be '${translation.plural}', but got '${plural}'.`);
}
}
export interface ExternalServer {
readonly server: Server;
readonly port: number;
readonly url: string;
}
/**
* Create an `express` `http.Server` listening on a random port.
*
* Call .close() on the server return value to close the server.
*/
export async function externalServer(outputPath: string, baseUrl = '/'): Promise<ExternalServer> {
const app = express();
app.use(baseUrl, express.static(resolve(outputPath)));
return new Promise((resolve) => {
const server = app.listen(0, 'localhost', () => {
const { port } = server.address() as AddressInfo;
resolve({
server,
port,
url: `http://localhost:${port}${baseUrl}`,
});
});
});
}
export const baseHrefs: { [l: string]: string } = {
'en-US': '/en/',
fr: '/fr-FR/',
de: '',
};
export async function setupI18nConfig() {
// Add component with i18n content, both translations and localeData (plural, dates).
await writeFile(
'src/app/app.ts',
`
import { Component, Inject, LOCALE_ID } from '@angular/core';
import { DatePipe } from '@angular/common';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [DatePipe, RouterOutlet],
templateUrl: './app.html'
})
export class App {
constructor(@Inject(LOCALE_ID) public locale: string) { }
title = 'i18n';
jan = new Date(2000, 0, 1);
minutes = 3;
}
`,
);
await writeFile(
`src/app/app.html`,
`
<p id="hello" i18n="An introduction header for this sample">Hello {{ title }}! </p>
<p id="locale">{{ locale }}</p>
<p id="date">{{ jan | date : 'LLLL' }}</p>
<p id="plural" i18n>Updated {minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}</p>
<router-outlet></router-outlet>
`,
);
await createDir(dirname(translationFile));
await writeFile(
translationFile,
`
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en-US" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="4286451273117902052" datatype="html">
<source>Hello <x id="INTERPOLATION" equiv-text="{{ title }}"/>! </source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.html</context>
<context context-type="linenumber">2,3</context>
</context-group>
<note priority="1" from="description">An introduction header for this sample</note>
</trans-unit>
<trans-unit id="4606963464835766483" datatype="html">
<source>Updated <x id="ICU" equiv-text="{minutes, plural, =0 {just now} =1 {one minute ago} other {{{minutes}} minutes ago}}" xid="1887283401472369100"/></source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.html</context>
<context context-type="linenumber">5,6</context>
</context-group>
</trans-unit>
<trans-unit id="2002272803511843863" datatype="html">
<source>{VAR_PLURAL, plural, =0 {just now} =1 {one minute ago} other {<x id="INTERPOLATION"/> minutes ago}}</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/app.html</context>
<context context-type="linenumber">5,6</context>
</context-group>
</trans-unit>
</body>
</file>
</xliff>`,
);
// Add a dynamic import to ensure syntax is supported
// ng serve support: https://github.com/angular/angular-cli/issues/16248
await writeFile('src/app/dynamic.ts', `export const abc = 5;`);
await appendToFile(
'src/app/app.ts',
`
(async () => { await import('./dynamic'); })();
`,
);
// Update angular.json to build, serve, and test each locale.
await updateJsonFile('angular.json', (workspaceJson) => {
const appProject = workspaceJson.projects['test-project'];
const appArchitect = workspaceJson.projects['test-project'].architect;
const buildConfigs = appArchitect['build'].configurations;
const serveConfigs = appArchitect['serve'].configurations;
appArchitect['build'].defaultConfiguration = undefined;
// Always error on missing translations.
appArchitect['build'].options.optimization = true;
appArchitect['build'].options.aot = true;
appArchitect['build'].options.i18nMissingTranslation = 'error';
appArchitect['build'].options.sourceMap = true;
appArchitect['build'].options.outputHashing = 'none';
const useWebpackBuilder = !getGlobalVariable('argv')['esbuild'];
if (useWebpackBuilder) {
appArchitect['build'].options.buildOptimizer = true;
appArchitect['build'].options.vendorChunk = true;
}
// Enable localization for all locales
appArchitect['build'].options.localize = true;
// Add i18n config items (app, build, serve, e2e).
// tslint:disable-next-line: no-any
const i18n: Record<string, any> = (appProject.i18n = { locales: {} });
for (const { lang } of langTranslations) {
if (lang === sourceLocale) {
i18n.sourceLocale = lang;
} else {
i18n.locales[lang] = `src/locale/messages.${lang}.xlf`;
}
buildConfigs[lang] = { localize: [lang] };
serveConfigs[lang] = { buildTarget: `test-project:build:${lang}` };
}
});
// Install the localize package if using ivy
let localizeVersion = '@angular/localize@' + readNgVersion();
if (getGlobalVariable('argv')['ng-snapshots']) {
localizeVersion = require('../../ng-snapshot/package.json').dependencies['@angular/localize'];
}
await installPackage(localizeVersion);
// Make translations for each language.
for (const { lang, translationReplacements } of langTranslations) {
if (lang != sourceLocale) {
await copyFile(translationFile, `src/locale/messages.${lang}.xlf`);
for (const replacements of translationReplacements!) {
await replaceInFile(
`src/locale/messages.${lang}.xlf`,
new RegExp(replacements[0], 'g'),
replacements[1] as string,
);
}
for (const replacement of [[/source/g, 'target']]) {
await replaceInFile(
`src/locale/messages.${lang}.xlf`,
new RegExp(replacement[0], 'g'),
replacement[1] as string,
);
}
}
}
}