-
Notifications
You must be signed in to change notification settings - Fork 417
/
Copy pathpackExternalModules.js
444 lines (402 loc) · 17.2 KB
/
packExternalModules.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
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
'use strict';
const BbPromise = require('bluebird');
const _ = require('lodash');
const path = require('path');
const fse = require('fs-extra');
const isBuiltinModule = require('is-builtin-module');
const Packagers = require('./packagers');
function rebaseFileReferences(pathToPackageRoot, moduleVersion) {
if (/^(?:file:[^/]{2}|\.\/|\.\.\/)/.test(moduleVersion)) {
const filePath = _.replace(moduleVersion, /^file:/, '');
return _.replace(
`${_.startsWith(moduleVersion, 'file:') ? 'file:' : ''}${pathToPackageRoot}/${filePath}`,
/\\/g,
'/'
);
}
return moduleVersion;
}
/**
* Add the given modules to a package json's dependencies.
*/
function addModulesToPackageJson(externalModules, packageJson, pathToPackageRoot) {
_.forEach(externalModules, externalModule => {
const splitModule = _.split(externalModule, '@');
// If we have a scoped module we have to re-add the @
if (_.startsWith(externalModule, '@')) {
splitModule.splice(0, 1);
splitModule[0] = '@' + splitModule[0];
}
let moduleVersion = _.join(_.tail(splitModule), '@');
// We have to rebase file references to the target package.json
moduleVersion = rebaseFileReferences(pathToPackageRoot, moduleVersion);
packageJson.dependencies = packageJson.dependencies || {};
packageJson.dependencies[_.first(splitModule)] = moduleVersion;
});
}
/**
* Remove a given list of excluded modules from a module list
* @this - The active plugin instance
*/
function removeExcludedModules(modules, packageForceExcludes, log) {
// eslint-disable-next-line lodash/prefer-immutable-method
const excludedModules = _.remove(modules, externalModule => {
const splitModule = _.split(externalModule, '@');
// If we have a scoped module we have to re-add the @
if (_.startsWith(externalModule, '@')) {
splitModule.splice(0, 1);
splitModule[0] = '@' + splitModule[0];
}
const moduleName = _.first(splitModule);
return _.includes(packageForceExcludes, moduleName);
});
if (log && !_.isEmpty(excludedModules)) {
this.serverless.cli.log(`Excluding external modules: ${_.join(excludedModules, ', ')}`);
}
}
/**
* Resolve the needed versions of production dependencies for external modules.
* @this - The active plugin instance
*/
function getProdModules(externalModules, packagePath, dependencyGraph, forceExcludes) {
const packageJsonPath = path.join(process.cwd(), packagePath);
const packageJson = require(packageJsonPath);
const prodModules = [];
// only process the module stated in dependencies section
if (!packageJson.dependencies) {
return [];
}
// Get versions of all transient modules
_.forEach(externalModules, module => {
let moduleVersion = packageJson.dependencies[module.external];
if (moduleVersion) {
prodModules.push(`${module.external}@${moduleVersion}`);
// Check if the module has any peer dependencies and include them too
try {
const modulePackagePath = path.join(
path.dirname(path.join(process.cwd(), packagePath)),
'node_modules',
module.external,
'package.json'
);
const peerDependencies = require(modulePackagePath).peerDependencies;
if (!_.isEmpty(peerDependencies)) {
this.options.verbose && this.serverless.cli.log(`Adding explicit peers for dependency ${module.external}`);
const peerDependenciesMeta = require(modulePackagePath).peerDependenciesMeta;
if (!_.isEmpty(peerDependenciesMeta)) {
_.forEach(peerDependencies, (value, key) => {
if (peerDependenciesMeta[key] && peerDependenciesMeta[key].optional === true) {
this.options.verbose &&
this.serverless.cli.log(
`Skipping peers dependency ${key} for dependency ${module.external} because it's optional`
);
_.unset(peerDependencies, key);
}
});
}
if (!_.isEmpty(peerDependencies)) {
const peerModules = getProdModules.call(
this,
_.map(peerDependencies, (value, key) => ({ external: key })),
packagePath,
dependencyGraph,
forceExcludes
);
Array.prototype.push.apply(prodModules, peerModules);
}
}
} catch (e) {
this.serverless.cli.log(`WARNING: Could not check for peer dependencies of ${module.external}`);
}
} else {
if (!packageJson.devDependencies || !packageJson.devDependencies[module.external]) {
// Add transient dependencies if they appear not in the service's dev dependencies
const originInfo = _.get(dependencyGraph, 'dependencies', {})[module.origin] || {};
moduleVersion = _.get(_.get(originInfo, 'dependencies', {})[module.external], 'version');
if (!moduleVersion) {
this.serverless.cli.log(`WARNING: Could not determine version of module ${module.external}`);
}
prodModules.push(moduleVersion ? `${module.external}@${moduleVersion}` : module.external);
} else if (
packageJson.devDependencies &&
packageJson.devDependencies[module.external] &&
!_.includes(forceExcludes, module.external)
) {
// To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check
// most likely set in devDependencies and should not lead to an error now.
const ignoredDevDependencies = ['aws-sdk'];
if (!_.includes(ignoredDevDependencies, module.external)) {
// Runtime dependency found in devDependencies but not forcefully excluded
this.serverless.cli.log(
`ERROR: Runtime dependency '${module.external}' found in devDependencies. Move it to dependencies or use forceExclude to explicitly exclude it.`
);
throw new this.serverless.classes.Error(`Serverless-webpack dependency error: ${module.external}.`);
}
this.options.verbose &&
this.serverless.cli.log(
`INFO: Runtime dependency '${module.external}' found in devDependencies. It has been excluded automatically.`
);
}
}
});
return prodModules;
}
function getExternalModuleName(module) {
const path = /^external "(.*)"$/.exec(module.identifier())[1];
const pathComponents = path.split('/');
const main = pathComponents[0];
// this is a package within a namespace
if (main.charAt(0) == '@') {
return `${main}/${pathComponents[1]}`;
}
return main;
}
function isExternalModule(module) {
return _.startsWith(module.identifier(), 'external ') && !isBuiltinModule(getExternalModuleName(module));
}
/**
* Find the original module that required the transient dependency. Returns
* undefined if the module is a first level dependency.
* @param {Object} issuer - Module issuer
*/
function findExternalOrigin(issuer) {
if (!_.isNil(issuer) && _.startsWith(issuer.rawRequest, './')) {
return findExternalOrigin(issuer.issuer);
}
return issuer;
}
function getExternalModules(stats) {
if (!stats.compilation.chunks) {
return [];
}
const externals = new Set();
for (const chunk of stats.compilation.chunks) {
if (!chunk.modulesIterable) {
continue;
}
// Explore each module within the chunk (built inputs):
for (const module of chunk.modulesIterable) {
if (isExternalModule(module)) {
externals.add({
origin: _.get(findExternalOrigin(module.issuer), 'rawRequest'),
external: getExternalModuleName(module)
});
}
}
}
return Array.from(externals);
}
module.exports = {
/**
* We need a performant algorithm to install the packages for each single
* function (in case we package individually).
* (1) We fetch ALL packages needed by ALL functions in a first step
* and use this as a base npm checkout. The checkout will be done to a
* separate temporary directory with a package.json that contains everything.
* (2) For each single compile we copy the whole node_modules to the compile
* directory and create a (function) compile specific package.json and store
* it in the compile directory. Now we start npm again there, and npm will just
* remove the superfluous packages and optimize the remaining dependencies.
* This will utilize the npm cache at its best and give us the needed results
* and performance.
*/
packExternalModules() {
const stats = this.compileStats;
const includes = this.configuration.includeModules;
if (!includes) {
return BbPromise.resolve();
}
// Read plugin configuration
const packageForceIncludes = _.get(includes, 'forceInclude', []);
const packageForceExcludes = _.get(includes, 'forceExclude', []);
const packagePath = includes.packagePath || './package.json';
const packageJsonPath = path.join(process.cwd(), packagePath);
const packageScripts = _.reduce(
this.configuration.packagerOptions.scripts || [],
(__, script, index) => {
__[`script${index}`] = script;
return __;
},
{}
);
// Determine and create packager
return BbPromise.try(() => Packagers.get.call(this, this.configuration.packager)).then(packager => {
// Fetch needed original package.json sections
const sectionNames = packager.copyPackageSectionNames;
const packageJson = this.serverless.utils.readFileSync(packageJsonPath);
const packageSections = _.pick(packageJson, sectionNames);
if (!_.isEmpty(packageSections)) {
this.options.verbose &&
this.serverless.cli.log(`Using package.json sections ${_.join(_.keys(packageSections), ', ')}`);
}
// Get first level dependency graph
this.options.verbose && this.serverless.cli.log(`Fetch dependency graph from ${packageJsonPath}`);
return packager.getProdDependencies(path.dirname(packageJsonPath), 1).then(dependencyGraph => {
const problems = _.get(dependencyGraph, 'problems', []);
if (this.options.verbose && !_.isEmpty(problems)) {
this.serverless.cli.log(`Ignoring ${_.size(problems)} NPM errors:`);
_.forEach(problems, problem => {
this.serverless.cli.log(`=> ${problem}`);
});
}
// (1) Generate dependency composition
const compositeModules = _.uniq(
_.flatMap(stats.stats, compileStats => {
const externalModules = _.concat(
getExternalModules.call(this, compileStats),
_.map(packageForceIncludes, whitelistedPackage => ({
external: whitelistedPackage
}))
);
return getProdModules.call(this, externalModules, packagePath, dependencyGraph, packageForceExcludes);
})
);
removeExcludedModules.call(this, compositeModules, packageForceExcludes, true);
if (_.isEmpty(compositeModules)) {
// The compiled code does not reference any external modules at all
this.serverless.cli.log('No external modules needed');
return BbPromise.resolve();
}
// (1.a) Install all needed modules
const compositeModulePath = path.join(this.webpackOutputPath, 'dependencies');
const compositePackageJson = path.join(compositeModulePath, 'package.json');
// (1.a.1) Create a package.json
const compositePackage = _.defaults(
{
name: this.serverless.service.service,
version: '1.0.0',
description: `Packaged externals for ${this.serverless.service.service}`,
private: true,
scripts: packageScripts
},
packageSections
);
const relPath = path.relative(compositeModulePath, path.dirname(packageJsonPath));
addModulesToPackageJson(compositeModules, compositePackage, relPath);
this.serverless.utils.writeFileSync(compositePackageJson, JSON.stringify(compositePackage, null, 2));
// (1.a.2) Copy package-lock.json if it exists, to prevent unwanted upgrades
const packageLockPath = path.join(path.dirname(packageJsonPath), packager.lockfileName);
let hasPackageLock = false;
return BbPromise.fromCallback(cb => fse.pathExists(packageLockPath, cb))
.then(exists => {
if (exists) {
this.serverless.cli.log('Package lock found - Using locked versions');
try {
let packageLockFile = this.serverless.utils.readFileSync(packageLockPath);
packageLockFile = packager.rebaseLockfile(relPath, packageLockFile);
if (_.isObject(packageLockFile)) {
packageLockFile = JSON.stringify(packageLockFile, null, 2);
}
this.serverless.utils.writeFileSync(
path.join(compositeModulePath, packager.lockfileName),
packageLockFile
);
hasPackageLock = true;
} catch (err) {
this.serverless.cli.log(`Warning: Could not read lock file: ${err.message}`);
}
}
return BbPromise.resolve();
})
.then(() => {
const start = _.now();
this.serverless.cli.log('Packing external modules: ' + compositeModules.join(', '));
return packager
.install(compositeModulePath, this.configuration.packagerOptions)
.then(() => this.options.verbose && this.serverless.cli.log(`Package took [${_.now() - start} ms]`))
.return(stats.stats);
})
.mapSeries(compileStats => {
const modulePath = compileStats.compilation.compiler.outputPath;
// Create package.json
const modulePackageJson = path.join(modulePath, 'package.json');
const modulePackage = _.defaults(
{
name: this.serverless.service.service,
version: '1.0.0',
description: `Packaged externals for ${this.serverless.service.service}`,
private: true,
scripts: packageScripts,
dependencies: {}
},
packageSections
);
const prodModules = getProdModules.call(
this,
_.concat(
getExternalModules.call(this, compileStats),
_.map(packageForceIncludes, whitelistedPackage => ({
external: whitelistedPackage
}))
),
packagePath,
dependencyGraph,
packageForceExcludes
);
removeExcludedModules.call(this, prodModules, packageForceExcludes);
const relPath = path.relative(modulePath, path.dirname(packageJsonPath));
addModulesToPackageJson(prodModules, modulePackage, relPath);
this.serverless.utils.writeFileSync(modulePackageJson, JSON.stringify(modulePackage, null, 2));
// GOOGLE: Copy modules only if not google-cloud-functions
// GCF Auto installs the package json
if (_.get(this.serverless, 'service.provider.name') === 'google') {
return BbPromise.resolve();
}
const startCopy = _.now();
return BbPromise.try(() => {
// Only copy dependency modules if demanded by packager
if (packager.mustCopyModules) {
return BbPromise.fromCallback(callback =>
fse.copy(
path.join(compositeModulePath, 'node_modules'),
path.join(modulePath, 'node_modules'),
callback
)
);
}
return BbPromise.resolve();
})
.then(() =>
hasPackageLock
? BbPromise.fromCallback(callback =>
fse.copy(
path.join(compositeModulePath, packager.lockfileName),
path.join(modulePath, packager.lockfileName),
callback
)
)
: BbPromise.resolve()
)
.tap(
() =>
this.options.verbose &&
this.serverless.cli.log(`Copy modules: ${modulePath} [${_.now() - startCopy} ms]`)
)
.then(() => {
// Prune extraneous packages - removes not needed ones
const startPrune = _.now();
return packager
.prune(modulePath, this.configuration.packagerOptions)
.tap(
() =>
this.options.verbose &&
this.serverless.cli.log(`Prune: ${modulePath} [${_.now() - startPrune} ms]`)
);
})
.then(() => {
// Prune extraneous packages - removes not needed ones
const startRunScripts = _.now();
return packager
.runScripts(modulePath, _.keys(packageScripts))
.tap(
() =>
this.options.verbose &&
this.serverless.cli.log(`Run scripts: ${modulePath} [${_.now() - startRunScripts} ms]`)
);
});
})
.return();
});
});
}
};