forked from command-line-bootcamp/cli-boot.camp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terminal-bundle.js
16855 lines (14373 loc) · 462 KB
/
terminal-bundle.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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Terminal = require('term.js')
var computed = require('computed-style')
var ndjson = require('ndjson')
var duplexify = require('duplexify')
var defaultcss = require('defaultcss')
var on = function(elem, evt, fn) { // TODO: find module
elem.addEventListener(evt, fn, false)
}
var off = function(elem, evt, fn) { // TODO: find module
elem.removeEventListener(evt, fn, false)
}
module.exports = function(opts) {
if (!opts) opts = {}
var result = duplexify()
result.appendTo = function(elem) {
if (typeof elem === 'string') elem = document.querySelector(elem)
if (opts.style !== false) defaultcss('docker-browser-console', require('./style'))
elem.className += ' docker-browser-console'
var dimensions = function() {
var el = document.createElement('div')
el.innerHTML = 'x'
el.style.float = 'left'
el.style.position = 'absolute'
el.style.left = '-1000px'
el.style.top = '-1000px'
elem.appendChild(el)
var dims = [el.offsetWidth, el.offsetHeight]
elem.removeChild(el)
return dims
}()
var get = function(name) {
return Math.floor(parseInt(computed(elem, name), 10) / dimensions[name === 'width' ? 0 : 1])
}
var wid = get('width')
var hei = get('height')
var onresize = function() {
var newWid = get('width')
var newHei = get('height')
if (newWid === wid && newHei === hei) return
wid = newWid
hei = newHei
term.resize(newWid, newHei)
output.write({
type: 'resize',
width: newWid,
height: newHei
})
}
if (opts.resize !== false) on(window, 'resize', onresize)
opts.convertEol = true
opts.cols = opts.cols || wid
opts.rows = opts.rows || hei
var renderer = opts.renderer || Terminal
var term = result.terminal = new renderer(opts)
var input = ndjson.parse()
var output = ndjson.stringify()
output.write({
type: 'run',
width: wid,
height: hei
})
input.on('data', function(data) {
if (data.type !== 'stderr' && data.type !== 'stdout') return
term.write(data.data)
result.emit(data.type, data.data)
})
term.open(elem)
result.setWritable(input)
result.setReadable(output)
term.on('data', function(data) {
output.write({type:'stdin', data:data})
result.emit('stdin', data)
})
term.on('title', function(title) {
result.emit('title', title)
})
result.on('close', function() {
off(window, 'resize', onresize)
term.destroy()
})
return result
}
return result
}
},{"./style":33,"computed-style":2,"defaultcss":3,"duplexify":4,"ndjson":20,"term.js":35}],2:[function(require,module,exports){
// This code has been refactored for 140 bytes
// You can see the original here: https://github.com/twolfson/computedStyle/blob/04cd1da2e30fa45844f95f5cb1ac898e9b9ef050/lib/computedStyle.js
var computedStyle = function (el, prop, getComputedStyle) {
getComputedStyle = window.getComputedStyle;
// In one fell swoop
return (
// If we have getComputedStyle
getComputedStyle ?
// Query it
// TODO: From CSS-Query notes, we might need (node, null) for FF
getComputedStyle(el) :
// Otherwise, we are in IE and use currentStyle
el.currentStyle
)[
// Switch to camelCase for CSSOM
// DEV: Grabbed from jQuery
// https://github.com/jquery/jquery/blob/1.9-stable/src/css.js#L191-L194
// https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L593-L597
prop.replace(/-(\w)/gi, function (word, letter) {
return letter.toUpperCase();
})
];
};
module.exports = computedStyle;
},{}],3:[function(require,module,exports){
/* jshint node: true */
'use strict';
/**
# defaultcss
A very simple module for creating a little bit of defaultcss. This is
really useful if you are creating a small JS widget that you want to be
completely stylable by the application implementer but would also like it
to look "kind of ok" if someone want to have a quick play.
## How it Works
The provided css text is injected into the HTML document within the document
`<head>` prior to any other `<link>` or `<style>` tags. This ensures that
any definitions that are made within your provided CSS have ample
opportunity to be overridden by user defined CSS.
## Example Usage
<<< examples/widget.js
## Reference
### defaultcss
```
defaultcss(label, csstext)
```
Create a new default `style` element and use the provided `label` to
generate an id for the element "%label%_defaultstyle". If an existing
element with that id is found, then do nothing.
If not, then create the new element and use the provided `csstext` as
`innerText` for th element.
**/
module.exports = function(label, text) {
var styleId = label + '_defaultstyle';
// look for a DOM element with the style id
var styleEl = document.getElementById(styleId);
// find the first <link> or <style> tag within the document head
var firstStyleDef = document.querySelector('link[rel="stylesheet"],style');
// if we can find a DOM element with that id, then do nothing as a default
// style has already been applied
if (styleEl) {
return styleEl;
}
// otherwise, create a style element
styleEl = document.createElement('style');
styleEl.innerText = text;
// insert the style element, in order or preference
// 1. before the first style related element in the page
if (firstStyleDef) {
firstStyleDef.parentNode.insertBefore(styleEl, firstStyleDef);
}
// 2. to the end of the HEAD
else if (document.head) {
document.head.appendChild(styleEl);
}
// 3. as the first element in the body
else if (document.body && document.body.childNodes.length > 0) {
document.body.insertBefore(styleEl, document.body.childNodes[0]);
}
// 4. in the body
else if (document.body) {
document.body.appendChild(styleEl);
}
return styleEl;
};
},{}],4:[function(require,module,exports){
(function (process,Buffer){
var stream = require('readable-stream')
var eos = require('end-of-stream')
var inherits = require('inherits')
var SIGNAL_FLUSH = new Buffer([0])
var onuncork = function(self, fn) {
if (self._corked) self.once('uncork', fn)
else fn()
}
var destroyer = function(self, end) {
return function(err) {
if (err) self.destroy(err.message === 'premature close' ? null : err)
else if (end && !self._ended) self.end()
}
}
var end = function(ws, fn) {
if (!ws) return fn()
if (ws._writableState && ws._writableState.finished) return fn()
if (ws._writableState) return ws.end(fn)
ws.end()
fn()
}
var toStreams2 = function(rs) {
return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
}
var Duplexify = function(writable, readable, opts) {
if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
stream.Duplex.call(this, opts)
this._writable = null
this._readable = null
this._readable2 = null
this._forwardDestroy = !opts || opts.destroy !== false
this._forwardEnd = !opts || opts.end !== false
this._corked = 1 // start corked
this._ondrain = null
this._drained = false
this._forwarding = false
this._unwrite = null
this._unread = null
this._ended = false
this.destroyed = false
if (writable) this.setWritable(writable)
if (readable) this.setReadable(readable)
}
inherits(Duplexify, stream.Duplex)
Duplexify.obj = function(writable, readable, opts) {
if (!opts) opts = {}
opts.objectMode = true
opts.highWaterMark = 16
return new Duplexify(writable, readable, opts)
}
Duplexify.prototype.cork = function() {
if (++this._corked === 1) this.emit('cork')
}
Duplexify.prototype.uncork = function() {
if (this._corked && --this._corked === 0) this.emit('uncork')
}
Duplexify.prototype.setWritable = function(writable) {
if (this._unwrite) this._unwrite()
if (this.destroyed) {
if (writable && writable.destroy) writable.destroy()
return
}
if (writable === null || writable === false) {
this.end()
return
}
var self = this
var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
var ondrain = function() {
var ondrain = self._ondrain
self._ondrain = null
if (ondrain) ondrain()
}
var clear = function() {
self._writable.removeListener('drain', ondrain)
unend()
}
if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
this._writable = writable
this._writable.on('drain', ondrain)
this._unwrite = clear
this.uncork() // always uncork setWritable
}
Duplexify.prototype.setReadable = function(readable) {
if (this._unread) this._unread()
if (this.destroyed) {
if (readable && readable.destroy) readable.destroy()
return
}
if (readable === null || readable === false) {
this.push(null)
this.resume()
return
}
var self = this
var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
var onreadable = function() {
self._forward()
}
var onend = function() {
self.push(null)
}
var clear = function() {
self._readable2.removeListener('readable', onreadable)
self._readable2.removeListener('end', onend)
unend()
}
this._drained = true
this._readable = readable
this._readable2 = readable._readableState ? readable : toStreams2(readable)
this._readable2.on('readable', onreadable)
this._readable2.on('end', onend)
this._unread = clear
this._forward()
}
Duplexify.prototype._read = function() {
this._drained = true
this._forward()
}
Duplexify.prototype._forward = function() {
if (this._forwarding || !this._readable2 || !this._drained) return
this._forwarding = true
var data
var state = this._readable2._readableState
while ((data = this._readable2.read(state.buffer.length ? state.buffer[0].length : state.length)) !== null) {
this._drained = this.push(data)
}
this._forwarding = false
}
Duplexify.prototype.destroy = function(err) {
if (this.destroyed) return
this.destroyed = true
var self = this
process.nextTick(function() {
self._destroy(err)
})
}
Duplexify.prototype._destroy = function(err) {
if (err) {
var ondrain = this._ondrain
this._ondrain = null
if (ondrain) ondrain(err)
else this.emit('error', err)
}
if (this._forwardDestroy) {
if (this._readable && this._readable.destroy) this._readable.destroy()
if (this._writable && this._writable.destroy) this._writable.destroy()
}
this.emit('close')
}
Duplexify.prototype._write = function(data, enc, cb) {
if (this.destroyed) return cb()
if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
if (data === SIGNAL_FLUSH) return this._finish(cb)
if (!this._writable) return cb()
if (this._writable.write(data) === false) this._ondrain = cb
else cb()
}
Duplexify.prototype._finish = function(cb) {
var self = this
this.emit('preend')
onuncork(this, function() {
end(self._forwardEnd && self._writable, function() {
// haxx to not emit prefinish twice
if (self._writableState.prefinished === false) self._writableState.prefinished = true
self.emit('prefinish')
onuncork(self, cb)
})
})
}
Duplexify.prototype.end = function(data, enc, cb) {
if (typeof data === 'function') return this.end(null, null, data)
if (typeof enc === 'function') return this.end(data, null, enc)
this._ended = true
if (data) this.write(data)
if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
return stream.Writable.prototype.end.call(this, cb)
}
module.exports = Duplexify
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":78,"buffer":69,"end-of-stream":5,"inherits":8,"readable-stream":19}],5:[function(require,module,exports){
var once = require('once');
var noop = function() {};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === 'function';
};
var eos = function(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
};
var onfinish = function() {
writable = false;
if (!readable) callback();
};
var onend = function() {
readable = false;
if (!writable) callback();
};
var onclose = function() {
if (readable && !(rs && rs.ended)) return callback(new Error('premature close'));
if (writable && !(ws && ws.ended)) return callback(new Error('premature close'));
};
var onrequest = function() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();
else stream.on('request', onrequest);
} else if (writable && !ws) { // legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', callback);
stream.on('close', onclose);
return function() {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('end', onend);
stream.removeListener('error', callback);
stream.removeListener('close', onclose);
};
};
module.exports = eos;
},{"once":7}],6:[function(require,module,exports){
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}
},{}],7:[function(require,module,exports){
var wrappy = require('wrappy')
module.exports = wrappy(once)
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
})
function once (fn) {
var f = function () {
if (f.called) return f.value
f.called = true
return f.value = fn.apply(this, arguments)
}
f.called = false
return f
}
},{"wrappy":6}],8:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],9:[function(require,module,exports){
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
},{"./_stream_readable":11,"./_stream_writable":13,"core-util-is":14,"inherits":8,"process-nextick-args":16}],10:[function(require,module,exports){
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":12,"core-util-is":14,"inherits":8}],11:[function(require,module,exports){
(function (process){
'use strict';
module.exports = Readable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events');
/*<replacement>*/
var EElistenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function (){try{
Stream = require('st' + 'ream');
}catch(_){}finally{
if (!Stream)
Stream = require('events').EventEmitter;
}}())
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var StringDecoder;
util.inherits(Readable, Stream);
var Duplex;
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
var Duplex;
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options && typeof options.read === 'function')
this._read = options.read;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
Readable.prototype.isPaused = function() {
return this._readableState.flowing === false;
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
if (!addToFront)
state.reading = false;
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront)
state.buffer.unshift(chunk);
else
state.buffer.push(chunk);
if (state.needReadable)
emitReadable(stream);
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (n === null || isNaN(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;