forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgulpfile.js
More file actions
596 lines (518 loc) · 20 KB
/
gulpfile.js
File metadata and controls
596 lines (518 loc) · 20 KB
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/* eslint-disable no-console */
'use strict';
var _ = require('lodash');
var argv = require('yargs').argv;
var gulp = require('gulp');
var PluginError = require('plugin-error');
var fancyLog = require('fancy-log');
var connect = require('gulp-connect');
var webpack = require('webpack');
var webpackStream = require('webpack-stream');
var gulpClean = require('gulp-clean');
var opens = require('opn');
var webpackConfig = require('./webpack.conf.js');
const standaloneDebuggingConfig = require('./webpack.debugging.js');
var helpers = require('./gulpHelpers.js');
const execaTask = helpers.execaTask;
var concat = require('gulp-concat');
var replace = require('gulp-replace');
const execaCmd = require('execa');
var gulpif = require('gulp-if');
var sourcemaps = require('gulp-sourcemaps');
var through = require('through2');
var fs = require('fs');
var jsEscape = require('gulp-js-escape');
const path = require('path');
const {minify} = require('terser');
const Vinyl = require('vinyl');
const wrap = require('gulp-wrap');
const rename = require('gulp-rename');
const merge = require('merge-stream');
var prebid = require('./package.json');
var port = 9999;
const INTEG_SERVER_HOST = argv.host ? argv.host : 'localhost';
const INTEG_SERVER_PORT = 4444;
const { spawn, fork } = require('child_process');
const TerserPlugin = require('terser-webpack-plugin');
const {precompile, babelPrecomp} = require('./gulp.precompilation.js');
const TEST_CHUNKS = 4;
// these modules must be explicitly listed in --modules to be included in the build, won't be part of "all" modules
var explicitModules = [
'pre1api'
];
// all the following functions are task functions
function bundleToStdout() {
nodeBundle().then(file => console.log(file));
}
bundleToStdout.displayName = 'bundle-to-stdout';
function clean() {
return gulp.src(['build', 'dist'], {
read: false,
allowEmpty: true
})
.pipe(gulpClean());
}
function requireNodeVersion(version) {
return (done) => {
const [major] = process.versions.node.split('.');
if (major < version) {
throw new Error(`This task requires Node v${version}`)
}
done();
}
}
// Dependant task for building postbid. It escapes postbid-config file.
function escapePostbidConfig() {
gulp.src('./integrationExamples/postbid/oas/postbid-config.js')
.pipe(jsEscape())
.pipe(gulp.dest('build/postbid/'));
};
escapePostbidConfig.displayName = 'escape-postbid-config';
function lint(done) {
if (argv.nolint) {
return done();
}
const args = ['eslint', '--cache', '--cache-strategy', 'content'];
if (!argv.nolintfix) {
args.push('--fix');
}
if (!(typeof argv.lintWarnings === 'boolean' ? argv.lintWarnings : true)) {
args.push('--quiet')
}
return execaTask(args.join(' '))().then(() => {
done();
}, (err) => {
done(err);
});
};
function makeVerbose(config = webpackConfig) {
return _.merge({}, config, {
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
mangle: false,
format: {
comments: 'all'
}
},
extractComments: false,
}),
],
}
});
}
function prebidSource(webpackCfg) {
var externalModules = helpers.getArgModules();
const analyticsSources = helpers.getAnalyticsSources();
const moduleSources = helpers.getModulePaths(externalModules);
return gulp.src([].concat(moduleSources, analyticsSources, helpers.getPrecompiledPath('src/prebid.js')))
.pipe(helpers.nameModules(externalModules))
.pipe(webpackStream(webpackCfg, webpack));
}
function makeDevpackPkg(config = webpackConfig) {
return function() {
var cloned = _.cloneDeep(config);
Object.assign(cloned, {
devtool: 'source-map',
mode: 'development'
})
return prebidSource(cloned)
.pipe(gulp.dest('build/dev'))
.pipe(connect.reload());
}
}
function makeWebpackPkg(config = webpackConfig) {
var cloned = _.cloneDeep(config)
if (!argv.sourceMaps) {
delete cloned.devtool;
}
return function buildBundle() {
return prebidSource(cloned)
.pipe(gulp.dest('build/dist'));
}
}
function buildCreative(mode = 'production') {
const opts = {mode};
if (mode === 'development') {
opts.devtool = 'inline-source-map'
}
return function() {
return gulp.src(['creative/**/*'])
.pipe(webpackStream(Object.assign(require('./webpack.creative.js'), opts)))
.pipe(gulp.dest('build/creative'))
}
}
function updateCreativeRenderers() {
return gulp.src(['build/creative/renderers/**/*'])
.pipe(wrap('// this file is autogenerated, see creative/README.md\nexport const RENDERER = <%= JSON.stringify(contents.toString()) %>'))
.pipe(rename(function (path) {
return {
dirname: `creative-renderer-${path.basename}`,
basename: 'renderer',
extname: '.js'
}
}))
.pipe(gulp.dest('libraries'))
}
function updateCreativeExample(cb) {
const CREATIVE_EXAMPLE = 'integrationExamples/gpt/x-domain/creative.html';
const root = require('node-html-parser').parse(fs.readFileSync(CREATIVE_EXAMPLE));
root.querySelectorAll('script')[0].textContent = fs.readFileSync('build/creative/creative.js')
fs.writeFileSync(CREATIVE_EXAMPLE, root.toString())
cb();
}
function getModulesListToAddInBanner(modules) {
if (!modules || modules.length === helpers.getModuleNames().length) {
return 'All available modules for this version.'
} else {
return modules.join(', ')
}
}
function gulpBundle(dev) {
return bundle(dev).pipe(gulp.dest('build/' + (dev ? 'dev' : 'dist')));
}
function nodeBundle(modules, dev = false) {
return new Promise((resolve, reject) => {
bundle(dev, modules)
.on('error', (err) => {
reject(err);
})
.pipe(through.obj(function (file, enc, done) {
if (file.path.endsWith('.js')) {
resolve(file.contents.toString(enc));
}
done();
}));
});
}
function memoryVinyl(name, contents) {
return new Vinyl({
cwd: '',
base: 'generated',
path: name,
contents: Buffer.from(contents, 'utf-8')
});
}
function wrapWithHeaderAndFooter(dev, modules) {
// NOTE: gulp-header, gulp-footer & gulp-wrap do not play nice with source maps.
// gulp-concat does; for that reason we are prepending and appending the source stream with "fake" header & footer files.
return function wrap(stream) {
const wrapped = through.obj();
const placeholder = '$$PREBID_SOURCE$$';
const tpl = _.template(fs.readFileSync('./bundle-template.txt'))({
prebid,
modules: getModulesListToAddInBanner(modules),
enable: !argv.manualEnable
});
(dev ? Promise.resolve(tpl) : minify(tpl, {format: {comments: true}}).then((res) => res.code))
.then((tpl) => {
// wrap source placeholder in an IIFE to make it an expression (so that it works with minify output)
const parts = tpl.replace(placeholder, `(function(){$$${placeholder}$$})()`).split(placeholder);
if (parts.length !== 2) {
throw new Error(`Cannot parse bundle template; it must contain exactly one instance of '${placeholder}'`);
}
const [header, footer] = parts;
wrapped.push(memoryVinyl('prebid-header.js', header));
stream.pipe(wrapped, {end: false});
stream.on('end', () => {
wrapped.push(memoryVinyl('prebid-footer.js', footer));
wrapped.push(null);
});
})
.catch((err) => {
wrapped.destroy(err);
});
return wrapped;
}
}
function disclosureSummary(modules, summaryFileName) {
const stream = through.obj();
import('./libraries/storageDisclosure/summary.mjs').then(({getStorageDisclosureSummary}) => {
const summary = getStorageDisclosureSummary(modules, (moduleName) => {
const metadataPath = `./metadata/modules/${moduleName}.json`;
if (fs.existsSync(metadataPath)) {
return JSON.parse(fs.readFileSync(metadataPath).toString());
} else {
return null;
}
})
stream.push(memoryVinyl(summaryFileName, JSON.stringify(summary, null, 2)));
stream.push(null);
})
return stream;
}
const MODULES_REQUIRING_METADATA = ['storageControl'];
function bundle(dev, moduleArr) {
var modules = moduleArr || helpers.getArgModules();
var allModules = helpers.getModuleNames(modules);
const sm = dev || argv.sourceMaps;
if (modules.length === 0) {
modules = allModules.filter(module => explicitModules.indexOf(module) === -1);
} else {
var diff = _.difference(modules, allModules);
if (diff.length !== 0) {
throw new PluginError('bundle', 'invalid modules: ' + diff.join(', ') + '. Check your modules list.');
}
}
const metadataModules = modules.find(module => MODULES_REQUIRING_METADATA.includes(module))
? modules.concat(['prebid-core']).map(helpers.getMetadataEntry).filter(name => name != null)
: [];
const coreFile = helpers.getBuiltPrebidCoreFile(dev);
const moduleFiles = helpers.getBuiltModules(dev, modules)
.concat(metadataModules.map(mod => helpers.getBuiltPath(dev, `${mod}.js`)));
const depGraph = require(helpers.getBuiltPath(dev, 'dependencies.json'));
const dependencies = new Set();
[coreFile].concat(moduleFiles).map(name => path.basename(name)).forEach((file) => {
(depGraph[file] || []).forEach((dep) => dependencies.add(helpers.getBuiltPath(dev, dep)));
});
const entries = _.uniq([coreFile].concat(Array.from(dependencies), moduleFiles));
var outputFileName = argv.bundleName ? argv.bundleName : 'prebid.js';
// change output filename if argument --tag given
if (argv.tag && argv.tag.length) {
outputFileName = outputFileName.replace(/\.js$/, `.${argv.tag}.js`);
}
const disclosureFile = path.parse(outputFileName).name + '_disclosures.json';
fancyLog('Concatenating files:\n', entries);
fancyLog('Appending ' + prebid.globalVarName + '.processQueue();');
fancyLog('Generating bundle:', outputFileName);
fancyLog('Generating storage use disclosure summary:', disclosureFile);
const wrap = wrapWithHeaderAndFooter(dev, modules);
const source = wrap(gulp.src(entries))
.pipe(gulpif(sm, sourcemaps.init({ loadMaps: true })))
.pipe(concat(outputFileName))
.pipe(gulpif(sm, sourcemaps.write('.')));
const disclosure = disclosureSummary(['prebid-core'].concat(modules), disclosureFile);
return merge(source, disclosure);
}
function setupDist() {
return gulp.src(['build/dist/**/*'])
.pipe(rename(function (path) {
if (path.dirname === '.' && path.basename === 'prebid') {
path.dirname = '../not-for-prod';
}
}))
.pipe(gulp.dest('dist/chunks'))
}
// Run the unit tests.
//
// By default, this runs in headless chrome.
//
// If --watch is given, the task will re-run unit tests whenever the source code changes
// If --file "<path-to-test-file>" is given, the task will only run tests in the specified file.
// If --browserstack is given, it will run the full suite of currently supported browsers.
// If --browsers is given, browsers can be chosen explicitly. e.g. --browsers=chrome,firefox,ie9
// If --notest is given, it will immediately skip the test task (useful for developing changes with `gulp serve --notest`)
function testTaskMaker(options = {}) {
['watch', 'file', 'browserstack', 'notest'].forEach(opt => {
options[opt] = options.hasOwnProperty(opt) ? options[opt] : argv[opt];
})
return function test(done) {
if (options.notest) {
done();
} else {
runKarma(options, done)
}
}
}
const test = testTaskMaker();
function e2eTestTaskMaker() {
return function test(done) {
const integ = startIntegServer();
startLocalServer();
runWebdriver({})
.then(stdout => {
// kill fake server
integ.kill('SIGINT');
done();
process.exit(0);
})
.catch(err => {
// kill fake server
integ.kill('SIGINT');
done(new Error(`Tests failed with error: ${err}`));
process.exit(1);
});
}
}
function runWebdriver({file}) {
process.env.TEST_SERVER_HOST = argv.host || 'localhost';
let local = argv.local || false;
let wdioConfFile = local === true ? 'wdio.local.conf.js' : 'wdio.conf.js';
let wdioCmd = path.join(__dirname, 'node_modules/.bin/wdio');
let wdioConf = path.join(__dirname, wdioConfFile);
let wdioOpts;
if (file) {
wdioOpts = [
wdioConf,
`--spec`,
`${file}`
]
} else {
wdioOpts = [
wdioConf
];
}
return execaCmd(wdioCmd, wdioOpts, {
stdio: 'inherit',
env: Object.assign({}, process.env, {FORCE_COLOR: '1'})
});
}
function runKarma(options, done) {
// the karma server appears to leak memory; starting it multiple times in a row will run out of heap
// here we run it in a separate process to bypass the problem
options = Object.assign({browsers: helpers.parseBrowserArgs(argv)}, options)
const env = Object.assign({}, options.env, process.env);
if (!env.TEST_CHUNKS) {
env.TEST_CHUNKS = TEST_CHUNKS;
}
const child = fork('./karmaRunner.js', null, {
env
});
child.on('exit', (exitCode) => {
if (exitCode) {
done(new Error('Karma tests failed with exit code ' + exitCode));
} else {
done();
}
})
child.send(options);
}
// If --file "<path-to-test-file>" is given, the task will only run tests in the specified file.
function testCoverage(done) {
runKarma({
coverage: true,
browserstack: false,
watch: false,
file: argv.file,
env: {
NODE_OPTIONS: '--max-old-space-size=8096',
TEST_CHUNKS
}
}, done);
}
function coveralls() { // 2nd arg is a dependency: 'test' must be finished
// first send results of istanbul's test coverage to coveralls.io.
return execaTask('cat build/coverage/lcov.info | node_modules/coveralls-next/bin/coveralls.js')();
}
// This task creates postbid.js. Postbid setup is different from prebid.js
// More info can be found here http://prebid.org/overview/what-is-post-bid.html
function buildPostbid() {
var fileContent = fs.readFileSync('./build/postbid/postbid-config.js', 'utf8');
return gulp.src('./integrationExamples/postbid/oas/postbid.js')
.pipe(replace('\[%%postbid%%\]', fileContent))
.pipe(gulp.dest('build/postbid/'));
}
function startIntegServer(dev = false) {
const args = ['./test/fake-server/index.js', `--port=${INTEG_SERVER_PORT}`, `--host=${INTEG_SERVER_HOST}`];
if (dev) {
args.push('--dev=true')
}
const srv = spawn('node', args);
srv.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
srv.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
return srv;
}
function startLocalServer(options = {}) {
return connect.server({
https: argv.https,
port: port,
host: INTEG_SERVER_HOST,
root: './',
livereload: options.livereload,
middleware: function () {
return [
function (req, res, next) {
res.setHeader('Ad-Auction-Allowed', 'True');
next();
}
];
}
});
}
// Watch Task with Live Reload
function watchTaskMaker(options = {}) {
if (options.livereload == null) {
options.livereload = true;
}
options.alsoWatch = options.alsoWatch || [];
return function watch(done) {
gulp.watch(helpers.getSourcePatterns().concat(
helpers.getIgnoreSources().map(src => `!${src}`)
), babelPrecomp(options));
gulp.watch([
helpers.getPrecompiledPath('**/*.js'),
...helpers.getIgnoreSources().map(src => `!${helpers.getPrecompiledPath(src)}`),
`!${helpers.getPrecompiledPath('test/**/*')}`,
], options.task());
startLocalServer(options);
done();
}
}
const watch = watchTaskMaker({task: () => gulp.series(clean, gulp.parallel(lint, 'build-bundle-dev', test))});
const watchFast = watchTaskMaker({dev: true, livereload: false, task: () => gulp.series('build-bundle-dev')});
// support tasks
gulp.task(lint);
gulp.task(watch);
gulp.task(clean);
gulp.task(escapePostbidConfig);
gulp.task('build-creative-dev', gulp.series(buildCreative(argv.creativeDev ? 'development' : 'production'), updateCreativeRenderers));
gulp.task('build-creative-prod', gulp.series(buildCreative(), updateCreativeRenderers));
gulp.task('build-bundle-dev-no-precomp', gulp.series('build-creative-dev', makeDevpackPkg(standaloneDebuggingConfig), makeDevpackPkg(), gulpBundle.bind(null, true)));
gulp.task('build-bundle-dev', gulp.series(precompile({dev: true}), 'build-bundle-dev-no-precomp'));
gulp.task('build-bundle-prod', gulp.series(precompile(), 'build-creative-prod', makeWebpackPkg(standaloneDebuggingConfig), makeWebpackPkg(), gulpBundle.bind(null, false)));
// build-bundle-verbose - prod bundle except names and comments are preserved. Use this to see the effects
// of dead code elimination.
gulp.task('build-bundle-verbose', gulp.series(precompile(), 'build-creative-dev', makeWebpackPkg(makeVerbose(standaloneDebuggingConfig)), makeWebpackPkg(makeVerbose()), gulpBundle.bind(null, false)));
// public tasks (dependencies are needed for each task since they can be ran on their own)
gulp.task('update-browserslist', execaTask('npx update-browserslist-db@latest'));
gulp.task('test-only-nobuild', testTaskMaker({coverage: true}))
gulp.task('test-only', gulp.series('precompile', test));
gulp.task('test-all-features-disabled-nobuild', testTaskMaker({disableFeatures: require('./features.json'), oneBrowser: 'chrome', watch: false}));
gulp.task('test-all-features-disabled', gulp.series('precompile-all-features-disabled', 'test-all-features-disabled-nobuild'));
gulp.task('test', gulp.series(clean, lint, 'test-all-features-disabled', 'test-only'));
gulp.task('test-coverage', gulp.series(clean, precompile(), testCoverage));
gulp.task('coveralls', gulp.series('test-coverage', coveralls));
// npm will by default use .gitignore, so create an .npmignore that is a copy of it except it includes "dist"
gulp.task('setup-npmignore', execaTask("sed 's/^\\/\\?dist\\/\\?$//g;w .npmignore' .gitignore", {quiet: true}));
gulp.task('build', gulp.series(clean, 'build-bundle-prod', updateCreativeExample, setupDist));
gulp.task('build-release', gulp.series('build', 'update-browserslist', 'setup-npmignore'));
gulp.task('build-postbid', gulp.series(escapePostbidConfig, buildPostbid));
gulp.task('serve', gulp.series(clean, lint, precompile(), gulp.parallel('build-bundle-dev-no-precomp', watch, test)));
gulp.task('serve-fast', gulp.series(clean, precompile({dev: true}), gulp.parallel('build-bundle-dev-no-precomp', watchFast)));
gulp.task('serve-prod', gulp.series(clean, gulp.parallel('build-bundle-prod', startLocalServer)));
gulp.task('serve-and-test', gulp.series(clean, precompile({dev: true}), gulp.parallel('build-bundle-dev-no-precomp', watchFast, testTaskMaker({watch: true}))));
gulp.task('serve-e2e', gulp.series(clean, 'build-bundle-prod', gulp.parallel(() => startIntegServer(), startLocalServer)));
gulp.task('serve-e2e-dev', gulp.series(clean, 'build-bundle-dev', gulp.parallel(() => startIntegServer(true), startLocalServer)));
gulp.task('default', gulp.series('build'));
gulp.task('e2e-test-only', gulp.series(requireNodeVersion(16), () => runWebdriver({file: argv.file})));
gulp.task('e2e-test', gulp.series(requireNodeVersion(16), clean, 'build-bundle-prod', e2eTestTaskMaker()));
// other tasks
gulp.task(bundleToStdout);
gulp.task('bundle', gulpBundle.bind(null, false)); // used for just concatenating pre-built files with no build step
gulp.task('extract-metadata', function (done) {
/**
* Run the complete bundle in a headless browser to extract metadata (such as aliases & GVL IDs) from all modules,
* with help from `modules/_moduleMetadata.js`
*/
const server = startLocalServer();
import('./metadata/extractMetadata.mjs').then(({default: extract}) => {
extract().then(metadata => {
fs.writeFileSync('./metadata/modules.json', JSON.stringify(metadata, null, 2))
}).finally(() => {
server.close()
}).then(() => done(), done);
});
})
gulp.task('compile-metadata', function (done) {
import('./metadata/compileMetadata.mjs').then(({default: compile}) => {
compile().then(() => done(), done);
})
})
gulp.task('update-metadata', gulp.series('build', 'extract-metadata', 'compile-metadata'));
module.exports = nodeBundle;