/
JSAsset.js
286 lines (248 loc) Β· 8.15 KB
/
JSAsset.js
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
const traverse = require('@babel/traverse').default;
const codeFrame = require('@babel/code-frame').codeFrameColumns;
const collectDependencies = require('../visitors/dependencies');
const walk = require('babylon-walk');
const Asset = require('../Asset');
const babelParser = require('@babel/parser');
const insertGlobals = require('../visitors/globals');
const fsVisitor = require('../visitors/fs');
const envVisitor = require('../visitors/env');
const babel = require('../transforms/babel/transform');
const babel7 = require('../transforms/babel/babel7');
const generate = require('@babel/generator').default;
const terser = require('../transforms/terser');
const SourceMap = require('../SourceMap');
const hoist = require('../scope-hoisting/hoist');
const path = require('path');
const fs = require('../utils/fs');
const logger = require('../Logger');
const IMPORT_RE = /\b(?:import\b|export\b|require\s*\()/;
const ENV_RE = /\b(?:process\.env)\b/;
const GLOBAL_RE = /\b(?:process|__dirname|__filename|global|Buffer|define)\b/;
const FS_RE = /\breadFileSync\b/;
const SW_RE = /\bnavigator\s*\.\s*serviceWorker\s*\.\s*register\s*\(/;
const WORKER_RE = /\bnew\s*(?:Shared)?Worker\s*\(/;
const SOURCEMAP_RE = /\/\/\s*[@#]\s*sourceMappingURL\s*=\s*([^\s]+)/;
const DATA_URL_RE = /^data:[^;]+(?:;charset=[^;]+)?;base64,(.*)/;
class JSAsset extends Asset {
constructor(name, options) {
super(name, options);
this.type = 'js';
this.globals = new Map();
this.isAstDirty = false;
this.isES6Module = false;
this.outputCode = null;
this.cacheData.env = {};
this.rendition = options.rendition;
this.sourceMap = this.rendition ? this.rendition.sourceMap : null;
}
shouldInvalidate(cacheData) {
for (let key in cacheData.env) {
if (cacheData.env[key] !== process.env[key]) {
return true;
}
}
return false;
}
mightHaveDependencies() {
return (
this.isAstDirty ||
!/.js$/.test(this.name) ||
IMPORT_RE.test(this.contents) ||
GLOBAL_RE.test(this.contents) ||
SW_RE.test(this.contents) ||
WORKER_RE.test(this.contents)
);
}
async parse(code) {
return babelParser.parse(code, {
filename: this.name,
allowReturnOutsideFunction: true,
strictMode: false,
sourceType: 'module',
plugins: ['exportDefaultFrom', 'exportNamespaceFrom', 'dynamicImport']
});
}
traverse(visitor) {
return traverse(this.ast, visitor, null, this);
}
traverseFast(visitor) {
return walk.simple(this.ast, visitor, this);
}
collectDependencies() {
walk.ancestor(this.ast, collectDependencies, this);
}
async loadSourceMap() {
// Get original sourcemap if there is any
let match = this.contents.match(SOURCEMAP_RE);
if (match) {
this.contents = this.contents.replace(SOURCEMAP_RE, '');
let url = match[1];
let dataURLMatch = url.match(DATA_URL_RE);
try {
let json, filename;
if (dataURLMatch) {
filename = this.name;
json = new Buffer(dataURLMatch[1], 'base64').toString();
} else {
filename = path.join(path.dirname(this.name), url);
json = await fs.readFile(filename, 'utf8');
// Add as a dep so we watch the source map for changes.
this.addDependency(filename, {includedInParent: true});
}
this.sourceMap = JSON.parse(json);
// Attempt to read missing source contents
if (!this.sourceMap.sourcesContent) {
this.sourceMap.sourcesContent = [];
}
let missingSources = this.sourceMap.sources.slice(
this.sourceMap.sourcesContent.length
);
if (missingSources.length) {
let contents = await Promise.all(
missingSources.map(async source => {
try {
let sourceFile = path.join(
path.dirname(filename),
this.sourceMap.sourceRoot || '',
source
);
let result = await fs.readFile(sourceFile, 'utf8');
this.addDependency(sourceFile, {includedInParent: true});
return result;
} catch (err) {
logger.warn(
`Could not load source file "${source}" in source map of "${
this.relativeName
}".`
);
}
})
);
this.sourceMap.sourcesContent = this.sourceMap.sourcesContent.concat(
contents
);
}
} catch (e) {
logger.warn(
`Could not load existing sourcemap of "${this.relativeName}".`
);
}
}
}
async pretransform() {
await this.loadSourceMap();
await babel(this);
// Inline environment variables
if (this.options.target === 'browser' && ENV_RE.test(this.contents)) {
await this.parseIfNeeded();
this.traverseFast(envVisitor);
}
}
async transform() {
if (this.options.target === 'browser') {
if (this.dependencies.has('fs') && FS_RE.test(this.contents)) {
// Check if we should ignore fs calls
// See https://github.com/defunctzombie/node-browser-resolve#skip
let pkg = await this.getPackage();
let ignore = pkg && pkg.browser && pkg.browser.fs === false;
if (!ignore) {
await this.parseIfNeeded();
this.traverse(fsVisitor);
}
}
if (GLOBAL_RE.test(this.contents)) {
await this.parseIfNeeded();
walk.ancestor(this.ast, insertGlobals, this);
}
}
if (this.options.scopeHoist) {
await this.parseIfNeeded();
await this.getPackage();
this.traverse(hoist);
this.isAstDirty = true;
} else {
if (this.isES6Module) {
await babel7(this, {
internal: true,
config: {
plugins: [require('@babel/plugin-transform-modules-commonjs')]
}
});
}
}
if (this.options.minify) {
await terser(this);
}
}
async generate() {
let enableSourceMaps =
this.options.sourceMaps &&
(!this.rendition || !!this.rendition.sourceMap);
let code;
if (this.isAstDirty) {
let opts = {
sourceMaps: this.options.sourceMaps,
sourceFileName: this.relativeName
};
let generated = generate(this.ast, opts, this.contents);
if (enableSourceMaps && generated.rawMappings) {
let rawMap = new SourceMap(generated.rawMappings, {
[this.relativeName]: this.contents
});
// Check if we already have a source map (e.g. from TypeScript or CoffeeScript)
// In that case, we need to map the original source map to the babel generated one.
if (this.sourceMap) {
this.sourceMap = await new SourceMap().extendSourceMap(
this.sourceMap,
rawMap
);
} else {
this.sourceMap = rawMap;
}
}
code = generated.code;
} else {
code = this.outputCode != null ? this.outputCode : this.contents;
}
if (enableSourceMaps && !this.sourceMap) {
this.sourceMap = new SourceMap().generateEmptyMap(
this.relativeName,
this.contents
);
}
if (this.globals.size > 0) {
code = Array.from(this.globals.values()).join('\n') + '\n' + code;
if (enableSourceMaps) {
if (!(this.sourceMap instanceof SourceMap)) {
this.sourceMap = await new SourceMap().addMap(this.sourceMap);
}
this.sourceMap.offset(this.globals.size);
}
}
return {
js: code,
map: this.sourceMap
};
}
generateErrorMessage(err) {
const loc = err.loc;
if (loc) {
// Babel 7 adds its own code frame on the error message itself
// We need to remove it and pass it separately.
if (err.message.startsWith(this.name)) {
err.message = err.message
.slice(this.name.length + 1, err.message.indexOf('\n'))
.trim();
}
err.codeFrame = codeFrame(this.contents, {start: loc});
err.highlightedCodeFrame = codeFrame(
this.contents,
{start: loc},
{highlightCode: true}
);
}
return err;
}
}
module.exports = JSAsset;