This repository has been archived by the owner on Oct 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
transform.js
338 lines (288 loc) · 8.84 KB
/
transform.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
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
/**
* © 2017 Liferay, Inc. <https://liferay.com>
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
import * as babel from 'babel-core';
import clone from 'clone';
import parseDataURL from 'data-urls';
import fs from 'fs-extra';
import * as babelIpc from 'liferay-npm-build-tools-common/lib/babel-ipc';
import * as gl from 'liferay-npm-build-tools-common/lib/globs';
import {getPackageTargetDir} from 'liferay-npm-build-tools-common/lib/packages';
import PkgDesc from 'liferay-npm-build-tools-common/lib/pkg-desc';
import PluginLogger from 'liferay-npm-build-tools-common/lib/plugin-logger';
import project from 'liferay-npm-build-tools-common/lib/project';
import path from 'path';
import readJsonSync from 'read-json-sync';
import rimraf from 'rimraf';
import * as log from '../log';
import manifest from '../manifest';
import report from '../report';
import {findFiles, getDestDir, runInChunks, runPlugins} from './util';
/**
* Transform root and dependency packages.
* @param {PkgDesc} rootPkg the root package descriptor
* @param {Array<PkgDesc>} depPkgs dependency package descriptors
* @return {Promise}
*/
export default function transformPackages(rootPkg, depPkgs) {
const dirtyPkgs = [rootPkg, ...depPkgs].filter(srcPkg => !srcPkg.clean);
return Promise.all(dirtyPkgs.map(srcPkg => transformPackage(srcPkg))).then(
() => log.debug(`Transformed ${dirtyPkgs.length} packages`)
);
}
/**
*
* @param {PkgDesc} srcPkg
* @return {Promise}
*/
function transformPackage(srcPkg) {
if (!manifest.isOutdated(srcPkg.id)) {
return Promise.resolve();
}
log.debug(`Transforming package '${srcPkg.id}'...`);
const destPkg = srcPkg.clone({
dir: getDestDir(srcPkg),
});
return runBundlerPlugins('pre', srcPkg, destPkg)
.then(() => babelifyPackage(destPkg))
.then(() => runBundlerPlugins('post', srcPkg, destPkg))
.then(() => renamePkgDirIfNecessary(destPkg))
.then(destPkg => manifest.addPackage(srcPkg, destPkg))
.then(() => log.debug(`Transformed package '${srcPkg.id}'`));
}
/**
* Process an NPM package with the configured liferay-nmp-bundler plugins. This
* function is called two times (known as phases) per package: one before Babel
* runs and one after.
* @param {String} phase 'pre' or 'post' depending on what phase we are in
* @param {PkgDesc} srcPkg the source package descriptor
* @param {PkgDesc} destPkg the target package descriptor
* @return {Promise} a Promise fulfilled when the process has been finished
*/
function runBundlerPlugins(phase, srcPkg, destPkg) {
return new Promise((resolve, reject) => {
try {
const state = runPlugins(
phase === 'pre'
? project.transform.getPrePluginDescriptors(destPkg)
: project.transform.getPostPluginDescriptors(destPkg),
srcPkg,
destPkg,
{
pkgJson: readJsonSync(
destPkg.dir.join('package.json').asNative
),
},
(plugin, log) => {
report.packageProcessBundlerPlugin(
phase,
destPkg,
plugin,
log
);
if (log.errorsPresent) {
report.warn(
'There are errors for some of the ' +
'liferay-npm-bundler plugins: please check ' +
'details of bundler transformations.',
{unique: true}
);
} else if (log.warnsPresent) {
report.warn(
'There are warnings for some of the ' +
'liferay-npm-bundler plugins: please check ' +
'details of bundler transformations.',
{unique: true}
);
}
}
);
fs.writeFileSync(
destPkg.dir.join('package.json').asNative,
JSON.stringify(state.pkgJson, '', 2)
);
resolve();
} catch (err) {
reject(err);
}
});
}
/**
* Run Babel on a package.
* @param {PkgDesc} destPkg the package descriptor
* @return {Promise} a Promise fulfilled when the process has been finished
*/
function babelifyPackage(destPkg) {
// Make a copy of the package's Babel configuration
const babelConfig = clone(project.transform.getBabelConfig(destPkg));
// Tune babel config
babelConfig.babelrc = false;
babelConfig.compact = false;
babelConfig.only = '**/*';
if (babelConfig.sourceMaps === undefined) {
babelConfig.sourceMaps = true;
}
// Report a copy of the package's Babel configuration before loading plugins
report.packageProcessBabelConfig(destPkg, clone(babelConfig));
// Intercept presets and plugins to load them from here
babelConfig.plugins = project.transform.getBabelPlugins(destPkg);
babelConfig.presets = [];
// Determine file globs
const globs = ['**/*.js', '!node_modules/**/*'];
if (destPkg.isRoot) {
globs.push(...gl.negate(project.transform.babelIgnores));
}
// Run babel through files
const prjRelPaths = findFiles(
project.dir.asNative,
gl.prefix(`${project.dir.asPosix}/${destPkg.dir.asPosix}/`, globs)
);
log.debug(
`Babelifying ${prjRelPaths.length} files in package '${destPkg.id}'...`
);
return runInChunks(
prjRelPaths,
project.misc.maxParallelFiles,
0,
prjRelPath => babelifyFile(destPkg, prjRelPath, babelConfig)
);
}
/**
*
* @param {PkgDesc} destPkg
* @param {string} prjRelPath
* @param {object} babelConfig
* @return {Promise}
*/
function babelifyFile(destPkg, prjRelPath, babelConfig) {
return new Promise(resolve => {
const logger = new PluginLogger();
babelIpc.set(project.dir.join(prjRelPath).asNative, {
log: logger,
manifest,
rootPkgJson: clone(project.pkgJson),
globalConfig: clone(project.globalConfig),
});
const fileAbsPath = project.dir.join(prjRelPath).asNative;
const filePkgRelPath = project.dir
.join(destPkg.dir)
.relative(fileAbsPath).asNative;
babel.transformFile(
fileAbsPath,
{
filename: fileAbsPath,
filenameRelative: prjRelPath,
inputSourceMap: loadSourceMap(fileAbsPath),
...babelConfig,
},
(err, result) => {
// Generate and/or log results
if (err) {
logger.error('babel', err);
report.warn(
'Babel failed processing some .js files: ' +
'check details of Babel transformations for more info.',
{unique: true}
);
} else {
const fileName = path.basename(fileAbsPath);
fs.writeFileSync(
fileAbsPath,
`${result.code}\n` +
`//# sourceMappingURL=${fileName}.map`
);
fs.writeFileSync(
`${fileAbsPath}.map`,
JSON.stringify(result.map)
);
}
// Report result of babel run
report.packageProcessBabelRun(destPkg, filePkgRelPath, logger);
if (logger.errorsPresent) {
report.warn(
'There are errors for some of the ' +
'Babel plugins: please check details ' +
'of Babel transformations.',
{unique: true}
);
} else if (logger.warnsPresent) {
report.warn(
'There are warnings for some of the ' +
'Babel plugins: please check details ' +
'of Babel transformations.',
{unique: true}
);
}
// Get rid of Babel IPC values
babelIpc.clear(prjRelPath);
// Resolve promise
resolve();
}
);
});
}
/**
* Load the source map of a transpiled JS file.
* @param {string} filePath the path to the transpiled JS file
* @return {Object|null} the source map object or null if not present
*/
export function loadSourceMap(filePath) {
const fileContent = fs.readFileSync(filePath);
const offset1 = fileContent.lastIndexOf('//# sourceMappingURL=');
const offset2 = fileContent.lastIndexOf('/*# sourceMappingURL=');
const offset = Math.max(offset1, offset2);
const annotation = fileContent.toString().substring(offset);
let matches = annotation.match(/\/\/# sourceMappingURL=(.*)/);
if (!matches) {
matches = annotation.match(/\/\*# sourceMappingURL=(.*) \*\//);
if (!matches) {
return null;
}
}
const url = matches[1];
if (url.indexOf('data:') == 0) {
const parsedData = parseDataURL(url);
if (parsedData) {
const {body, mimeType} = parsedData;
if (mimeType.toString() === 'application/json') {
return JSON.parse(body.toString());
}
}
} else {
const sourceMapFile = path.normalize(
path.join(path.dirname(filePath), url)
);
try {
return readJsonSync(sourceMapFile);
} catch (err) {
// Swallow.
}
}
return null;
}
/**
* Rename a package folder if package.json doesn't match original package name
* or version and the package is not the root package.
* @param {PkgDesc} destPkg the package descriptor
* @return {Promise} resolves to the (possibly) modified `destPkg`
*/
function renamePkgDirIfNecessary(destPkg) {
if (destPkg.isRoot) {
return Promise.resolve(destPkg);
}
const pkgJson = readJsonSync(destPkg.dir.join('package.json').asNative);
const outputDirPath = path.dirname(destPkg.dir.asNative);
if (pkgJson.name !== destPkg.name || pkgJson.version !== destPkg.version) {
const newDirPath = path.join(
outputDirPath,
getPackageTargetDir(pkgJson.name, pkgJson.version)
);
rimraf.sync(newDirPath);
return fs
.move(destPkg.dir.asNative, newDirPath)
.then(() => new PkgDesc(pkgJson.name, pkgJson.version, newDirPath));
}
return Promise.resolve(destPkg);
}