-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
624 lines (538 loc) · 14.4 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
const ChainedMapExtendable = require('chain-able')
const {OFF, objToStr, isFunctionWithNoKeys} = require('./deps')
const pluginObjs = Object.assign(require('./plugins'), require('./middleware'))
const shh = {
shushed: false,
}
let shushed = {}
let required = {}
let scoped = {}
/**
*
* @TODO:
* - [x] change pkg config
* - [x] be able to pass in .config at runtime to install more dependencies
* - [x] check pkg json config at runtime
* - [x] call depflip on postinstall
* - [x] ensure all tests work
* - test by installing in another package, release as alpha,
* - OR read its own pkg config hahah
*
* - ensure all files are in pkg.files
* - update docs
*
* ------
*
* lower priority since it's a fair bit of work to mock this
* unless it can be done with Reflection/Proxy??
*
* - [x] add safety to each function so check if dep is installed,
* if not, log that it was installed
* add to pkgjson config if it has one
* continue
*/
// const {compose} = require('chain-able')
// const ChainedMapExtendable = compose({extend: true})
class LogChain extends ChainedMapExtendable {
/**
* @param {any} parent
*/
constructor(parent) {
super(parent)
delete this.inspect
this.version = '0.3.14'
// this extending is 0microseconds
this.extend(['title', 'color'])
this.extendWith(['space', 'tosource', 'time', 'silent'], true)
this.set('logger', console.log)
this.resets = []
this.presets = {}
this.log = this.echo
this.shh = shh
this.handleParent(parent)
// this.clr = require('chalk')
return this
}
/**
* @inheritdoc
* @see this.factory
*/
static factory(instance = null) {
return new LogChain(instance).factory(instance)
}
/**
* @since 0.3.0
* @TODO could be .scoped and then pass in debug here...
* @desc creates a new instance
* @param {FlipLog | null} [instance=null] specific instance, or new one
* @return {FlipLog} @chainable
*/
factory(instance = null) {
const plugins = Object.keys(pluginObjs)
const log = instance || new LogChain()
for (let u = 0; u < plugins.length; u++) {
const key = plugins[u]
log.use(pluginObjs[key])
}
if (instance !== null && typeof instance === 'string') {
scoped[instance] = log
}
return log.reset()
}
/**
* @since 0.3.0
* @desc adds to the scope, or gets from the scope :-}
* @param {string} name
* @return {FlipLog} @chainable
*/
scope(name) {
scoped[name] = scoped[name] || this
return scoped[name]
}
/**
* @param {string} name
* @return {FlipLog}
*/
used(name) {
return this.set('used', (this.get('used') || []).concat([name]))
}
/**
* @desc safely require a dependency if it exists
* if not, use the one in modules
* @param {string} name dependency package npm name
* @return {false | Object | any} dependency required
*/
requirePkg(name) {
// if we've already included it - may need to set as require.resolve
if (required[name]) {
// return require(name) // eslint-disable-line
return required[name] // eslint-disable-line
}
// wrap require
const dep = require('./modules')(name)
// warn and safely handle missing pkgs
if (!dep) {
const colored = this.colored(name)
// @NOTE: IGNORING THIS
this.text('did not have package ' + colored)
.data(`npm i ${colored} --save-dev \n yarn add ${colored} --dev`)
.echo()
return false
}
// store result for later
required[name] = dep
// return dep
return dep
}
/**
* @TODO: should wait until done using, store the deps, do all at once, uniq them
*
* @param {Object} obj
* @return {FlipLog}
*/
use(obj) {
if (isFunctionWithNoKeys(obj)) {
obj = obj.call(this, this)
}
if (this.deps === undefined) {
this.deps = []
}
// @TODO:
// this way we only use things once
// and can debug what plugins/middleware/ was used
if (this.has('used') === true) {
if (obj.name && this.get('used').includes(obj.name)) {
return this
}
}
else if (obj.name !== undefined) {
this.used(obj.name)
delete obj.name
}
/**
* so we can have a vanilla state with each plugin
*
* if it has a reset function,
* add to an array of reset functions
*/
if (obj.reset) {
if (this.resets.includes(obj.reset) === false) {
this.resets.push(obj.reset.bind(this))
}
delete obj.reset
}
/**
* call any initialization decorators
*/
if (obj.init) {
obj.init.bind(this)()
}
const keys = Object.keys(obj)
for (let k = 0; k < keys.length; k++) {
const key = keys[k]
if (key === 'deps' || typeof obj[key].bind !== 'function') {
// console.log({key}, 'not bindable')
continue
}
this[key] = obj[key].bind(this)
}
return this
}
/**
* @private
* @param {any} parent
* @return {FlipLog}
*/
handleParent(parent) {
this.from = super.from.bind(this)
if (!parent || !(parent instanceof ChainedMapExtendable)) return this
const entries = parent.entries()
if (!entries) return this
const {filter} = entries
const {presets} = parent
if (presets) this.presets = presets
if (filter) this.filter(filter)
return this
}
/**
* @TODO needs work to make it a function again
* @param {Boolean} [hardReset=false]
* @return {FlipLog}
*/
new(hardReset = false) {
function LogChainFn(args = null) {
if (args === null || args instanceof ChainedMapExtendable) {
const log = new LogChain(args)
return log.factory(log)
}
}
return this
// if using hard reset, do not inherit
// const logChain = new LogChain(hardReset ? null : this)
// return logChain
// const expose = require('expose-hidden')
// so we can extend without reassigning function name
// delete logChain.name
//
// const logfn = (arg, text, color) => {
// return logChain.data(arg).text(text).color(color).verbose(10).echo()
// }
//
// expose(logChain)
// Object.assign(logfn, logChain)
// return logfn
}
/**
* @perf takes ~500 microseconds
* reset the state so we do not instantiate every time
* @return {FlipLog}
*/
reset() {
// if (this.resetted === true) return this
// this.resetted = true
if (!this.savedLog) this.savedLog = []
// const timer = require('fliptime')
// timer.start('reset')
this.delete('silent')
.delete('title')
.delete('tosource')
.delete('text')
.delete('color')
.delete('space')
// .delete('data')
.set('data', OFF)
.verbose(10)
// timer.start('fns')
for (let r = 0; r < this.resets.length; r++) {
this.resets[r]()
}
// timer.stop('reset').stop('fns').log('reset').log('fns')
return this
}
// ----------------------------- adding data ------------------
/**
* @param {number | boolean | string | any} data
* @return {FlipLog}
*/
verbose(data) {
if (Number.isInteger(data)) {
return this.set('verbose', data)
}
if (typeof data === 'boolean') {
return this.set('verbose', data)
}
if (!data && data !== false) {
return this.set('verbose', true)
}
if (data === false) {
return this.set('verbose', false)
}
return this.set('data', data).set('verbose', true)
}
/**
* @param {any} arg
* @return {FlipLog}
*/
data(arg) {
if (arguments.length === 1) {
return this.set('data', arg)
}
return this.set('data', Array.from(arguments))
}
/**
* @param {string | serializable} text
* @return {FlipLog}
*/
text(text) {
if (this.has('title') === true) {
const title = this.get('title') ? `${this.get('title')}` : ''
return this.set('text', title + text)
}
return this.set('text', text)
}
/**
* @tutorial https://github.com/fliphub/fliplog#-emoji
* @see FlipLog.title
* @param {string} name
* @return {FlipLog}
*/
emoji(name) {
const emojiByName = require('./deps/emoji-by-name')
return this.title(`${emojiByName(name)} `)
}
/**
* @param {string} msg
* @param {string} [color=false]
* @return {FlipLog}
*/
addText(msg, color = false) {
if (color !== false) {
msg = this.getColored(color)(msg)
}
if (this.has('text') === true) {
this.set('text', `${this.get('text')} ${msg}`)
}
else {
this.text(msg)
}
return this
}
// ----------------------------- actual output ------------------
/**
* @since 0.3.0
* @desc to reduce complexity in echo function
* @return {FlipLog} @chainable
*/
echoShushed() {
// everything is silent everywhere,
// store log with formatter,
// reset
this.finalize()
const text = this.logText()
const datas = this.logData()
shushed[Date.now] = {text, datas}
this.shushed = shushed
this.reset()
return this
}
/**
* @see https://stackoverflow.com/questions/4976466/difference-between-process-stdout-write-and-console-log-in-node-js
* @since 0.3.1
* @desc set the logger to be process.stdout instead of console.log
* @param {boolean} [data=OFF] `false` will make it not output
* @return {FlipLog} @chainable
*/
stdout(data = OFF) {
this.set('logger', process.stdout.write.bind(process.stdout))
// this._stdout.write(require('util').format.apply(this, arguments) + '\n')
return this.echo(data)
}
/**
* @rename @since 0.4.0 echoConsole -> forceEcho
* @since 0.3.0
* @see this.echo, this.finalize, this.logText, this.logData, this.reset
* @desc the actual internal `console.log`ing
* @return {FlipLog} @chainable
*/
forceEcho() {
// so we can have them on 1 line
this.finalize()
const datas = this.logData()
const text = this.logText()
const logger = this.get('logger') || console.log
// check whether the values are default constant OFF
// so that when we log, they can be on the same console.log call
// in order to be on the same line
if (datas === OFF && text === OFF) {
return this
}
// text and no data
if (datas !== OFF && text === OFF) {
logger(datas)
}
else if (datas === OFF && text !== OFF) {
// no data, just text
logger(text + '')
}
else if (datas !== OFF && text !== OFF) {
if ((/\n|\r/gmi).test(text)) {
if (logger === console.log) {
logger(text + '')
logger(datas)
}
else {
logger(text + '', datas)
}
}
else {
logger(text + '', datas)
}
}
if (this.has('spaces') === true) {
const spaces = this.logSpaces()
if (spaces !== '') logger(spaces)
}
// timer.stop('echo-new').log('echo-new')
this.reset()
return this
}
/**
* @TODO: needs thought whether to return or to echo...
* since `+` is shorter to echo
*
* @alias log
* @alias echo
* @since 0.4.0
* @return {string} log output
*/
// toString() {
// return this.echo()
// }
/**
* @desc echos, then returns
* @example log.bold('eh').data({})+
* @alias echo
* @alias log
* @return {number} 0 if silent, 1 if success
*/
toNumber() {
this.echo()
return shh.shushed === true || this.has('silent') === true ? 0 : 1
}
/**
* @alias toString
* @alias log
* @since 0.0.1
* @param {boolean} [data=OFF] `false` will make it not output
* @return {FlipLog} @chainable
*/
echo(data = OFF) {
// const timer = require('fliptime')
// timer.start('echo-new')
if (this.stack !== null && this.stack !== undefined) {
this.stack()
}
// data !== 'force' &&
/* prettier-ignore */
if (this.has('tags') === true || this.has('filter') === true) {
this._filter()
}
// don't call any formatter middleware, reset state, perf
// || data === 0
if (data === false) {
this.reset()
return this
}
// data is default, use the stored data
// if (data === OFF) {
// data = this.get('data')
// }
if (shh.shushed === true) {
return this.echoShushed()
}
// don't call any formatter middleware, silent
if (this.has('silent') === true) {
this.reset()
return this
}
// if we are using sleep plugin
if (this.sleepIfNeeded !== undefined) {
this.sleepIfNeeded()
}
return this.forceEcho()
}
/**
* @private
* @since 0.3.0
* @desc call the formatters and transformers on the data if we are echoing
* so that they are only formatted when echoing
* @return {FlipLog} @chainable
*/
finalize() {
let arg = this.get('data')
if (this.has('formatter') === true) {
arg = this.get('formatter')(arg)
}
// @TODO: don't forget about ansi...
if (this.has('textFormatter') === true) {
let txt = this.get('text')
let text = txt
let title = ''
if (this.has('title')) {
title = this.get('title')
text = title + txt
this.delete('title')
}
text = this.get('textFormatter').call(this, text, this)
this.set('text', text)
this.delete('textFormatter')
}
return this.set('data', arg)
}
/**
* @private
* @since 0.1.0
* @TODO: should call middleware instead of hardcoded methods
* @desc does the actuall echoing of the text
* @return {string}
*/
logText() {
if (this.has('text') === false) {
return OFF
}
let text = this.get('text')
// if (text === null || text === undefined || text === null || text === OFF) {
// if (!text) return OFF
// convert obj to string
if (typeof text === 'object') {
text = objToStr(text)
}
if (this.has('color') === true) {
text = this.getColored(text)
}
if (this.has('text') === true) {
text = this.getTime(text)
}
if (this.has('spaces') === true) {
text += this.logSpaces()
}
return text
}
/**
* @private
* @TODO: should be array of middleware
* @desc returns the data to log
* @return {any}
*/
logData() {
let data = this.get('data')
if (data === OFF) return OFF
data = this.getToSource(data)
data = this.getVerbose(data)
return data
}
}
// ----------------------------- instantiate ------------------
// instantiating + adding + reset = ~10 microseconds
const log = new LogChain().factory()
module.exports = log