-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathbuild-optimizer_spec.ts
356 lines (309 loc) · 12.8 KB
/
build-optimizer_spec.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
/**
* @license
* Copyright Google Inc. 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
*/
// tslint:disable:no-big-function
// tslint:disable-next-line:no-implicit-dependencies
import { tags } from '@angular-devkit/core';
import { RawSourceMap } from 'source-map';
import { TransformJavascriptOutput } from '../helpers/transform-javascript';
import { buildOptimizer } from './build-optimizer';
describe('build-optimizer', () => {
const imports = 'import { Injectable, Input, Component } from \'@angular/core\';';
const clazz = 'var Clazz = (function () { function Clazz() { } return Clazz; }());';
const decorators = 'Clazz.decorators = [ { type: Injectable } ];';
describe('basic functionality', () => {
it('applies scrub-file and prefix-functions to side-effect free modules', () => {
const input = tags.stripIndent`
${imports}
var ChangeDetectionStrategy;
(function (ChangeDetectionStrategy) {
ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
${clazz}
${decorators}
Clazz.propDecorators = { 'ngIf': [{ type: Input }] };
Clazz.ctorParameters = function () { return [{type: Injectable}]; };
var ComponentClazz = (function () {
function ComponentClazz() { }
__decorate([
Input(),
__metadata("design:type", Object)
], Clazz.prototype, "selected", void 0);
ComponentClazz = __decorate([
Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
}),
__metadata("design:paramtypes", [Injectable])
], ComponentClazz);
return ComponentClazz;
}());
var RenderType_MdOption = ɵcrt({ encapsulation: 2, styles: styles_MdOption});
`;
const output = tags.oneLine`
${imports}
var ChangeDetectionStrategy = /*@__PURE__*/ (function (ChangeDetectionStrategy) {
ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
return ChangeDetectionStrategy;
})({});
var Clazz = /*@__PURE__*/ (function () { function Clazz() { } return Clazz; }());
var ComponentClazz = /*@__PURE__*/ (function () {
function ComponentClazz() { }
return ComponentClazz;
}());
var RenderType_MdOption = /*@__PURE__*/ ɵcrt({ encapsulation: 2, styles: styles_MdOption });
`;
// Check Angular 4/5 and unix/windows paths.
const inputPaths = [
'/node_modules/@angular/core/@angular/core.es5.js',
'/node_modules/@angular/core/esm5/core.js',
'\\node_modules\\@angular\\core\\@angular\\core.es5.js',
'\\node_modules\\@angular\\core\\esm5\\core.js',
'/project/file.ngfactory.js',
'/project/file.ngstyle.js',
];
inputPaths.forEach((inputFilePath) => {
const boOutput = buildOptimizer({ content: input, inputFilePath });
expect(tags.oneLine`${boOutput.content}`).toEqual(output);
expect(boOutput.emitSkipped).toEqual(false);
});
});
it('supports flagging module as side-effect free', () => {
const output = tags.oneLine`
var RenderType_MdOption = /*@__PURE__*/ ɵcrt({ encapsulation: 2, styles: styles_MdOption });
`;
const input = tags.stripIndent`
var RenderType_MdOption = ɵcrt({ encapsulation: 2, styles: styles_MdOption});
`;
const boOutput = buildOptimizer({ content: input, isSideEffectFree: true });
expect(tags.oneLine`${boOutput.content}`).toEqual(output);
expect(boOutput.emitSkipped).toEqual(false);
});
it('should not add pure comments to tslib helpers', () => {
const input = tags.stripIndent`
class LanguageState {
}
LanguageState.ctorParameters = () => [
{ type: TranslateService },
{ type: undefined, decorators: [{ type: Inject, args: [LANGUAGE_CONFIG,] }] }
];
__decorate([
Action(CheckLanguage),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", void 0)
], LanguageState.prototype, "checkLanguage", null);
`;
const output = tags.oneLine`
let LanguageState = /*@__PURE__*/ (() => {
class LanguageState {
}
__decorate([
Action(CheckLanguage),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", void 0)
], LanguageState.prototype, "checkLanguage", null);
return LanguageState;
})();
`;
const boOutput = buildOptimizer({ content: input, isSideEffectFree: true });
expect(tags.oneLine`${boOutput.content}`).toEqual(output);
expect(boOutput.emitSkipped).toEqual(false);
});
it('should not add pure comments to tslib helpers with $ and number suffix', () => {
const input = tags.stripIndent`
class LanguageState {
}
LanguageState.ctorParameters = () => [
{ type: TranslateService },
{ type: undefined, decorators: [{ type: Inject, args: [LANGUAGE_CONFIG,] }] }
];
__decorate$1([
Action(CheckLanguage),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", void 0)
], LanguageState.prototype, "checkLanguage", null);
`;
const output = tags.oneLine`
let LanguageState = /*@__PURE__*/ (() => {
class LanguageState {
}
__decorate$1([
Action(CheckLanguage),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object]),
__metadata("design:returntype", void 0)
], LanguageState.prototype, "checkLanguage", null);
return LanguageState;
})();
`;
const boOutput = buildOptimizer({ content: input, isSideEffectFree: true });
expect(tags.oneLine`${boOutput.content}`).toEqual(output);
expect(boOutput.emitSkipped).toEqual(false);
});
it('should not wrap classes which had all static properties dropped in IIFE', () => {
const classDeclaration = tags.oneLine`
import { Injectable } from '@angular/core';
class Platform {
constructor(_doc) {
}
init() {
}
}
`;
const input = tags.oneLine`
${classDeclaration}
Platform.decorators = [
{ type: Injectable }
];
/** @nocollapse */
Platform.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT] }] }
];
`;
const boOutput = buildOptimizer({ content: input, isSideEffectFree: true });
expect(tags.oneLine`${boOutput.content}`).toEqual(classDeclaration);
expect(boOutput.emitSkipped).toEqual(false);
});
});
describe('resilience', () => {
it('doesn\'t process files with invalid syntax by default', () => {
const input = tags.oneLine`
))))invalid syntax
${clazz}
Clazz.decorators = [ { type: Injectable } ];
`;
const boOutput = buildOptimizer({ content: input });
expect(boOutput.content).toBeFalsy();
expect(boOutput.emitSkipped).toEqual(true);
});
it('throws on files with invalid syntax in strict mode', () => {
const input = tags.oneLine`
))))invalid syntax
${clazz}
Clazz.decorators = [ { type: Injectable } ];
`;
expect(() => buildOptimizer({ content: input, strict: true })).toThrow();
});
// TODO: re-enable this test when updating to TypeScript >2.9.1.
// The `prefix-classes` tests will also need to be adjusted.
// See https://github.com/angular/devkit/pull/998#issuecomment-393867606 for more info.
xit(`doesn't exceed call stack size when type checking very big classes`, () => {
// BigClass with a thousand methods.
// Clazz is included with ctorParameters to trigger transforms with type checking.
const input = `
var BigClass = /** @class */ (function () {
function BigClass() {
}
${Array.from(new Array(1000)).map((_v, i) =>
`BigClass.prototype.method${i} = function () { return this.myVar; };`,
).join('\n')}
return BigClass;
}());
${clazz}
Clazz.ctorParameters = function () { return []; };
`;
let boOutput: TransformJavascriptOutput;
expect(() => {
boOutput = buildOptimizer({ content: input });
expect(boOutput.emitSkipped).toEqual(false);
}).not.toThrow();
});
});
describe('whitelisted modules', () => {
// This statement is considered pure by getPrefixFunctionsTransformer on whitelisted modules.
const input = 'console.log(42);';
const output = '/*@__PURE__*/ console.log(42);';
it('should process whitelisted modules', () => {
const inputFilePath = '/node_modules/@angular/core/@angular/core.es5.js';
const boOutput = buildOptimizer({ content: input, inputFilePath });
expect(boOutput.content).toContain(output);
expect(boOutput.emitSkipped).toEqual(false);
});
it('should not process non-whitelisted modules', () => {
const inputFilePath = '/node_modules/other-package/core.es5.js';
const boOutput = buildOptimizer({ content: input, inputFilePath });
expect(boOutput.emitSkipped).toEqual(true);
});
it('should not process non-whitelisted umd modules', () => {
const inputFilePath = '/node_modules/other_lib/index.js';
const boOutput = buildOptimizer({ content: input, inputFilePath });
expect(boOutput.emitSkipped).toEqual(true);
});
});
describe('sourcemaps', () => {
const transformableInput = tags.oneLine`
${imports}
${clazz}
${decorators}
`;
it('doesn\'t produce sourcemaps by default', () => {
expect(buildOptimizer({ content: transformableInput }).sourceMap).toBeFalsy();
});
it('produces sourcemaps', () => {
expect(buildOptimizer(
{ content: transformableInput, emitSourceMap: true },
).sourceMap).toBeTruthy();
});
// TODO: re-enable this test, it was temporarily disabled as part of
// https://github.com/angular/devkit/pull/842
xit('doesn\'t produce sourcemaps when emitting was skipped', () => {
const ignoredInput = tags.oneLine`
var Clazz = (function () { function Clazz() { } return Clazz; }());
`;
const invalidInput = tags.oneLine`
))))invalid syntax
${clazz}
Clazz.decorators = [ { type: Injectable } ];
`;
const ignoredOutput = buildOptimizer({ content: ignoredInput, emitSourceMap: true });
expect(ignoredOutput.emitSkipped).toBeTruthy();
expect(ignoredOutput.sourceMap).toBeFalsy();
const invalidOutput = buildOptimizer({ content: invalidInput, emitSourceMap: true });
expect(invalidOutput.emitSkipped).toBeTruthy();
expect(invalidOutput.sourceMap).toBeFalsy();
});
it('emits sources content', () => {
const sourceMap = buildOptimizer(
{ content: transformableInput, emitSourceMap: true },
).sourceMap as RawSourceMap;
const sourceContent = sourceMap.sourcesContent as string[];
expect(sourceContent[0]).toEqual(transformableInput);
});
it('uses empty strings if inputFilePath and outputFilePath is not provided', () => {
const { content, sourceMap } = buildOptimizer(
{ content: transformableInput, emitSourceMap: true });
if (!sourceMap) {
throw new Error('sourceMap was not generated.');
}
expect(sourceMap.file).toEqual('');
expect(sourceMap.sources[0]).toEqual('');
expect(content).not.toContain(`sourceMappingURL`);
});
it('uses inputFilePath and outputFilePath if provided', () => {
const inputFilePath = '/path/to/file.js';
const outputFilePath = '/path/to/file.bo.js';
const { content, sourceMap } = buildOptimizer({
content: transformableInput,
emitSourceMap: true,
inputFilePath,
outputFilePath,
});
if (!sourceMap) {
throw new Error('sourceMap was not generated.');
}
expect(sourceMap.file).toEqual(outputFilePath);
expect(sourceMap.sources[0]).toEqual(inputFilePath);
expect(content).toContain(`sourceMappingURL=${outputFilePath}.map`);
});
});
});