-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gruntfile.cjs
executable file
·475 lines (451 loc) · 19.8 KB
/
Gruntfile.cjs
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
const path = require('path');
const fs = require('fs');
const TerserPlugin = require('terser-webpack-plugin');
function hsCamelCase(name) {
if (name.indexOf('hs') === 0) {
name = 'hs' + name.slice(2).charAt(0).toUpperCase() + name.slice(3);
}
return name;
}
const webpackExternals = {
// hsutil: 'hsutil',
// hslayout: 'hslayout',
// hswidget: 'hswidget',
fs: 'fs', // node.fs
path: 'path', // node.path
url: 'url', // node.url
http: 'http', // node.http
crypto: 'crypto', // node.crypto
child_process: 'child_process' // node.child_process
};
/**
* `grunt`: the grunt instance
* `dir`: the directory containing the grunt file
* `dependencies`: modules that this module depends on; used for watching for changes
* `type`: module type:
* - 'app': a runnable web-app
* - 'lib': a library, not intended to run standalone
* - 'node' a runnable node application
* `lib`: optional camelCase lib name; uses `package.json`.name as a default and tries to camel-case it.
*/
module.exports = (grunt) => {
sgc = make(grunt);
grunt.initConfig(sgc);
}
const launchJest = () => require('child_process').spawnSync('./node_modules/.bin/jest', ['-c=jest.config.json', '-i'], {stdio: 'inherit'});
const commit = () => require('child_process').spawnSync('git', ['commit', '-m version bump"', '-a'], {stdio: 'inherit'});
function make(grunt) {
const cfg = require('./gruntCfg.json');
const dir = __dirname;
const dependencies = cfg.dependencies || [];
const type = cfg.type || 'lib';
const devPath = dir.slice(0, dir.indexOf('/dev/')+5);
const pkg = grunt.file.readJSON(dir+'/package.json');
const slash = pkg.name.lastIndexOf('/');
const lib = cfg.lib || hsCamelCase(slash<0? pkg.name : pkg.name.slice(slash+1));
const libPath = lib.toLowerCase();
console.log(`${devPath} > ${lib}: ${type}`);
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('@vamship/grunt-typedoc');
grunt.loadNpmTasks('grunt-ts');
grunt.loadNpmTasks('grunt-webpack');
//------ Add Doc Tasks
grunt.registerTask('noTask', []);
grunt.registerTask('doc', ['clean:docs', 'copy:example', 'typedoc', 'insertExamples', 'sourceCode', 'copy:docs', `${(type === 'app')? 'copy:docs2NPM' : 'noTask'}`]);
//------ Add Staging Tasks
grunt.registerTask('stage', [`${(type === 'app')? 'copy:app2NPM': 'copy:lib2NPM'}`]);
//------ Add Test Tasks
grunt.registerTask('ospec', () => { require('child_process').spawnSync('./node_modules/.bin/ospec', {stdio: 'inherit'}); });
grunt.registerTask('jest', () => launchJest().status===0)
grunt.registerTask('commit', () => [0,commit().status][0])
grunt.registerTask('test', ['clean:cov', 'jest', 'copy:coverage', 'cleanupCoverage']);
//------ Add Coverage Reporting
grunt.registerTask('codecov', codecov);
//------ Support Tasks
grunt.registerTask('coverageReport',['codecov']);
grunt.registerTask('build-html', ['copy:buildHTML']);
grunt.registerTask('build-css', ['less']);
grunt.registerTask('build-base', ['clean:dist', 'clean:docs', 'build-html', 'build-css', 'copy:bin']);
switch(type) {
case 'node':grunt.registerTask('buildMin', ['build-base', 'ts:esm', 'ts:cjs', 'doc', 'stage', 'test', 'coverageReport']);
grunt.registerTask('buildDev', ['build-base', 'ts:esm', 'ts:cjs', 'stage']);
break;
case 'lib': grunt.registerTask('buildMin', ['build-base', 'ts:esm', 'ts:cjs', 'webpack:appDev', 'webpack:appProd', 'doc', 'stage', 'test', 'coverageReport']);
grunt.registerTask('buildDev', ['build-base', 'ts:esm', 'ts:cjs', 'webpack:appDev', 'stage']);
break;
case 'app':
default: grunt.registerTask('buildMin', ['build-base', 'ts:esm', 'webpack:appDev', 'webpack:appProd', 'doc', 'stage', 'test', 'coverageReport']);
grunt.registerTask('buildDev', ['build-base', 'ts:esm', 'webpack:appDev', 'stage']);
}
//------ Entry-point MultiTasks
grunt.registerTask('default', ['product']);
grunt.registerTask('publish', ['product', 'commit']);
grunt.registerTask('dev', ['buildDev']);
grunt.registerTask('build', ['product']);
grunt.registerTask('product', ['buildMin']);
grunt.registerTask('ci', ['build-base', 'ts:cjs', 'test', 'coverageReport']);
grunt.registerTask('help', ['h']);
grunt.registerMultiTask('sourceCode', translateSourcesToHTML);
grunt.registerMultiTask('cleanupCoverage', removeTimestampFromCoverage);
grunt.registerMultiTask('insertExamples', insertExamples);
//------ Add general help
grunt.registerTask('h', 'help on grunt options', () => {
grunt.log.writeln(` grunt: \t make once, don't watch`);
grunt.log.writeln(` grunt watch: \t watch for changes, don't make yet`);
grunt.log.writeln(` grunt make: \t build, test, doc, and stage`);
grunt.log.writeln(` grunt product: make optimized, don't watch; relevant for apps only`);
});
//------ Add Task Configurations
return {
pkg: pkg,
lib: lib,
libPath: grunt.config.process(lib).toLowerCase(),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
clean: {
dist: ['bin'],
docs: ['docs'],
cov: ['_coverage']
},
copy: {
buildHTML: { expand:true, cwd:'src/',
src:['*.html', '*.json'], dest:'bin/'
},
bin:{ files: [
{
expand:true, cwd: 'src/bin', // if present, scaffolding for bin distribution
src:['**/*', '!**/*.ts'], dest:'bin'
// },{
// expand:true, cwd: '.', // if present, scaffolding for bin distribution
// src:['package.json'], dest:'bin'
},{ // mark cjs folder as commonJS to Node:
src:'./packageCJS.json', dest:`./bin/cjs/package.json`
}
]},
// create docs/html files
docs: { files: [
{ expand:true, cwd: devPath+'/local/', // default docs index.html from 'local' admin project
src:['index*.html'], dest:'docs'
},
{ expand:true, cwd: './src/docs', // project-specific docs index*.html
src:['index*.html', '**/index.json'], dest:'docs'
},
{ expand:true, cwd: './', // project-specific docs css files
src:[`${lib}.css*`], dest:'docs'
},
{ expand:true, cwd: './bin', // project-specific docs files: libraries and configurations (*.json)
src:[`${lib}.js`, `${lib}.min.js`, `*.json`], dest:'docs'
}
]},
example:{ expand:true, cwd: 'src/example',
src:['**/*', '!**/*.ts'], dest:'docs/example'
},
coverage: {files: [
{ expand:true, cwd: '_coverage', // copy coverage into docs
src:['**/*'], dest:`docs/data/src/${lib}/coverage` },
{ expand:true, cwd: '_coverage', // copy dummy file to docs/data/src to avoid 'src/lib' entry in github
src:['lcov.info'], dest:`docs/data/src` },
]},
lib2NPM: { files: [
{ expand:true, cwd: 'bin', // copy everything from bin
src:['**/*.*'], dest:`node_modules/${libPath}/bin/` },
{ expand:true, cwd: './', // copy everything from bin
src:['package.json', '*.md'], dest:`node_modules/${libPath}/` }
]},
app2NPM: { files: [
{ expand:true, cwd: 'bin', // copy everything from bin
src:['**/*.*'], dest:`node_modules/${libPath}/bin/` },
{ expand:true, cwd: devPath+'/staging/', // index.html
src:['index.html'], dest:`node_modules/${libPath}/` }
]},
docs2NPM: { files: [ // copy the module's docs to npm
{ expand:true, cwd: 'bin', // copy everything from bin
src:[`**/${lib}.*`], dest:`docs` },
{ expand:true, cwd: 'docs',
src:['**/*'], dest:`node_modules/${libPath}/docs`}
]}
},
less: {
options: {
sourceMap: true,
sourceMapURL: '<%= lib %>.css.map'
},
css: {
files: [{
cwd: './', src: './src/css/<%= pkg.name %>.less', dest: './bin/<%= lib %>.css'
}]
},
example: {
files: {
'docs/example/<%= pkg.name %>.css': `src/example/${libPath}.less`
}
}
},
ts: {
options: {
target: "ESNext", // webpack 4.44 does not yet support a?.b?.c
module: "esnext",
rootDir: "./src",
moduleResolution: "node",
esModuleInterop: true,
inlineSourceMap: true,
removeComments: true,
noImplicitAny: true,
declaration: true,
suppressImplicitAnyIndexErrors: true
},
esm : {
outDir: "bin/esm",
src: ["src/**/*.ts", "!src/**/*.spec.ts", "!src/**/*.jest.ts", "!src/example/*.ts"],
},
cjs : {
options: { module: "CommonJS" },
outDir: "bin/cjs",
src: ["src/**/*.ts", "!src/**/*.spec.ts", "!src/**/*.jest.ts", "!src/example/*.ts"],
},
example : {
outDir: "docs/example",
src: ["src/example/*.ts"],
}
},
typedoc: {
code: {
options: {
target: 'es6',
module: 'commonjs',
moduleResolution: "node",
esModuleInterop: true,
json: `docs/data/${lib}.json`,
mode: 'modules',
name: `${lib}`,
},
src: ['src/**/*.ts', '!src/**/*.*.ts', '!src/example/**/*'] // no specs, no example
}
},
webpack: {
options: {
stats: !process.env.NODE_ENV || process.env.NODE_ENV === 'development'
},
appProd: {
mode: 'production',
entry: {
main: './bin/esm/index.js'
},
module: {
rules:[
{ test: /\.m?js/, resolve: { fullySpecified: false } }
]
},
// optimization: {
// splitChunks: {
// chunks: 'all'
// },
// },
output: {
//filename: `[name].bundle.js`,
filename: `${lib}.min.js`,
//chunkFilename: '[name].bundle.js',
path: path.resolve(dir, './bin'),
library: lib,
libraryTarget: "this"
},
externals: webpackExternals,
plugins: [
new TerserPlugin({
terserOptions: {
ecma: 6,
module: true,
mangle: false
},
parallel: true
})
]
},
appDev: {
mode: 'development',
entry: './bin/esm/index.js',
devtool: "inline-source-map",
module: {
rules:[
{ test: /\.m?js/, resolve: { fullySpecified: false } }
]
},
output: {
filename: `${lib}.js`,
path: path.resolve(dir, './bin'),
library: lib,
libraryTarget: "this"
},
externals: webpackExternals,
}
},
sourceCode: {
main: { // translate all *.ts files in src *.htmlfilesin doc
expand: true,
cwd: 'src/',
src: ['**/*.ts', '!**/*.jest.ts', '!**/*.test.ts', '!**/*.spec.ts'],
dest: `docs/data/src/${lib}/`,
rename: (dest, src) => dest + src.replace('.ts','.html')
}
},
insertExamples: {
main: { // insert example code into comments
cwd: 'src/',
src: ['**/*.js', '**/*.css'],
dest: `docs/data/${lib}.json`
}
},
cleanupCoverage: {
main: { // translate all *.ts files in src *.html files in doc
expand: true,
cwd: `docs/data/src/${lib}/coverage`,
src: ['**/*.html'],
dest:''
}
},
watch: {
dependencies: {
files: dependencies.map(d => `./node_modules/${d.toLowerCase()}/bin/${d}.js`),
tasks: ['dev']
},
gruntfile: {
files: ['Gruntfile.js', __dirname+'/sharedGruntConfig.js'],
tasks: ['dev']
},
js: {
files: ['src/**/*.ts', '!src/**/*.spec.ts', '!src/**/*.jest.ts', '!src/**/*.less'],
tasks: ['dev']
},
less: {
files: ['src/**/*.less'],
tasks: ['build-css', 'stage']
},
html: {
files: ['src/**/*.html'],
tasks: ['build-html', 'stage']
},
jest: {
files: ['src/**/*.jest.ts'],
tasks: ['jest']
}
}
}
function translateSourcesToHTML() {
// returns a 4-character, right aligned. line number
function lineNum(num) { return (' '+(num)).substr(-4).replace(/( )/g, ' '); }
function wrapLine(line, i) {
return `<p id=${i+1} class="line"><span>${lineNum(i+1)}</span>${line}</p>`;
}
function quote(content) { return `<quote>${content}</quote>`; }
function comment(content) {
return content
.split('\n')
.map(l => `<comment>${l}</comment>`)
.join('\n');
}
// function module(content) { return `<module>${content}</module>`; }
function processFile(srcFile, destDir) {
const src = ''+srcFile;
const i = src.lastIndexOf('/');
const file = (i>=0)? src.slice(i+1) : src;
let content = grunt.file.read(srcFile)
.replace(/\</g, '<') // replace '<' before adding `comment'
.replace(/\>/g, '>') // replace '>' before adding `comment'
.replace(/( )/g, ' ') // preserve whitespaces
.replace(/(\/\/.*?)<\/code>/g, comment) // color code // comments
.replace(/\/\/.*?\n/g, comment) // color code // comments
.replace(/\/\*[\s\S]*?\*\//g, comment) // color code /*...*/ comments
.replace(/'[^']*?'/g, quote) // color code '...' strings
.replace(/"[^"]*?"/g, quote) // color code "..." strings
.split('\n') // array of lines
.map(wrapLine) // wrap each line into some formatting
.join('\n') // join lines into a complete string
;
grunt.log.writeln(` ${srcFile} --> ${destDir}`);
grunt.file.write(destDir, `
${intro}
<h1>${file}</h1>
<div class='listing'><code>${content}</code></div>
${extro}
`);
}
const style = `
body { overflow:hidden;}
h1 { font-family: Arial, sans-serif; font-size: 24px; color: #44a; }
p { margin:0; padding:0; }
br { margin:0; padding:0; }
.line {
white-space: nowrap;
height:16px;
}
.line>span {
display:inline-block; background-color:#eef; height:100%;
margin: 0 5px 0 0; padding-right: 5px; color:#999;
}
comment {color: #080;} module {color: #804;}
quote {color: #008;} comment>quote {color: #080;}
.listing { margin: 10px; border: 1px solid #ccc;
font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, Courier, monospace;
font-size: 14px;
overflow:scroll;
height:90%;
}
code { padding: 5px 0;}
`;
const intro = `<html><style>${style.trim()}</style></html><body>`;
const extro = `</body>`;
let files = this.files;
files.map(file => processFile(file.src, file.dest));
writeIndexJson();
grunt.log.writeln(`converted ${files.length} files`);
}
function removeTimestampFromCoverage() {
const replaceFooter = content => content.replace(/<div class='footer[\s\S]*?<\/div>/, '');
const addLibName = content => content.replace(/All files/g, `${lib}: All files`);
this.files.map(f => {
let content = ''+fs.readFileSync(f.src[0]);
// console.log(`${lib}: ${f.src[0]}`);
content = replaceFooter(content);
content = addLibName(content);
fs.writeFileSync(f.src[0], content);
});
console.log(`cleaned ${this.files.length} files`);
}
function codecov() {
const cp = require('child_process');
try {
const codecov = require('./.codecov.json');
if (codecov) {
const result = cp.spawnSync(`bash <(curl -s https://codecov.io/bash) -t ${codecov.token}`, {stdio: 'inherit', shell:'/bin/bash'});
console.log(`status: ${result.status}`);
if (result.stderr) { console.log(`error: ${result.stderr}`); }
}
} catch(e) { console.log(`...skipped`); }
}
function writeIndexJson() {
grunt.file.write('docs/data/index.json', `{"docs": ["${lib}.json"], "title": "HS Libraries"}`);
}
function insertExamples() {
this.files.map(f => {
let changed = false;
const content = grunt.file.read(f.dest);
const result = content.replace(/ximport='(.*?)'/g, (match, p1) => {
const i = f.src.indexOf(p1);
if (i>=0) {
changed = true;
grunt.log.writeln(`substituting ${match} = ${p1} for ${f.cwd+f.src[i]}`);
return grunt.file.read(f.cwd+f.src[i]).replace(/\n/g, "\\n").replace(/\"/g, "\\\"");
}
return '';
});
if (changed) { grunt.file.write(f.dest, result); }
})
}
};