-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
373 lines (293 loc) · 8.65 KB
/
gulpfile.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
// Copyright (c) Wictor Wilén. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Load general config
const config = require('./gulp.config');
// NodeJS
const fs = require('fs'),
path = require('path');
// Gulp Base
const {
src,
dest,
watch,
series,
parallel,
lastRun,
task
} = require('gulp');
// gulp plugins
const inject = require('gulp-inject'),
zip = require('gulp-zip'),
replace = require('gulp-token-replace'),
PluginError = require('plugin-error'),
gulpLoadPlugins = require('gulp-load-plugins'),
del = require('del');
const $ = gulpLoadPlugins();
// Web Servers
const ngrok = require('ngrok');
// load references
const
nodemon = require('nodemon'),
argv = require('yargs').argv,
autoprefixer = require('autoprefixer'),
log = require('fancy-log'),
ZSchema = require('z-schema'),
axios = require('axios');
const webpack = require('webpack');
require('dotenv').config();
/**
* Setting up environments
*/
const isProd = process.env.NODE_ENV === 'production';
const isTest = process.env.NODE_ENV === 'test';
const isDev = !isProd && !isTest;
const styles = () => {
return src('src/app/**/*.scss')
.pipe($.plumber())
.pipe($.if(!isProd, $.sourcemaps.init()))
.pipe($.sass.sync({
outputStyle: 'expanded',
precision: 10,
includePaths: ['.']
}).on('error', $.sass.logError))
.pipe($.postcss([
autoprefixer()
]))
.pipe($.if(!isProd, $.sourcemaps.write()))
.pipe(dest('dist'));
};
/**
* Register watches
*/
const watches = () => {
// all other watches
watch(
config.watches,
series('webpack:server')
);
watch(
config.clientWatches,
series('webpack:client')
);
// watch for style changes
watch('src/app/**/*.scss', series('styles', 'static:copy', 'static:inject'))
.on('unlink', (a, b) => {
let cssFilename = path.basename(a, '.scss') + '.css',
cssDirectory = path.dirname(a).replace('src/app', './dist'),
cssPath = path.join(cssDirectory, cssFilename);
console.log(cssPath, fs.existsSync(cssPath));
if (fs.existsSync(cssPath)) {
fs.unlinkSync(cssPath);
injectSources();
}
});
// watch on new and deleted files
watch(config.injectSources)
.on('unlink', injectSources)
.on('add', injectSources);
// watch for static files
watch(config.staticFiles, series('static:copy', 'static:inject'));
}
task('watch', watches);
// TASK: nuke
task('nuke', () => {
return del(['temp', 'dist']);
});
task('nodemon', (callback) => {
var started = false;
var debug = argv.debug !== undefined;
return nodemon({
script: 'dist/server.js',
watch: ['dist/server.js'],
nodeArgs: debug ? ['--inspect'] : []
}).on('start', function () {
if (!started) {
callback();
started = true;
log('HOSTNAME: ' + process.env.HOSTNAME);
}
});
});
const _webpack = (idx, callback) => {
const webpackConfig = require(
path.join(__dirname + '/webpack.config')
)
webpack(webpackConfig[idx], (err, stats) => {
if (err) throw new PluginError("webpack", err);
var jsonStats = stats.toJson();
if (jsonStats.errors.length > 0) {
jsonStats.errors.map(e => {
log('[Webpack error] ' + e);
});
throw new PluginError("webpack", "Webpack errors, see log");
}
if (jsonStats.warnings.length > 0) {
jsonStats.warnings.map(function (e) {
log('[Webpack warning] ' + e);
});
}
callback();
});
}
/**
* Webpack bundling
*/
task('webpack:client', (callback) => {
_webpack(1, callback);
});
task('webpack:server', (callback) => {
_webpack(0, callback);
});
task('webpack', parallel("webpack:client", "webpack:server"));
/**
* Copies static files
*/
task('static:copy', () => {
return src(config.staticFiles, {
base: "./src/app"
})
.pipe(
dest('./dist/')
);
});
const injectSources = () => {
var injectSrc = src(config.injectSources);
var injectOptions = {
relative: false,
ignorePath: 'dist/web',
addRootSlash: true
};
return src(config.htmlFiles)
.pipe(replace({
tokens: {
...process.env
}
}))
.pipe(
inject(injectSrc, injectOptions)
)
.pipe(
dest('./dist')
);
};
/**
* Injects script into pages
*/
task('static:inject', injectSources);
/**
* SASS compilation
*/
task('styles', styles);
/**
* Build task, that uses webpack and injects scripts into pages
*/
task('build', series('webpack', 'styles', 'static:copy', 'static:inject'));
/**
* Replace parameters in the manifest
*/
task('generate-manifest', (cb) => {
return src('src/manifest/manifest.json')
.pipe(replace({
tokens: {
...process.env
}
}))
.pipe(dest(config.temp));
});
/**
* Schema validation
*/
task('schema-validation', (callback) => {
let filePath = path.join(__dirname, 'temp/manifest.json');
if (fs.existsSync(filePath)) {
let manifest = fs.readFileSync(filePath, {
encoding: 'UTF-8'
}),
manifestJson;
try {
manifestJson = JSON.parse(manifest);
} catch (error) {
callback(
new PluginError(error.message)
);
return;
}
log('Using manifest schema ' + manifestJson.manifestVersion);
let definition = config.SCHEMAS.find(s => s.version == manifestJson.manifestVersion);
if (definition === undefined) {
callback(new PluginError("validate-manifest", "Unable to locate schema"));
return;
}
if (manifestJson["$schema"] !== definition.schema) {
log("Note: the defined schema in your manifest does not correspond to the manifestVersion");
}
let requiredUrl = definition.schema;
let validator = new ZSchema();
let schema = {
"$ref": requiredUrl
};
axios.get(requiredUrl, {
decompress: true,
responseType: 'json'
}).then(response => {
validator.setRemoteReference(requiredUrl, response.data);
var valid = validator.validate(manifestJson, schema);
var errors = validator.getLastErrors();
if (!valid) {
callback(new PluginError("validate-manifest", errors.map((e) => {
return e.message;
}).join('\n')));
} else {
callback();
}
}).catch(err => {
log.warn("WARNING: unable to download and validate schema: " + err);
callback();
});
} else {
console.log('Manifest doesn\'t exist');
}
});
task('validate-manifest', series('generate-manifest', 'schema-validation'));
/**
* Task for starting ngrok and replacing the HOSTNAME with ngrok tunnel url.
* The task also creates a manifest file with ngrok tunnel url.
* See local .env file for configuration
*/
task('start-ngrok', (cb) => {
log("[NGROK] starting ngrok...");
let conf = {
subdomain: process.env.NGROK_SUBDOMAIN,
region: process.env.NGROK_REGION,
addr: process.env.PORT,
authtoken: process.env.NGROK_AUTH
};
ngrok.connect(conf).then((url) => {
log('[NGROK] Url: ' + url);
if (!conf.authtoken) {
log("[NGROK] You have been assigned a random ngrok URL that will only be available for this session. You wil need to re-upload the Teams manifest next time you run this command.");
}
let hostName = url.replace('http://', '');
hostName = hostName.replace('https://', '');
log('[NGROK] HOSTNAME: ' + hostName);
process.env.HOSTNAME = hostName
cb();
}).catch((err) => {
log.error(`[NGROK] Error: ${JSON.stringify(err)}`);
cb(err.msg);
});
});
/**
* Creates the tab manifest
*/
task('zip', () => {
return src(config.manifests)
.pipe(src('./temp/manifest.json'))
.pipe(zip(config.manifestFileName))
.pipe(dest('package'));
});
task('styles', styles);
task('serve', series('nuke', 'build', 'nodemon', 'watch'));
task('manifest', series('validate-manifest', 'zip'));
task('ngrok-serve', series('start-ngrok', 'manifest', 'serve'));