-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
744 lines (612 loc) · 17.7 KB
/
index.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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
const { resolve, basename, dirname } = require('path')
const { DllReferencePlugin, DllPlugin } = require('webpack')
const { ChainedMapExtendable, dopemerge } = require('chain-able')
const { isRel, isAbs, write, exists } = require('flipfile')
const { tillNowSatisfies, uniq, lastModified, flatten, log } = require('./deps')
const timer = require('fliptime')
const flipcache = require('flipcache')
const fliphash = require('fliphash')
let cache
let hashcache
/**
* gets modified time
* absolute path
* stores in cache to remember all edits
*
* @param {GlobFile} file
* @return {GlobFile}
*/
function saveModified(file) {
// file data
const modified = new Date(file.mtime).getTime()
const abs = file.abs
// keys
const key = 'modifiedLog.' + fliphash(abs)
const keyRecord = key + '.record'
// if not set
if (cache.has(key) === false) cache.set(key, { record: [], meta: {} })
// add uniq records
const record = cache.get(keyRecord)
if (record.includes(modified) === false) record.push(modified)
return file
}
/**
* @TODO
* - [ ] configure lib name & target etc
*
* @classdesc
* internally choose whether to make it an array and add dll plugin first
* if there is no bundle built, then only export dll plugin
* then run the build command again
*
* OR
*
* export both
* and store the manifests
*/
class DLL extends ChainedMapExtendable {
// --- setup ---
/**
* @param {any} parent
* @return {DLL} @chainable
*/
static init(parent) {
return new DLL(parent)
}
/**
* @param {any} parent
*/
constructor(parent) {
super(parent)
timer.start('dll')
this.extend([
'og',
'files',
'deps',
'refs',
'dlls',
'context',
'pkg',
'staleTime',
'everyX',
'shouldBeUsed',
])
.og(false)
.files([])
.deps([])
.refs([])
.dlls([])
.output('output')
.context('.')
.lastModifiedFilter({ hours: 2 })
.staleTime({ days: 1 })
.everyX(33)
// this.files = new ChainedSet(this)
}
// --- building ---
/**
* @TODO:
* - [ ] time globbing through 1000 files to check edited
* - [ ] need to say how many bundles -
* default to 1 which means single arr entry
*
* @param {string} [findGlob=string]
* @param {Function} [filter=null]
* @return {DLL} @chainable
*/
find(findGlob = null, filter = null) {
const glob = require('globby')
if (findGlob) this.set('srcGlob', findGlob)
const { srcGlob, lastModifiedFilter, dir } = this.entries()
const { lstatSync } = require('fs')
log.green('glob:').fmtobj(srcGlob).echo(this.get('debug') || true)
// call the glob
const g = new glob.sync(srcGlob, { absolute: true, cwd: __dirname })
// filter results using stats
const files = g.filter(abs => {
// put as an object for use in saveModified & modifiedFilter
const obj = {
abs,
stats: lstatSync(abs),
mtime: lstatSync(abs).mtime,
}
// use filter if we have it
if (filter !== null) {
if (filter(abs, obj) !== true) {
return false
}
}
// filter
if (lastModifiedFilter(obj) === false) return false
// save it to the cache
saveModified(obj)
return abs
})
// seemingly if you use glob readDirSync twice
// it mutates the original array o.o
return this.files(files.slice(0))
}
/**
* @desc filter with callback when available
* default to bundledDependencies when they exist
* fallback to dependencies
* dependencies, devDependencies, allDependencies
* @param {Function<Array<?string>, Array<?string>> | Array<string>} [filter=null]
* @return {DLL} @chainable
*/
pkgDeps(filter = null) {
// if set as a path, use it, otherwise, require it
let pkg = this.get('pkg')
log.yellow('pkgPath:').data(pkg).echo(this.get('debug'))
if (typeof pkg === 'string' && pkg.includes('/') && exists(pkg)) {
pkg = require(pkg)
log.yellow('pkg:').data(pkg).echo(this.get('debug'))
}
// gather deps
const bundled = Object.keys(pkg.bundledDependencies || {})
const deps = Object.keys(pkg.dependencies || {})
const dev = Object.keys(pkg.devDependencies || {})
const all = deps.concat(dev).concat(bundled)
let depsToUse = bundled
// use filter when available
if (filter !== null) {
if (typeof filter === 'function') {
depsToUse = filter(deps, dev, all)
} else if (Array.isArray(filter)) {
depsToUse = filter
}
} else if (!depsToUse.length) {
// otherwise, if no bundled, fallback to deps
depsToUse = deps
}
// use it when we have it
if (depsToUse && depsToUse.length) {
return this.deps(depsToUse)
}
// if no deps, ignore
return this
}
// --- dev/cache/debug ---
/**
* @desc clears the cache
* @see flipfile/del
* @return {DLL} @chainable
*/
clearCache() {
const fs = require('flipfile/extra')
const { removeSync } = fs
removeSync(resolve(this.get('dir'), './.fliphub'))
return this
}
/**
* @param {Array<string>} files file paths to bust cache on
* @return {DLL} @chainable
*/
cacheBustingFiles(files) {
return this.set('cacheBustingFiles', files)
}
/**
* @param {Object} ago
* @return {DLL} @chainable
*/
lastModifiedFilter(ago) {
return this.set('lastModifiedFilter', lastModified(ago))
}
/**
* @private
*
* @desc maps entries to manifest json
* saves in cache file
* @modifies this.manifests
*
* @see DLL.dllRefPlugins, DLL.dllPlugins, flipcache
* @return {DLL} @chainable
*/
saveManifests() {
const { output, dir } = this.entries()
// by ref
const cacheManifests = cache.get('manifests')
// map entry to manifest.json
const manifests = Object.keys(this.entry()).map(entry => {
// map to manifest json
const file = resolve(output, entry + '-manifest.json')
// resolve with clients directory
const resolved = resolve(dir, file)
// add to cached file
cacheManifests.push(resolved)
return resolved
})
// save
this.set('manifests', manifests)
// unique & persist the data
cache.set('manifests', cacheManifests.filter(uniq)).write()
return this
}
// --- data ---
/**
* @since 0.1.0
* @desc use filename, to resolve paths to dir, and
* @example dll.filename(__filename)
* @param {string} filename absolute path, __filename
* @return {DLL} @chainable
*/
filename(filename) {
return this.dir(dirname(filename)).set('filename', filename)
}
/**
* @TODO should cache bust on pkg if it does not already
*
* @desc sets up resolved paths
* @modifies this.pkg
* @modifies this.cacheBustingFiles
* @param {string} dir directory to resolve paths to
* @return {DLL} @chainable
*/
dir(dir) {
// paths
const file = resolve(dir, './.fliphub/manifests.json')
const cachefile = resolve(dir, './.fliphub/manifestscache.json')
const pkgPath = resolve(dir, './package.json')
const webpackConfig = resolve(dir, './webpack.config.js')
// store pkg path and dir
this.set('dir', dir)
if (this.has('pkg') === false) this.set('pkg', pkgPath)
// only setup cache once
if (cache !== null && cache !== undefined) return this
cache = flipcache
.to(file)
.json()
.load()
.setIfNotEmpty('manifests', [])
.setIfNotEmpty('modifiedLog', {})
.setIfNotEmpty('builds', [])
.setIfNotEmpty('lastBuilt', Date.now())
let busts = [require.main.filename, this.get('pkg')]
if (exists(webpackConfig)) {
busts.push(webpackConfig)
}
if (this.has('cacheBustingFiles') === true) {
busts = busts.concat(this.get('cacheBustingFiles'))
}
log
.emoji('cache')
.blue('cacheBustingFiles:')
.data({ busts })
.echo(this.get('debug'))
try {
hashcache = flipcache
.hashCache(cachefile)
.debug(this.get('debug'))
.hash(dir)
.bustOnChange(busts)
.setContent(cache.toString())
} catch (e) {
log.error(e).echo()
}
return this
}
/**
* @desc override the output path in the webpack config
* @param {string} output absolute path
* @return {DLL} @chainable
*/
output(output) {
if (isRel(output)) output = resolve(output)
return this.set('output', output)
}
/**
* @see DLL.ensureSetup, DLL.appConfig, DLL.dllConfig, DLL.output
* @param {Object} webpackConfig
* @return {DLL} @chainable
*/
config(webpackConfig) {
this.ensureSetup()
// set original
this.set('appConfig', webpackConfig)
// deref
const config = Object.assign({}, {}, webpackConfig)
config.entry = Object.assign({}, {}, config.entry)
config.output = Object.assign({}, {}, config.output)
// change entry to use the dll entries instead
delete config.entry
let outputPath = this.get('output')
// clean output to use dll output
if (config.output && config.output.path) {
outputPath = config.output.path
this.output(outputPath)
}
delete config.output
// use dll output
config.output = {
path: outputPath,
library: '[name]_dll_lib',
filename: '[name].dll.js',
}
if (config.target === 'node') {
this.set('node', true)
config.output.libraryTarget = 'commonjs2'
}
// set it
this.set('dllConfig', config)
return this
}
// --- statics ---
/**
* @desc for multiple configs
* @param {Array<Object>} configs
* @param {function} cb
* @return {Array<Object>}
*/
static configs(configs, cb) {
const conf = configs.map(config => cb(new DLL(), config))
return flatten(conf)
}
/**
* @desc for easy auto mode
* @param {Object} config
* @param {string} [dir=process.cwd()]
* @return {Array<Object>}
*/
static auto(config, dir = process.cwd()) {
return new DLL()
.dir(dir)
.config(config)
.find('src/**/*.+(js|jsx|ts|tsx)')
.pkgDeps()
.toConfig()
}
// --- webpack config ---
/**
* @private
* @return {Object<vendor, internal>}
*/
entry() {
const { deps, files } = this.entries()
log.data({ files, deps }).green('entry files, deps').echo(this.get('debug'))
const entry = {
vendor: deps,
internal: files,
}
if (entry.vendor.length === 0) delete entry.vendor
if (entry.internal.length === 0) delete entry.internal
if (Object.keys(entry).length === 0) {
log.red('had no entries sorry eh').echo() // this.get('debug')
this.set('og', true)
return false
}
return entry
}
/**
* @tutorial https://webpack.js.org/plugins/dll-plugin/#dllreferenceplugin
* @desc creates an array of DLLReferencePlugins
* @return {Array<DLLReferencePlugin>}
*/
dllRefPlugins() {
const plugins = this.get('manifests')
.map(file => {
if (exists(file) === false) return undefined
const args = {
context: this.get('context'),
manifest: require(file),
}
if (this.get('node') === true) {
args.sourceType = 'commonsjs2'
}
return new DllReferencePlugin(args)
})
.filter(plugin => plugin !== undefined)
if (plugins.length === 0) {
log
.bold('had no dll manifests')
.data('they have been created, run build again to use them.')
.echo(this.get('debug'))
}
return plugins
}
/**
* @tutorial https://webpack.js.org/plugins/dll-plugin/#dllplugin
* @see dllReferencePlugins
* @return {Array<DLLPlugin>}
*/
dllPlugins() {
const args = {
// The path to the manifest file which maps between
// modules included in a bundle and the internal IDs
// within that bundle
path: resolve(this.get('output'), './[name]-manifest.json'),
// The name of the global variable which the library's
// require function has been assigned to. This must match the
// output.library option above
name: '[name]_dll_lib',
}
return [new DllPlugin(args)]
}
// --- analysis/determining/metadata ---
/**
* @desc defaults the dir to pwd
* @return {DLL} @chainable
*/
ensureSetup() {
if (this.has('dir') === false) {
console.log('make sure you set .dir, defaulting to process.cwd()')
this.dir(process.cwd())
}
return this
}
/**
* @TODO: these settings should be in interactive, and saved to pkgjson
* decorate should call this... like in top todos
* should be triggered by both configs
*
* @return {DLL} @chainable
*/
build() {
const build = {}
build.dll = this.shouldBuildDLL()
build.time = Date.now()
cache.get('builds').push(build)
cache.write()
return this
}
/**
* @private
* @desc
* - checks cache.shouldbeused
* - checks staleTime
* - checks whether it is built
* @return {boolean}
*/
shouldBuildDLL() {
if (this.has('shouldBeUsed') === true) return this.get('shouldBeUsed')
const staleTime = this.get('staleTime')
const everyX = this.get('everyX')
const builds = cache.get('builds')
log.yellow('builds.length').verbose(builds.length).echo(this.get('debug'))
// if we have no builds, build the first one
if (builds.length === 0) {
this.set('shouldBeUsed', true)
return true
}
const index = builds.length - 1
const last = builds[index]
const { time, dll } = last
let canBeUsed = false
try {
canBeUsed = hashcache.canBeUsed()
} catch (e) {
// ignoring for now
log.data(e).red('error').echo(false)
canBeUsed = true
}
log
.yellow('second - hash')
.verbose({ index, last, canBeUsed })
.echo(this.get('debug'))
// require files changed etc
if (canBeUsed === false) return true
// if dll was not in last 10 builds
if (builds.length >= everyX) {
const dllInLastBuilds = builds
.slice(-everyX)
.map(build => !!build.dll)
.includes(true)
// @NOTE: think about this
// this.clearCache()
log
.yellow('third - everyX')
.verbose({ dllInLastBuilds, everyX, minus: -everyX })
.echo(this.get('debug'))
if (dllInLastBuilds === false) {
this.set('shouldBeUsed', true)
return true
}
}
log
.yellow('fourth - diffs')
.verbose({ staleTime, time, tillNow: tillNowSatisfies(time, staleTime) })
.echo(this.get('debug'))
// check time diffs
if (tillNowSatisfies(time, staleTime) === true) {
this.set('shouldBeUsed', true)
return true
}
const manifestFilesExist = !!cache.get('manifests').filter(exists).length
log
.yellow('fifth - manifests exist')
.verbose({ manifestFilesExist })
.echo(this.get('debug'))
if (manifestFilesExist === false) {
this.set('shouldBeUsed', true)
return true
}
this.set('shouldBeUsed', false)
// default do not build
return false
}
/**
* @desc optionally adds dll config
* adds appConfig
*
* @see DLL.saveManifests
* @see DLL.shouldBuildDLL
* @see DLL.build
* @see DLL.dllConfig
* @see DLL.appConfig
* @return {Array<WebpackConfigObject>}
*/
toConfig() {
if (this.get('og') === true || this.entry() === false) {
log.yellow('og mode: returning original config').echo(this.get('debug'))
return [this.get('appConfig')]
}
const configs = []
this.build()
this.saveManifests()
const shouldBuildDLL = this.shouldBuildDLL()
log.green('shouldBuildDLL:').data(shouldBuildDLL).echo(this.get('debug'))
if (shouldBuildDLL) configs.push(this.dllConfig())
configs.push(this.appConfig())
const ms = timer.stop('dll').msTook('dll')
log.emoji('timer').bold('d-l-l took: ' + ms + 'ms').echo()
return configs
}
// --- exports/transformed/results ---
/**
* @private
* @desc original webpack config, ensures there are plugins
* @see DLL.config, DLL.dllRefPlugins, DLL.dllConfig
* @return {WebpackConfigObject}
*/
appConfig() {
const config = dopemerge(this.get('appConfig'), {
plugins: [],
})
config.plugins = config.plugins.concat(this.dllRefPlugins())
return config
}
/**
* @NOTE seemingly there is an issue deepmerging these object
* plugin arrays if plugins is a single object in both
*
* @desc used when exporting two configs,
* this config is for building the dll bundle
* @see DLL.entry, DLL.dllPlugins, DLL.config
* @return {WebpackConfigObject}
*/
dllConfig() {
const config = dopemerge(this.get('dllConfig'), {
entry: this.entry(),
plugins: [],
})
config.plugins = config.plugins.concat(this.dllPlugins())
return config
}
/**
* @see https://github.com/webpack/docs/wiki/list-of-plugins#using-dlls-via-nodejs
* @desc because dll references don't get required properly on node
* @return {string} path to generated output
*/
nodeEntry() {
const glob = require('flipfile/glob')
const output = this.get('output')
const outputGlob = output + '/*.js'
const files = cache
.get('manifests')
.map(manifest =>
manifest.replace('-manifest', '.dll').replace('.json', '.js')
)
.concat(glob.sync(outputGlob, { absolute: true }))
const content = files
.filter(file => !file.includes('node-entry'))
.filter(uniq)
.map(file => {
const name = basename(file, '.js').replace('.dll', '_dll_lib')
return `global["${name}"] = require("${file}")\n`
})
.join('')
const nodeEntry = resolve(output, './node-entry.js')
write(nodeEntry, content)
return nodeEntry
}
}
module.exports = DLL