-
Notifications
You must be signed in to change notification settings - Fork 0
/
include-dependencies.js
77 lines (63 loc) · 2.46 KB
/
include-dependencies.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
'use strict';
const _ = require('lodash');
const semver = require('semver');
const path = require('path');
const dependencies = require('dependency-tree');
module.exports = class IncludeDependencies {
constructor(serverless) {
if (!semver.satisfies(serverless.version, '>= 1.2')) {
throw new Error('serverless-plugin-include-dependencies requires serverless 1.2 or higher!');
}
this.serverless = serverless;
this.hooks = {
'before:deploy:function:deploy': () => this.package(),
'before:deploy:createDeploymentArtifacts': () => this.package()
};
}
package() {
const service = this.serverless.service;
if (typeof service.functions === 'object') {
const servicePath = this.serverless.config.servicePath;
const cache = {};
service.package = service.package || {};
service.package.exclude = _.union(service.package.exclude, ['node_modules/**']);
Object.keys(service.functions).forEach(functionName => {
const functionObject = service.functions[functionName];
const list = dependencies.toList({
filename: this.getHandlerFilename(functionObject.handler),
directory: servicePath,
visited: cache,
filter: path => path.indexOf('aws-sdk') === -1,
});
if (service.package && service.package.individually) {
functionObject.package = functionObject.package || {};
this.include(functionObject.package, list);
} else {
service.package = service.package || {};
this.include(service.package, list);
}
});
}
}
getHandlerFilename(handler) {
const handlerPath = handler.slice(0, handler.lastIndexOf('.'));
return require.resolve((path.join(this.serverless.config.servicePath, handlerPath)));
}
include(target, paths) {
const servicePath = this.serverless.config.servicePath;
const modules = {};
paths.forEach(p => {
const relativePath = path.relative(servicePath, p);
if (relativePath.match(/^node_modules[/\\]/)) {
const modulePath = this.getModulePath(relativePath.replace(/^node_modules[/\\]/, ''));
const glob = path.join('node_modules', modulePath, '**');
modules[`${glob}`] = true;
}
});
target.include = _.union(target.include, Object.keys(modules));
}
getModulePath(relativePath) {
// this is a shitty attempt at cross-platform (i.e. Windows) path support
return relativePath.split(/[/\\]/)[0];
}
};