-
Notifications
You must be signed in to change notification settings - Fork 618
/
Copy pathAssetProcessor.ts
475 lines (407 loc) · 15.7 KB
/
AssetProcessor.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import type * as Webpack from 'webpack';
import { Constants } from './utilities/Constants';
import type { ILocaleElementMap } from './interfaces';
import type { LocalizationPlugin, IStringSerialNumberData as IStringData } from './LocalizationPlugin';
interface IReconstructionElement {
kind: 'static' | 'localized' | 'dynamic';
}
interface IStaticReconstructionElement extends IReconstructionElement {
kind: 'static';
staticString: string;
}
interface ILocalizedReconstructionElement extends IReconstructionElement {
kind: 'localized';
values: ILocaleElementMap;
size: number;
stringName: string;
escapedBackslash: string;
locFilePath: string;
}
interface IDynamicReconstructionElement extends IReconstructionElement {
kind: 'dynamic';
valueFn: (locale: string, token: string | undefined) => string;
size: number;
escapedBackslash: string;
token?: string;
}
interface IParseResult {
issues: string[];
reconstructionSeries: IReconstructionElement[];
}
interface IReconstructedString {
source: string;
size: number;
}
interface ILocalizedReconstructionResult {
result: Map<string, IReconstructedString>;
issues: string[];
}
interface INonLocalizedReconstructionResult {
result: IReconstructedString;
issues: string[];
}
export interface IProcessAssetOptionsBase {
plugin: LocalizationPlugin;
compilation: Webpack.compilation.Compilation;
assetName: string;
asset: IAsset;
chunk: Webpack.compilation.Chunk;
noStringsLocaleName: string;
chunkHasLocalizedModules: (chunk: Webpack.compilation.Chunk) => boolean;
}
export interface IProcessNonLocalizedAssetOptions extends IProcessAssetOptionsBase {}
export interface IProcessLocalizedAssetOptions extends IProcessAssetOptionsBase {
locales: Set<string>;
fillMissingTranslationStrings: boolean;
defaultLocale: string;
}
export interface IAsset {
size(): number;
source(): string;
}
export interface IProcessAssetResult {
filename: string;
asset: IAsset;
}
export const PLACEHOLDER_REGEX: RegExp = new RegExp(
`${Constants.STRING_PLACEHOLDER_PREFIX}_(\\\\*)_([A-C])(\\+[^+]+\\+)?_(\\d+)`,
'g'
);
export class AssetProcessor {
public static processLocalizedAsset(
options: IProcessLocalizedAssetOptions
): Map<string, IProcessAssetResult> {
const assetSource: string = options.asset.source();
const parsedAsset: IParseResult = AssetProcessor._parseStringToReconstructionSequence(
options.plugin,
assetSource,
this._getJsonpFunction(options.chunk, options.chunkHasLocalizedModules, options.noStringsLocaleName)
);
const reconstructedAsset: ILocalizedReconstructionResult = AssetProcessor._reconstructLocalized(
parsedAsset.reconstructionSeries,
options.locales,
options.fillMissingTranslationStrings,
options.defaultLocale,
options.asset.size()
);
const parsedAssetName: IParseResult = AssetProcessor._parseStringToReconstructionSequence(
options.plugin,
options.assetName,
() => {
throw new Error('unsupported');
}
);
const reconstructedAssetName: ILocalizedReconstructionResult = AssetProcessor._reconstructLocalized(
parsedAssetName.reconstructionSeries,
options.locales,
options.fillMissingTranslationStrings,
options.defaultLocale,
options.assetName.length
);
const result: Map<string, IProcessAssetResult> = new Map<string, IProcessAssetResult>();
for (const [locale, { source, size }] of reconstructedAsset.result) {
const newAsset: IAsset = { ...options.asset };
newAsset.source = () => source;
newAsset.size = () => size;
result.set(locale, {
filename: reconstructedAssetName.result.get(locale)!.source,
asset: newAsset
});
}
const issues: string[] = [
...parsedAsset.issues,
...reconstructedAsset.issues,
...parsedAssetName.issues,
...reconstructedAssetName.issues
];
if (issues.length > 0) {
options.compilation.errors.push(
Error(`localization:\n${issues.map((issue) => ` ${issue}`).join('\n')}`)
);
}
return result;
}
public static processNonLocalizedAsset(options: IProcessNonLocalizedAssetOptions): IProcessAssetResult {
const assetSource: string = options.asset.source();
const parsedAsset: IParseResult = AssetProcessor._parseStringToReconstructionSequence(
options.plugin,
assetSource,
this._getJsonpFunction(options.chunk, options.chunkHasLocalizedModules, options.noStringsLocaleName)
);
const reconstructedAsset: INonLocalizedReconstructionResult = AssetProcessor._reconstructNonLocalized(
parsedAsset.reconstructionSeries,
options.asset.size(),
options.noStringsLocaleName
);
const parsedAssetName: IParseResult = AssetProcessor._parseStringToReconstructionSequence(
options.plugin,
options.assetName,
() => {
throw new Error('unsupported');
}
);
const reconstructedAssetName: INonLocalizedReconstructionResult = AssetProcessor._reconstructNonLocalized(
parsedAssetName.reconstructionSeries,
options.assetName.length,
options.noStringsLocaleName
);
const issues: string[] = [
...parsedAsset.issues,
...reconstructedAsset.issues,
...parsedAssetName.issues,
...reconstructedAssetName.issues
];
if (issues.length > 0) {
options.compilation.errors.push(
Error(`localization:\n${issues.map((issue) => ` ${issue}`).join('\n')}`)
);
}
const newAsset: IAsset = { ...options.asset };
newAsset.source = () => reconstructedAsset.result.source;
newAsset.size = () => reconstructedAsset.result.size;
return {
filename: reconstructedAssetName.result.source,
asset: newAsset
};
}
private static _reconstructLocalized(
reconstructionSeries: IReconstructionElement[],
locales: Set<string>,
fillMissingTranslationStrings: boolean,
defaultLocale: string,
initialSize: number
): ILocalizedReconstructionResult {
const localizedResults: Map<string, IReconstructedString> = new Map<string, IReconstructedString>();
const issues: string[] = [];
for (const locale of locales) {
const reconstruction: string[] = [];
let sizeDiff: number = 0;
for (const element of reconstructionSeries) {
switch (element.kind) {
case 'static': {
reconstruction.push((element as IStaticReconstructionElement).staticString);
break;
}
case 'localized': {
const localizedElement: ILocalizedReconstructionElement =
element as ILocalizedReconstructionElement;
let newValue: string | undefined = localizedElement.values[locale];
if (!newValue) {
if (fillMissingTranslationStrings) {
newValue = localizedElement.values[defaultLocale];
} else {
issues.push(
`The string "${localizedElement.stringName}" in "${localizedElement.locFilePath}" is missing in ` +
`the locale ${locale}`
);
newValue = '-- MISSING STRING --';
}
}
const escapedBackslash: string = localizedElement.escapedBackslash || '\\';
// Replace backslashes with the properly escaped backslash
newValue = newValue.replace(/\\/g, escapedBackslash);
// @todo: look into using JSON.parse(...) to get the escaping characters
const escapingCharacterSequence: string = escapedBackslash.substr(escapedBackslash.length / 2);
// Ensure the the quotemark, apostrophe, tab, and newline characters are properly escaped
newValue = newValue.replace(/\r/g, `${escapingCharacterSequence}r`);
newValue = newValue.replace(/\n/g, `${escapingCharacterSequence}n`);
newValue = newValue.replace(/\t/g, `${escapingCharacterSequence}t`);
newValue = newValue.replace(/\"/g, `${escapingCharacterSequence}u0022`);
newValue = newValue.replace(/\'/g, `${escapingCharacterSequence}u0027`);
reconstruction.push(newValue);
sizeDiff += newValue.length - localizedElement.size;
break;
}
case 'dynamic': {
const dynamicElement: IDynamicReconstructionElement = element as IDynamicReconstructionElement;
const newValue: string = dynamicElement.valueFn(locale, dynamicElement.token);
reconstruction.push(newValue);
sizeDiff += newValue.length - dynamicElement.size;
break;
}
}
}
const newAssetSource: string = reconstruction.join('');
localizedResults.set(locale, {
source: newAssetSource,
size: initialSize + sizeDiff
});
}
return {
issues,
result: localizedResults
};
}
private static _reconstructNonLocalized(
reconstructionSeries: IReconstructionElement[],
initialSize: number,
noStringsLocaleName: string
): INonLocalizedReconstructionResult {
const issues: string[] = [];
const reconstruction: string[] = [];
let sizeDiff: number = 0;
for (const element of reconstructionSeries) {
switch (element.kind) {
case 'static': {
reconstruction.push((element as IStaticReconstructionElement).staticString);
break;
}
case 'localized': {
const localizedElement: ILocalizedReconstructionElement =
element as ILocalizedReconstructionElement;
issues.push(
`The string "${localizedElement.stringName}" in "${localizedElement.locFilePath}" appeared in an asset ` +
'that is not expected to contain localized resources.'
);
const newValue: string = '-- NOT EXPECTED TO BE LOCALIZED --';
reconstruction.push(newValue);
sizeDiff += newValue.length - localizedElement.size;
break;
}
case 'dynamic': {
const dynamicElement: IDynamicReconstructionElement = element as IDynamicReconstructionElement;
const newValue: string = dynamicElement.valueFn(noStringsLocaleName, dynamicElement.token);
reconstruction.push(newValue);
sizeDiff += newValue.length - dynamicElement.size;
break;
}
}
}
const newAssetSource: string = reconstruction.join('');
return {
issues,
result: {
source: newAssetSource,
size: initialSize + sizeDiff
}
};
}
private static _parseStringToReconstructionSequence(
plugin: LocalizationPlugin,
source: string,
jsonpFunction: (locale: string, chunkIdToken: string | undefined) => string
): IParseResult {
const issues: string[] = [];
const reconstructionSeries: IReconstructionElement[] = [];
let lastIndex: number = 0;
let regexResult: RegExpExecArray | null;
while ((regexResult = PLACEHOLDER_REGEX.exec(source))) {
// eslint-disable-line no-cond-assign
const staticElement: IStaticReconstructionElement = {
kind: 'static',
staticString: source.substring(lastIndex, regexResult.index)
};
reconstructionSeries.push(staticElement);
const [placeholder, escapedBackslash, elementLabel, token, placeholderSerialNumber] = regexResult;
let localizedReconstructionElement: IReconstructionElement;
switch (elementLabel) {
case Constants.STRING_PLACEHOLDER_LABEL: {
const stringData: IStringData | undefined = plugin.getDataForSerialNumber(placeholderSerialNumber);
if (!stringData) {
issues.push(`Missing placeholder ${placeholder}`);
const brokenLocalizedElement: IStaticReconstructionElement = {
kind: 'static',
staticString: placeholder
};
localizedReconstructionElement = brokenLocalizedElement;
} else {
const localizedElement: ILocalizedReconstructionElement = {
kind: 'localized',
values: stringData.values,
size: placeholder.length,
locFilePath: stringData.locFilePath,
escapedBackslash: escapedBackslash,
stringName: stringData.stringName
};
localizedReconstructionElement = localizedElement;
}
break;
}
case Constants.LOCALE_NAME_PLACEHOLDER_LABEL: {
const dynamicElement: IDynamicReconstructionElement = {
kind: 'dynamic',
valueFn: (locale: string) => locale,
size: placeholder.length,
escapedBackslash: escapedBackslash
};
localizedReconstructionElement = dynamicElement;
break;
}
case Constants.JSONP_PLACEHOLDER_LABEL: {
const dynamicElement: IDynamicReconstructionElement = {
kind: 'dynamic',
valueFn: jsonpFunction,
size: placeholder.length,
escapedBackslash: escapedBackslash,
token: token.substring(1, token.length - 1)
};
localizedReconstructionElement = dynamicElement;
break;
}
default: {
throw new Error(`Unexpected label ${elementLabel}`);
}
}
reconstructionSeries.push(localizedReconstructionElement);
lastIndex = regexResult.index + placeholder.length;
}
const lastElement: IStaticReconstructionElement = {
kind: 'static',
staticString: source.substr(lastIndex)
};
reconstructionSeries.push(lastElement);
return {
issues,
reconstructionSeries
};
}
private static _getJsonpFunction(
chunk: Webpack.compilation.Chunk,
chunkHasLocalizedModules: (chunk: Webpack.compilation.Chunk) => boolean,
noStringsLocaleName: string
): (locale: string, chunkIdToken: string | undefined) => string {
const idsWithStrings: Set<number | string> = new Set<number | string>();
const idsWithoutStrings: Set<number | string> = new Set<number | string>();
const asyncChunks: Set<Webpack.compilation.Chunk> = chunk.getAllAsyncChunks();
for (const asyncChunk of asyncChunks) {
const chunkId: number | string | null = asyncChunk.id;
if (chunkId === null || chunkId === undefined) {
throw new Error(`Chunk "${asyncChunk.name}"'s ID is null or undefined.`);
}
if (chunkHasLocalizedModules(asyncChunk)) {
idsWithStrings.add(chunkId);
} else {
idsWithoutStrings.add(chunkId);
}
}
if (idsWithStrings.size === 0) {
return () => JSON.stringify(noStringsLocaleName);
} else if (idsWithoutStrings.size === 0) {
return (locale: string) => JSON.stringify(locale);
} else {
// Generate an array [<locale>, <nostrings locale>] and an object that is used as an indexer into that
// object that maps chunk IDs to 0s for chunks with localized strings and 1s for chunks without localized
// strings
//
// This can be improved in the future. We can maybe sort the chunks such that the chunks below a certain ID
// number are localized and the those above are not.
const chunkMapping: { [chunkId: string]: number } = {};
for (const idWithStrings of idsWithStrings) {
chunkMapping[idWithStrings] = 0;
}
for (const idWithoutStrings of idsWithoutStrings) {
chunkMapping[idWithoutStrings] = 1;
}
return (locale: string, chunkIdToken: string | undefined) => {
if (!locale) {
throw new Error('Missing locale name.');
}
return `(${JSON.stringify([locale, noStringsLocaleName])})[${JSON.stringify(
chunkMapping
)}[${chunkIdToken}]]`;
};
}
}
}