forked from foumart/JS.13kGames.2024_Odyssey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
364 lines (327 loc) · 12.6 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
const { src, dest, series } = require('gulp');
const gulp = require('gulp');
const concat = require('gulp-concat');
const htmlmin = require('gulp-htmlmin');
const replace = require('gulp-string-replace');
const cleanCSS = require('gulp-clean-css');
const browserSync = require('browser-sync').create();
const closureCompiler = require('google-closure-compiler').gulp();
const argv = require('yargs').argv;
const gulpif = require('gulp-if');
const advzip = require('gulp-advzip');
const roadroller = require('roadroller');
const packageJson = require('./package.json');
// import ES modules
let imagemin, optipng, svgo, gifsicle, mozjpeg;
let del, zip, js, css;
const replaceOptions = { logs: { enabled: false } };
const timestamp = getDateString();
// Data taken directly from package.json
const name = packageJson.name;
const version = packageJson.version;
const id_name = `${name.replace(/\s/g, '')}`;//_${getDateString(true)}
const title = packageJson.title || name;
const descr = packageJson.description || name + " description";
const link = packageJson.link || "index.html";
const keywords = packageJson.keywords || "";
const author = packageJson.author.name || "";
const iconExtension = packageJson.iconExtension;
const iconType = packageJson.iconType;
const iconSize = packageJson.iconSize;
const orientation = packageJson.orientation;
const replacedIds = [];
// Script Arguments:
// --dir: set the output directory
const dir = argv.dir || 'public';
// --test: don't use versioned zip file - useful for fast testing.
const test = argv.test != undefined ? true : false;
// --pwa: enable progressive web app - use a service worker, webmanifest and pwa initialization scripts. Adds 842 bytes.
const pwa = argv.pwa != undefined ? true : false;
// --debug: display service worker logs
const debug = argv.debug != undefined ? true : false;
// --roadroll: use a JS packer for up to 15% compression
const roadroll = argv.roadroll != undefined ? true : false;
// --prod: replaces the start_url in manifest to make PWA work on the js13k platform, otherwise using to index.html.
const prod = argv.prod != undefined ? true : false;
// --mobile: should html` tags for mobile be included. Adds 42 bytes.
const mobile = argv.mobile != undefined || argv.all != undefined ? `
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-icon" sizes="${iconSize}x${iconSize}" href="ico.${iconExtension}"/>` : false;
// --social: should html tags for social media be included. Adds around 100 bytes, depending on description length.
// TODO: quotes should not be removed for content that has space characters
const social = argv.social != undefined || argv.all != undefined ? `
<meta name="application-name" content="${title}"/>
<meta name="description" content="${descr}"/>
<meta name="keywords" content="${keywords}"/>
<meta name="author" content="${author}"/>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="${title}"/>
<meta name="twitter:description" content="${descr}"/>
<meta name="twitter:image" content="ico.${iconExtension}"/>` : false;
// Prepare a web icon to be used by html and pwa
function ico(callback) {
(async () => {
// Keep the imports, even if not copying an icon, the gulp image modules are needed for the assets.
const gulpImageminModule = await import('gulp-imagemin');
imagemin = gulpImageminModule.default;
gifsicle = gulpImageminModule.gifsicle;
mozjpeg = gulpImageminModule.mozjpeg;
optipng = gulpImageminModule.optipng;
svgo = gulpImageminModule.svgo;
if (!mobile) {
return callback();
}
if (iconExtension == "svg") {
src(['src/ico.svg'], { allowEmpty: true })
.pipe(imagemin({silent: true, verbose: false}, [svgo()]))
.pipe(dest(dir + '/'))
.on('end', callback)
} else {
src(['src/ico.png'], { allowEmpty: true, encoding: false })
.pipe(imagemin({silent: true, verbose: false}, [optipng()]))
.pipe(dest(dir + '/'))
.on('end', callback)
}
})();
}
// Compress other graphical assets (if any)
function assets(callback) {
src(['src/assets/*'], { allowEmpty: true, encoding: false })
.pipe(imagemin({silent: true, verbose: false}, [optipng(), gifsicle(), mozjpeg(), svgo()]))
.pipe(dest(dir + '/assets/'))
.on('end', callback);
}
// Prepare service worker script
function sw(callback) {
if (pwa) {
src(['resources/service_worker.js'], { allowEmpty: true })
.pipe(replace('var debug;', `var debug = ${debug ? 'true' : 'false'};`, replaceOptions))
.pipe(replace('{ID_NAME}', id_name, replaceOptions))
.pipe(replace('{VERSION}', version, replaceOptions))
.pipe(replace('{ICON_EXTENSION}', iconExtension, replaceOptions))
.pipe(gulpif(!debug, replace('caches', 'window.caches', replaceOptions)))
.pipe(gulpif(!debug,
closureCompiler({
compilation_level: 'ADVANCED_OPTIMIZATIONS',
warning_level: 'QUIET',
language_in: 'ECMASCRIPT6',
language_out: 'ECMASCRIPT6'
})
))
.pipe(gulpif(!debug, replace('window.caches', 'caches', replaceOptions)))
.pipe(gulpif(!debug, replace('"use strict";', '', replaceOptions)))
.pipe(concat('sw.js'))
.pipe(dest(dir + '/'))
.on('end', callback)
} else {
callback();
}
}
// Compile the pwa initialization script (if needed) as well as game logic scripts
function app(callback) {
const scripts = [
'src/scripts/*.js'
];
if (pwa) {
scripts.unshift('resources/sw_init.js');
}
scripts.unshift('resources/app_init.js');
src(scripts, { allowEmpty: true })
.pipe(replace('let _debug;', `let _debug = ${debug ? 'true' : 'false'};`, replaceOptions))
.pipe(gulpif(pwa, replace('service_worker', 'sw', replaceOptions)))
.pipe(replace('{VERSION}', version, replaceOptions))
.pipe(gulpif(!pwa, replace('function init', 'window.addEventListener("load",init);function init', replaceOptions)))
.pipe(gulpif(!debug,
closureCompiler({
compilation_level: 'ADVANCED_OPTIMIZATIONS',
warning_level: 'QUIET',
language_in: 'ECMASCRIPT_2017',
language_out: 'ECMASCRIPT6',
externs: 'resources/externs.js'
})
))
.pipe(concat('app.js'))
.pipe(dest(dir + '/tmp/'))
.on('end', callback);
}
// Minify CSS
function cs(callback) {
src('src/styles/*.css', { allowEmpty: true })
.pipe(cleanCSS())
.pipe(concat('temp.css'))
.pipe(dest(dir + '/tmp/'))
.on('end', callback)
}
// Prepare web manifest file
function mf(callback) {
if (pwa) {
src('resources/mf.webmanifest', { allowEmpty: true })
.pipe(replace('service_worker', 'sw', replaceOptions))
.pipe(replace('{TITLE}', title, replaceOptions))
.pipe(replace('{LINK}', prod ? link : "index.html", replaceOptions))
.pipe(replace('{ICON_EXTENSION}', iconExtension, replaceOptions))
.pipe(replace('{ICON_TYPE}', iconType, replaceOptions))
.pipe(replace('{ICON_SIZE}', iconSize, replaceOptions))
.pipe(replace('{ORIENTATION}', orientation, replaceOptions))
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(dest(dir + '/'))
.on('end', callback);
} else {
callback();
}
}
// Read the temporary JS and CSS files and compress the javascript with Roadroller
async function mangle() {
const fs = require('fs');
css = fs.readFileSync(dir + '/tmp/temp.css', 'utf8');
js = fs.readFileSync(dir + '/tmp/app.js', 'utf8');
if (!debug) {
//
const elementIds = ['mainDiv', 'bgrCanvas', 'gameCanvas', 'gameContainer', 'uiDiv'];
for (let i = 0; i < elementIds.length; i++) {
const regex = new RegExp(elementIds[i], 'g');
js = js.replace(regex, String.fromCharCode(i + 97) + "z");
replacedIds.push(String.fromCharCode(i + 97) + "z");
}
// Rename CSS classes with a single letter starting from letter "a"..
const classIds = ['css_button', 'css_icon', 'css_space', 'css_controls'];
for (let i = 0; i < classIds.length; i++) {
const regex = new RegExp(classIds[i], 'g');
css = css.replace(regex, String.fromCharCode(i + 97));
js = js.replace(regex, String.fromCharCode(i + 97));
}
if (roadroll) {
const packer = new roadroller.Packer(
[{
data: js,
type: 'js',
action: 'eval'
}],
{
selectors: 32,
maxMemoryMB: 640,
precision: 16,
recipLearningRate: 1500,
modelMaxCount: 3,
modelRecipBaseCount: 30,
numAbbreviations: 64,
allowFreeVars: 0
}
);
await packer.optimize();
const { firstLine, secondLine } = packer.makeDecoder();
js = firstLine + secondLine;
}
} else {
let dummyPromise = new Promise(function(resolve) {
setTimeout(resolve, 1);
})
await dummyPromise;
}
}
// Inline JS and CSS into index.html
function pack(callback) {
let stream = src('src/index.html', { allowEmpty: true });
stream
.pipe(gulpif(!pwa, replace('<link rel="icon" type="{ICON_TYPE}" sizes="any" href="ico.{ICON_EXTENSION}">', '', replaceOptions)))
.pipe(gulpif(!debug, replace('mainDiv', replacedIds[0], replaceOptions)))
.pipe(gulpif(!debug, replace('bgrCanvas', replacedIds[1], replaceOptions)))
.pipe(gulpif(!debug, replace('gameCanvas', replacedIds[2], replaceOptions)))
.pipe(gulpif(!debug, replace('gameContainer', replacedIds[3], replaceOptions)))
.pipe(gulpif(!debug, replace('uiDiv', replacedIds[4], replaceOptions)))
.pipe(replace('{TITLE}', title, replaceOptions))
.pipe(replace('{ICON_EXTENSION}', iconExtension, replaceOptions))
.pipe(replace('{ICON_TYPE}', iconType, replaceOptions))
.pipe(replace('rep_social', social != false ? social : '', replaceOptions))
.pipe(replace('rep_mobile', mobile != false ? mobile : '', replaceOptions))
.pipe(gulpif(!pwa, replace('<link rel="manifest" href="mf.webmanifest">', '', replaceOptions)))
.pipe(htmlmin({ collapseWhitespace: true, removeComments: true, removeAttributeQuotes: true }))
.pipe(replace('rep_css', '<style>' + css + '</style>', replaceOptions))
.pipe(replace('rep_js', '<script>' + js + '</script>', replaceOptions))
.pipe(concat('index.html'))
.pipe(dest(dir + '/'))
.on('end', callback);
}
// Delete the public folder at the beginning
function prep(callback) {
(async () => {
del = (await import('del')).deleteAsync;
del(dir);
callback();
})();
}
// Delete the temporary folder generated during packaging
function clean(callback) {
(async () => {
del = (await import('del')).deleteAsync;
del(dir + '/tmp/');
callback();
})();
}
// Package zip (exclude any fonts that are used locally, like Twemoji.ttf)
function archive(callback) {
if (debug) callback();
else {
(async () => {
zip = (await import('gulp-zip')).default;
src([dir + '/*', dir + '/*/*', '!'+ dir + '/*.ttf'], { allowEmpty: true })
.pipe(zip(test ? 'game.zip' : 'game_' + timestamp + '.zip'))
.pipe(advzip({ optimizationLevel: 4, iterations: 10 }))
.pipe(dest('zip/'))
.on('end', callback);
})();
}
}
// Output the zip filesize
function check(callback) {
if (debug) callback();
else {
var fs = require('fs');
const size = fs.statSync(test ? 'zip/game.zip' : 'zip/game_' + timestamp + '.zip').size;
const limit = 1024 * 13;
const left = limit - size;
const percent = Math.abs(Math.round((left / limit) * 10000) / 100);
console.log(` ${size} ${left} bytes ${left < 0 ? 'overhead' : 'remaining'} (${percent}%)`);
callback();
}
}
// Watch for changes in the source folder
function watch(callback) {
browserSync.init({
server: './public',
ui: false,
port: 8080
});
gulp.watch('./src').on('change', () => {
exports.sync();
});
callback();
};
// Reload the browser sync instance, or run a new server with live reload
function reload(callback) {
if (!browserSync.active) {
watch(callback);
} else {
browserSync.reload();
callback();
}
}
// Helper function for timestamp and naming
function getDateString(shorter) {
const date = new Date();
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day =`${date.getDate()}`.padStart(2, '0');
if (shorter) return `${year}${month}${day}`;
const signiture =`${date.getHours()}`.padStart(2, '0')+`${date.getMinutes()}`.padStart(2, '0')+`${date.getSeconds()}`.padStart(2, '0');
return `${year}${month}${day}_${signiture}`;
}
// Exports
exports.default = series(prep, ico, sw, app, cs, mf, mangle, assets, pack, clean, archive, check, watch);
exports.sync = series(ico, app, cs, mangle, assets, pack, clean, reload);
exports.zip = series(archive, check);
/*
JS13K Template Gulpfile by Noncho Savov
https://www.FoumartGames.com
*/