UNPKG

173 kBJavaScriptView Raw
1(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){
2/*
3 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
4 *
5 * Use of this source code is governed by a BSD-style license
6 * that can be found in the LICENSE file in the root of the source
7 * tree.
8 */
9
10/* More information about these options at jshint.com/docs/options */
11/* jshint browser: true, camelcase: true, curly: true, devel: true,
12 eqeqeq: true, forin: false, globalstrict: true, node: true,
13 quotmark: single, undef: true, unused: strict */
14/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise,
15mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */
16/* exported trace,requestUserMedia */
17'use strict';
18
19var RTCPeerConnection = null;
20var getUserMedia = null;
21var attachMediaStream = null;
22var reattachMediaStream = null;
23var webrtcDetectedBrowser = null;
24var webrtcDetectedVersion = null;
25
26function trace(text) {
27 // This function is used for logging.
28 if (text[text.length - 1] === '\n') {
29 text = text.substring(0, text.length - 1);
30 }
31 if (window.performance) {
32 var now = (window.performance.now() / 1000).toFixed(3);
33 console.log(now + ': ' + text);
34 } else {
35 console.log(text);
36 }
37}
38
39if (navigator.mozGetUserMedia) {
40 console.log('This appears to be Firefox');
41
42 webrtcDetectedBrowser = 'firefox';
43
44 webrtcDetectedVersion =
45 parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
46
47 // The RTCPeerConnection object.
48 RTCPeerConnection = function(pcConfig, pcConstraints) {
49 // .urls is not supported in FF yet.
50 if (pcConfig && pcConfig.iceServers) {
51 for (var i = 0; i < pcConfig.iceServers.length; i++) {
52 if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
53 pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
54 delete pcConfig.iceServers[i].urls;
55 }
56 }
57 }
58 return new mozRTCPeerConnection(pcConfig, pcConstraints);
59 };
60
61 // The RTCSessionDescription object.
62 window.RTCSessionDescription = mozRTCSessionDescription;
63
64 // The RTCIceCandidate object.
65 window.RTCIceCandidate = mozRTCIceCandidate;
66
67 // getUserMedia shim (only difference is the prefix).
68 // Code from Adam Barth.
69 getUserMedia = navigator.mozGetUserMedia.bind(navigator);
70 navigator.getUserMedia = getUserMedia;
71
72 // Shim for MediaStreamTrack.getSources.
73 MediaStreamTrack.getSources = function(successCb) {
74 setTimeout(function() {
75 var infos = [
76 {kind: 'audio', id: 'default', label:'', facing:''},
77 {kind: 'video', id: 'default', label:'', facing:''}
78 ];
79 successCb(infos);
80 }, 0);
81 };
82
83 // Creates ICE server from the URL for FF.
84 window.createIceServer = function(url, username, password) {
85 var iceServer = null;
86 var urlParts = url.split(':');
87 if (urlParts[0].indexOf('stun') === 0) {
88 // Create ICE server with STUN URL.
89 iceServer = {
90 'url': url
91 };
92 } else if (urlParts[0].indexOf('turn') === 0) {
93 if (webrtcDetectedVersion < 27) {
94 // Create iceServer with turn url.
95 // Ignore the transport parameter from TURN url for FF version <=27.
96 var turnUrlParts = url.split('?');
97 // Return null for createIceServer if transport=tcp.
98 if (turnUrlParts.length === 1 ||
99 turnUrlParts[1].indexOf('transport=udp') === 0) {
100 iceServer = {
101 'url': turnUrlParts[0],
102 'credential': password,
103 'username': username
104 };
105 }
106 } else {
107 // FF 27 and above supports transport parameters in TURN url,
108 // So passing in the full url to create iceServer.
109 iceServer = {
110 'url': url,
111 'credential': password,
112 'username': username
113 };
114 }
115 }
116 return iceServer;
117 };
118
119 window.createIceServers = function(urls, username, password) {
120 var iceServers = [];
121 // Use .url for FireFox.
122 for (var i = 0; i < urls.length; i++) {
123 var iceServer =
124 window.createIceServer(urls[i], username, password);
125 if (iceServer !== null) {
126 iceServers.push(iceServer);
127 }
128 }
129 return iceServers;
130 };
131
132 // Attach a media stream to an element.
133 attachMediaStream = function(element, stream) {
134 console.log('Attaching media stream');
135 element.mozSrcObject = stream;
136 };
137
138 reattachMediaStream = function(to, from) {
139 console.log('Reattaching media stream');
140 to.mozSrcObject = from.mozSrcObject;
141 };
142
143} else if (navigator.webkitGetUserMedia) {
144 console.log('This appears to be Chrome');
145
146 webrtcDetectedBrowser = 'chrome';
147 // Temporary fix until crbug/374263 is fixed.
148 // Setting Chrome version to 999, if version is unavailable.
149 var result = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
150 if (result !== null) {
151 webrtcDetectedVersion = parseInt(result[2], 10);
152 } else {
153 webrtcDetectedVersion = 999;
154 }
155
156 // Creates iceServer from the url for Chrome M33 and earlier.
157 window.createIceServer = function(url, username, password) {
158 var iceServer = null;
159 var urlParts = url.split(':');
160 if (urlParts[0].indexOf('stun') === 0) {
161 // Create iceServer with stun url.
162 iceServer = {
163 'url': url
164 };
165 } else if (urlParts[0].indexOf('turn') === 0) {
166 // Chrome M28 & above uses below TURN format.
167 iceServer = {
168 'url': url,
169 'credential': password,
170 'username': username
171 };
172 }
173 return iceServer;
174 };
175
176 // Creates an ICEServer object from multiple URLs.
177 window.createIceServers = function(urls, username, password) {
178 return {
179 'urls': urls,
180 'credential': password,
181 'username': username
182 };
183 };
184
185 // The RTCPeerConnection object.
186 RTCPeerConnection = function(pcConfig, pcConstraints) {
187 return new webkitRTCPeerConnection(pcConfig, pcConstraints);
188 };
189
190 // Get UserMedia (only difference is the prefix).
191 // Code from Adam Barth.
192 getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
193 navigator.getUserMedia = getUserMedia;
194
195 // Attach a media stream to an element.
196 attachMediaStream = function(element, stream) {
197 if (typeof element.srcObject !== 'undefined') {
198 element.srcObject = stream;
199 } else if (typeof element.mozSrcObject !== 'undefined') {
200 element.mozSrcObject = stream;
201 } else if (typeof element.src !== 'undefined') {
202 element.src = URL.createObjectURL(stream);
203 } else {
204 console.log('Error attaching stream to element.');
205 }
206 };
207
208 reattachMediaStream = function(to, from) {
209 to.src = from.src;
210 };
211} else {
212 console.log('Browser does not appear to be WebRTC-capable');
213}
214
215// Returns the result of getUserMedia as a Promise.
216function requestUserMedia(constraints) {
217 return new Promise(function(resolve, reject) {
218 try {
219 getUserMedia(constraints, resolve, reject);
220 } catch (e) {
221 reject(e);
222 }
223 });
224}
225
226if (typeof module !== 'undefined') {
227 module.exports = {
228 RTCPeerConnection: RTCPeerConnection,
229 getUserMedia: getUserMedia,
230 attachMediaStream: attachMediaStream,
231 reattachMediaStream: reattachMediaStream,
232 webrtcDetectedBrowser: webrtcDetectedBrowser,
233 webrtcDetectedVersion: webrtcDetectedVersion
234 //requestUserMedia: not exposed on purpose.
235 //trace: not exposed on purpose.
236 };
237}
238
239},{}],2:[function(require,module,exports){
240(function (process){
241var defined = require('defined');
242var createDefaultStream = require('./lib/default_stream');
243var Test = require('./lib/test');
244var createResult = require('./lib/results');
245var through = require('through');
246
247var canEmitExit = typeof process !== 'undefined' && process
248 && typeof process.on === 'function' && process.browser !== true
249;
250var canExit = typeof process !== 'undefined' && process
251 && typeof process.exit === 'function'
252;
253
254var nextTick = typeof setImmediate !== 'undefined'
255 ? setImmediate
256 : process.nextTick
257;
258
259exports = module.exports = (function () {
260 var harness;
261 var lazyLoad = function () {
262 return getHarness().apply(this, arguments);
263 };
264
265 lazyLoad.only = function () {
266 return getHarness().only.apply(this, arguments);
267 };
268
269 lazyLoad.createStream = function (opts) {
270 if (!opts) opts = {};
271 if (!harness) {
272 var output = through();
273 getHarness({ stream: output, objectMode: opts.objectMode });
274 return output;
275 }
276 return harness.createStream(opts);
277 };
278
279 return lazyLoad
280
281 function getHarness (opts) {
282 if (!opts) opts = {};
283 opts.autoclose = !canEmitExit;
284 if (!harness) harness = createExitHarness(opts);
285 return harness;
286 }
287})();
288
289function createExitHarness (conf) {
290 if (!conf) conf = {};
291 var harness = createHarness({
292 autoclose: defined(conf.autoclose, false)
293 });
294
295 var stream = harness.createStream({ objectMode: conf.objectMode });
296 var es = stream.pipe(conf.stream || createDefaultStream());
297 if (canEmitExit) {
298 es.on('error', function (err) { harness._exitCode = 1 });
299 }
300
301 var ended = false;
302 stream.on('end', function () { ended = true });
303
304 if (conf.exit === false) return harness;
305 if (!canEmitExit || !canExit) return harness;
306
307 var inErrorState = false;
308
309 process.on('exit', function (code) {
310 // let the process exit cleanly.
311 if (code !== 0) {
312 return
313 }
314
315 if (!ended) {
316 var only = harness._results._only;
317 for (var i = 0; i < harness._tests.length; i++) {
318 var t = harness._tests[i];
319 if (only && t.name !== only) continue;
320 t._exit();
321 }
322 }
323 harness.close();
324 process.exit(code || harness._exitCode);
325 });
326
327 return harness;
328}
329
330exports.createHarness = createHarness;
331exports.Test = Test;
332exports.test = exports; // tap compat
333exports.test.skip = Test.skip;
334
335var exitInterval;
336
337function createHarness (conf_) {
338 if (!conf_) conf_ = {};
339 var results = createResult();
340 if (conf_.autoclose !== false) {
341 results.once('done', function () { results.close() });
342 }
343
344 var test = function (name, conf, cb) {
345 var t = new Test(name, conf, cb);
346 test._tests.push(t);
347
348 (function inspectCode (st) {
349 st.on('test', function sub (st_) {
350 inspectCode(st_);
351 });
352 st.on('result', function (r) {
353 if (!r.ok) test._exitCode = 1
354 });
355 })(t);
356
357 results.push(t);
358 return t;
359 };
360 test._results = results;
361
362 test._tests = [];
363
364 test.createStream = function (opts) {
365 return results.createStream(opts);
366 };
367
368 var only = false;
369 test.only = function (name) {
370 if (only) throw new Error('there can only be one only test');
371 results.only(name);
372 only = true;
373 return test.apply(null, arguments);
374 };
375 test._exitCode = 0;
376
377 test.close = function () { results.close() };
378
379 return test;
380}
381
382}).call(this,require('_process'))
383},{"./lib/default_stream":3,"./lib/results":4,"./lib/test":5,"_process":24,"defined":9,"through":13}],3:[function(require,module,exports){
384(function (process){
385var through = require('through');
386var fs = require('fs');
387
388module.exports = function () {
389 var line = '';
390 var stream = through(write, flush);
391 return stream;
392
393 function write (buf) {
394 for (var i = 0; i < buf.length; i++) {
395 var c = typeof buf === 'string'
396 ? buf.charAt(i)
397 : String.fromCharCode(buf[i])
398 ;
399 if (c === '\n') flush();
400 else line += c;
401 }
402 }
403
404 function flush () {
405 if (fs.writeSync && /^win/.test(process.platform)) {
406 try { fs.writeSync(1, line + '\n'); }
407 catch (e) { stream.emit('error', e) }
408 }
409 else {
410 try { console.log(line) }
411 catch (e) { stream.emit('error', e) }
412 }
413 line = '';
414 }
415};
416
417}).call(this,require('_process'))
418},{"_process":24,"fs":14,"through":13}],4:[function(require,module,exports){
419(function (process){
420var EventEmitter = require('events').EventEmitter;
421var inherits = require('inherits');
422var through = require('through');
423var resumer = require('resumer');
424var inspect = require('object-inspect');
425var nextTick = typeof setImmediate !== 'undefined'
426 ? setImmediate
427 : process.nextTick
428;
429
430module.exports = Results;
431inherits(Results, EventEmitter);
432
433function Results () {
434 if (!(this instanceof Results)) return new Results;
435 this.count = 0;
436 this.fail = 0;
437 this.pass = 0;
438 this._stream = through();
439 this.tests = [];
440}
441
442Results.prototype.createStream = function (opts) {
443 if (!opts) opts = {};
444 var self = this;
445 var output, testId = 0;
446 if (opts.objectMode) {
447 output = through();
448 self.on('_push', function ontest (t, extra) {
449 if (!extra) extra = {};
450 var id = testId++;
451 t.once('prerun', function () {
452 var row = {
453 type: 'test',
454 name: t.name,
455 id: id
456 };
457 if (has(extra, 'parent')) {
458 row.parent = extra.parent;
459 }
460 output.queue(row);
461 });
462 t.on('test', function (st) {
463 ontest(st, { parent: id });
464 });
465 t.on('result', function (res) {
466 res.test = id;
467 res.type = 'assert';
468 output.queue(res);
469 });
470 t.on('end', function () {
471 output.queue({ type: 'end', test: id });
472 });
473 });
474 self.on('done', function () { output.queue(null) });
475 }
476 else {
477 output = resumer();
478 output.queue('TAP version 13\n');
479 self._stream.pipe(output);
480 }
481
482 nextTick(function next() {
483 var t;
484 while (t = getNextTest(self)) {
485 t.run();
486 if (!t.ended) return t.once('end', function(){ nextTick(next); });
487 }
488 self.emit('done');
489 });
490
491 return output;
492};
493
494Results.prototype.push = function (t) {
495 var self = this;
496 self.tests.push(t);
497 self._watch(t);
498 self.emit('_push', t);
499};
500
501Results.prototype.only = function (name) {
502 if (this._only) {
503 self.count ++;
504 self.fail ++;
505 write('not ok ' + self.count + ' already called .only()\n');
506 }
507 this._only = name;
508};
509
510Results.prototype._watch = function (t) {
511 var self = this;
512 var write = function (s) { self._stream.queue(s) };
513 t.once('prerun', function () {
514 write('# ' + t.name + '\n');
515 });
516
517 t.on('result', function (res) {
518 if (typeof res === 'string') {
519 write('# ' + res + '\n');
520 return;
521 }
522 write(encodeResult(res, self.count + 1));
523 self.count ++;
524
525 if (res.ok) self.pass ++
526 else self.fail ++
527 });
528
529 t.on('test', function (st) { self._watch(st) });
530};
531
532Results.prototype.close = function () {
533 var self = this;
534 if (self.closed) self._stream.emit('error', new Error('ALREADY CLOSED'));
535 self.closed = true;
536 var write = function (s) { self._stream.queue(s) };
537
538 write('\n1..' + self.count + '\n');
539 write('# tests ' + self.count + '\n');
540 write('# pass ' + self.pass + '\n');
541 if (self.fail) write('# fail ' + self.fail + '\n')
542 else write('\n# ok\n')
543
544 self._stream.queue(null);
545};
546
547function encodeResult (res, count) {
548 var output = '';
549 output += (res.ok ? 'ok ' : 'not ok ') + count;
550 output += res.name ? ' ' + res.name.toString().replace(/\s+/g, ' ') : '';
551
552 if (res.skip) output += ' # SKIP';
553 else if (res.todo) output += ' # TODO';
554
555 output += '\n';
556 if (res.ok) return output;
557
558 var outer = ' ';
559 var inner = outer + ' ';
560 output += outer + '---\n';
561 output += inner + 'operator: ' + res.operator + '\n';
562
563 if (has(res, 'expected') || has(res, 'actual')) {
564 var ex = inspect(res.expected);
565 var ac = inspect(res.actual);
566
567 if (Math.max(ex.length, ac.length) > 65) {
568 output += inner + 'expected:\n' + inner + ' ' + ex + '\n';
569 output += inner + 'actual:\n' + inner + ' ' + ac + '\n';
570 }
571 else {
572 output += inner + 'expected: ' + ex + '\n';
573 output += inner + 'actual: ' + ac + '\n';
574 }
575 }
576 if (res.at) {
577 output += inner + 'at: ' + res.at + '\n';
578 }
579 if (res.operator === 'error' && res.actual && res.actual.stack) {
580 var lines = String(res.actual.stack).split('\n');
581 output += inner + 'stack:\n';
582 output += inner + ' ' + lines[0] + '\n';
583 for (var i = 1; i < lines.length; i++) {
584 output += inner + lines[i] + '\n';
585 }
586 }
587
588 output += outer + '...\n';
589 return output;
590}
591
592function getNextTest (results) {
593 if (!results._only) {
594 return results.tests.shift();
595 }
596
597 do {
598 var t = results.tests.shift();
599 if (!t) continue;
600 if (results._only === t.name) {
601 return t;
602 }
603 } while (results.tests.length !== 0)
604}
605
606function has (obj, prop) {
607 return Object.prototype.hasOwnProperty.call(obj, prop);
608}
609
610}).call(this,require('_process'))
611},{"_process":24,"events":20,"inherits":10,"object-inspect":11,"resumer":12,"through":13}],5:[function(require,module,exports){
612(function (process,__dirname){
613var deepEqual = require('deep-equal');
614var defined = require('defined');
615var path = require('path');
616var inherits = require('inherits');
617var EventEmitter = require('events').EventEmitter;
618
619module.exports = Test;
620
621var nextTick = typeof setImmediate !== 'undefined'
622 ? setImmediate
623 : process.nextTick
624;
625
626inherits(Test, EventEmitter);
627
628var getTestArgs = function (name_, opts_, cb_) {
629 var name = '(anonymous)';
630 var opts = {};
631 var cb;
632
633 for (var i = 0; i < arguments.length; i++) {
634 var arg = arguments[i];
635 var t = typeof arg;
636 if (t === 'string') {
637 name = arg;
638 }
639 else if (t === 'object') {
640 opts = arg || opts;
641 }
642 else if (t === 'function') {
643 cb = arg;
644 }
645 }
646 return { name: name, opts: opts, cb: cb };
647};
648
649function Test (name_, opts_, cb_) {
650 if (! (this instanceof Test)) {
651 return new Test(name_, opts_, cb_);
652 }
653
654 var args = getTestArgs(name_, opts_, cb_);
655
656 this.readable = true;
657 this.name = args.name || '(anonymous)';
658 this.assertCount = 0;
659 this.pendingCount = 0;
660 this._skip = args.opts.skip || false;
661 this._plan = undefined;
662 this._cb = args.cb;
663 this._progeny = [];
664 this._ok = true;
665
666 if (args.opts.timeout !== undefined) {
667 this.timeoutAfter(args.opts.timeout);
668 }
669
670 for (var prop in this) {
671 this[prop] = (function bind(self, val) {
672 if (typeof val === 'function') {
673 return function bound() {
674 return val.apply(self, arguments);
675 };
676 }
677 else return val;
678 })(this, this[prop]);
679 }
680}
681
682Test.prototype.run = function () {
683 if (!this._cb || this._skip) {
684 return this._end();
685 }
686 this.emit('prerun');
687 this._cb(this);
688 this.emit('run');
689};
690
691Test.prototype.test = function (name, opts, cb) {
692 var self = this;
693 var t = new Test(name, opts, cb);
694 this._progeny.push(t);
695 this.pendingCount++;
696 this.emit('test', t);
697 t.on('prerun', function () {
698 self.assertCount++;
699 })
700
701 if (!self._pendingAsserts()) {
702 nextTick(function () {
703 self._end();
704 });
705 }
706
707 nextTick(function() {
708 if (!self._plan && self.pendingCount == self._progeny.length) {
709 self._end();
710 }
711 });
712};
713
714Test.prototype.comment = function (msg) {
715 this.emit('result', msg.trim().replace(/^#\s*/, ''));
716};
717
718Test.prototype.plan = function (n) {
719 this._plan = n;
720 this.emit('plan', n);
721};
722
723Test.prototype.timeoutAfter = function(ms) {
724 if (!ms) throw new Error('timeoutAfter requires a timespan');
725 var self = this;
726 var timeout = setTimeout(function() {
727 self.fail('test timed out after ' + ms + 'ms');
728 self.end();
729 }, ms);
730 this.once('end', function() {
731 clearTimeout(timeout);
732 });
733}
734
735Test.prototype.end = function (err) {
736 var self = this;
737 if (arguments.length >= 1 && !!err) {
738 this.ifError(err);
739 }
740
741 if (this.calledEnd) {
742 this.fail('.end() called twice');
743 }
744 this.calledEnd = true;
745 this._end();
746};
747
748Test.prototype._end = function (err) {
749 var self = this;
750 if (this._progeny.length) {
751 var t = this._progeny.shift();
752 t.on('end', function () { self._end() });
753 t.run();
754 return;
755 }
756
757 if (!this.ended) this.emit('end');
758 var pendingAsserts = this._pendingAsserts();
759 if (!this._planError && this._plan !== undefined && pendingAsserts) {
760 this._planError = true;
761 this.fail('plan != count', {
762 expected : this._plan,
763 actual : this.assertCount
764 });
765 }
766 this.ended = true;
767};
768
769Test.prototype._exit = function () {
770 if (this._plan !== undefined &&
771 !this._planError && this.assertCount !== this._plan) {
772 this._planError = true;
773 this.fail('plan != count', {
774 expected : this._plan,
775 actual : this.assertCount,
776 exiting : true
777 });
778 }
779 else if (!this.ended) {
780 this.fail('test exited without ending', {
781 exiting: true
782 });
783 }
784};
785
786Test.prototype._pendingAsserts = function () {
787 if (this._plan === undefined) {
788 return 1;
789 }
790 else {
791 return this._plan - (this._progeny.length + this.assertCount);
792 }
793};
794
795Test.prototype._assert = function assert (ok, opts) {
796 var self = this;
797 var extra = opts.extra || {};
798
799 var res = {
800 id : self.assertCount ++,
801 ok : Boolean(ok),
802 skip : defined(extra.skip, opts.skip),
803 name : defined(extra.message, opts.message, '(unnamed assert)'),
804 operator : defined(extra.operator, opts.operator)
805 };
806 if (has(opts, 'actual') || has(extra, 'actual')) {
807 res.actual = defined(extra.actual, opts.actual);
808 }
809 if (has(opts, 'expected') || has(extra, 'expected')) {
810 res.expected = defined(extra.expected, opts.expected);
811 }
812 this._ok = Boolean(this._ok && ok);
813
814 if (!ok) {
815 res.error = defined(extra.error, opts.error, new Error(res.name));
816 }
817
818 if (!ok) {
819 var e = new Error('exception');
820 var err = (e.stack || '').split('\n');
821 var dir = path.dirname(__dirname) + '/';
822
823 for (var i = 0; i < err.length; i++) {
824 var m = /^[^\s]*\s*\bat\s+(.+)/.exec(err[i]);
825 if (!m) {
826 continue;
827 }
828
829 var s = m[1].split(/\s+/);
830 var filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[1]);
831 if (!filem) {
832 filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[2]);
833
834 if (!filem) {
835 filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[3]);
836
837 if (!filem) {
838 continue;
839 }
840 }
841 }
842
843 if (filem[1].slice(0, dir.length) === dir) {
844 continue;
845 }
846
847 res.functionName = s[0];
848 res.file = filem[1];
849 res.line = Number(filem[2]);
850 if (filem[3]) res.column = filem[3];
851
852 res.at = m[1];
853 break;
854 }
855 }
856
857 self.emit('result', res);
858
859 var pendingAsserts = self._pendingAsserts();
860 if (!pendingAsserts) {
861 if (extra.exiting) {
862 self._end();
863 } else {
864 nextTick(function () {
865 self._end();
866 });
867 }
868 }
869
870 if (!self._planError && pendingAsserts < 0) {
871 self._planError = true;
872 self.fail('plan != count', {
873 expected : self._plan,
874 actual : self._plan - pendingAsserts
875 });
876 }
877};
878
879Test.prototype.fail = function (msg, extra) {
880 this._assert(false, {
881 message : msg,
882 operator : 'fail',
883 extra : extra
884 });
885};
886
887Test.prototype.pass = function (msg, extra) {
888 this._assert(true, {
889 message : msg,
890 operator : 'pass',
891 extra : extra
892 });
893};
894
895Test.prototype.skip = function (msg, extra) {
896 this._assert(true, {
897 message : msg,
898 operator : 'skip',
899 skip : true,
900 extra : extra
901 });
902};
903
904Test.prototype.ok
905= Test.prototype['true']
906= Test.prototype.assert
907= function (value, msg, extra) {
908 this._assert(value, {
909 message : msg,
910 operator : 'ok',
911 expected : true,
912 actual : value,
913 extra : extra
914 });
915};
916
917Test.prototype.notOk
918= Test.prototype['false']
919= Test.prototype.notok
920= function (value, msg, extra) {
921 this._assert(!value, {
922 message : msg,
923 operator : 'notOk',
924 expected : false,
925 actual : value,
926 extra : extra
927 });
928};
929
930Test.prototype.error
931= Test.prototype.ifError
932= Test.prototype.ifErr
933= Test.prototype.iferror
934= function (err, msg, extra) {
935 this._assert(!err, {
936 message : defined(msg, String(err)),
937 operator : 'error',
938 actual : err,
939 extra : extra
940 });
941};
942
943Test.prototype.equal
944= Test.prototype.equals
945= Test.prototype.isEqual
946= Test.prototype.is
947= Test.prototype.strictEqual
948= Test.prototype.strictEquals
949= function (a, b, msg, extra) {
950 this._assert(a === b, {
951 message : defined(msg, 'should be equal'),
952 operator : 'equal',
953 actual : a,
954 expected : b,
955 extra : extra
956 });
957};
958
959Test.prototype.notEqual
960= Test.prototype.notEquals
961= Test.prototype.notStrictEqual
962= Test.prototype.notStrictEquals
963= Test.prototype.isNotEqual
964= Test.prototype.isNot
965= Test.prototype.not
966= Test.prototype.doesNotEqual
967= Test.prototype.isInequal
968= function (a, b, msg, extra) {
969 this._assert(a !== b, {
970 message : defined(msg, 'should not be equal'),
971 operator : 'notEqual',
972 actual : a,
973 notExpected : b,
974 extra : extra
975 });
976};
977
978Test.prototype.deepEqual
979= Test.prototype.deepEquals
980= Test.prototype.isEquivalent
981= Test.prototype.same
982= function (a, b, msg, extra) {
983 this._assert(deepEqual(a, b, { strict: true }), {
984 message : defined(msg, 'should be equivalent'),
985 operator : 'deepEqual',
986 actual : a,
987 expected : b,
988 extra : extra
989 });
990};
991
992Test.prototype.deepLooseEqual
993= Test.prototype.looseEqual
994= Test.prototype.looseEquals
995= function (a, b, msg, extra) {
996 this._assert(deepEqual(a, b), {
997 message : defined(msg, 'should be equivalent'),
998 operator : 'deepLooseEqual',
999 actual : a,
1000 expected : b,
1001 extra : extra
1002 });
1003};
1004
1005Test.prototype.notDeepEqual
1006= Test.prototype.notEquivalent
1007= Test.prototype.notDeeply
1008= Test.prototype.notSame
1009= Test.prototype.isNotDeepEqual
1010= Test.prototype.isNotDeeply
1011= Test.prototype.isNotEquivalent
1012= Test.prototype.isInequivalent
1013= function (a, b, msg, extra) {
1014 this._assert(!deepEqual(a, b, { strict: true }), {
1015 message : defined(msg, 'should not be equivalent'),
1016 operator : 'notDeepEqual',
1017 actual : a,
1018 notExpected : b,
1019 extra : extra
1020 });
1021};
1022
1023Test.prototype.notDeepLooseEqual
1024= Test.prototype.notLooseEqual
1025= Test.prototype.notLooseEquals
1026= function (a, b, msg, extra) {
1027 this._assert(!deepEqual(a, b), {
1028 message : defined(msg, 'should be equivalent'),
1029 operator : 'notDeepLooseEqual',
1030 actual : a,
1031 expected : b,
1032 extra : extra
1033 });
1034};
1035
1036Test.prototype['throws'] = function (fn, expected, msg, extra) {
1037 if (typeof expected === 'string') {
1038 msg = expected;
1039 expected = undefined;
1040 }
1041
1042 var caught = undefined;
1043
1044 try {
1045 fn();
1046 } catch (err) {
1047 caught = { error : err };
1048 var message = err.message;
1049 delete err.message;
1050 err.message = message;
1051 }
1052
1053 var passed = caught;
1054
1055 if (expected instanceof RegExp) {
1056 passed = expected.test(caught && caught.error);
1057 expected = String(expected);
1058 }
1059
1060 if (typeof expected === 'function' && caught) {
1061 passed = caught.error instanceof expected;
1062 caught.error = caught.error.constructor;
1063 }
1064
1065 this._assert(passed, {
1066 message : defined(msg, 'should throw'),
1067 operator : 'throws',
1068 actual : caught && caught.error,
1069 expected : expected,
1070 error: !passed && caught && caught.error,
1071 extra : extra
1072 });
1073};
1074
1075Test.prototype.doesNotThrow = function (fn, expected, msg, extra) {
1076 if (typeof expected === 'string') {
1077 msg = expected;
1078 expected = undefined;
1079 }
1080 var caught = undefined;
1081 try {
1082 fn();
1083 }
1084 catch (err) {
1085 caught = { error : err };
1086 }
1087 this._assert(!caught, {
1088 message : defined(msg, 'should not throw'),
1089 operator : 'throws',
1090 actual : caught && caught.error,
1091 expected : expected,
1092 error : caught && caught.error,
1093 extra : extra
1094 });
1095};
1096
1097function has (obj, prop) {
1098 return Object.prototype.hasOwnProperty.call(obj, prop);
1099}
1100
1101Test.skip = function (name_, _opts, _cb) {
1102 var args = getTestArgs.apply(null, arguments);
1103 args.opts.skip = true;
1104 return Test(args.name, args.opts, args.cb);
1105};
1106
1107// vim: set softtabstop=4 shiftwidth=4:
1108
1109
1110}).call(this,require('_process'),"/node_modules/tape/lib")
1111},{"_process":24,"deep-equal":6,"defined":9,"events":20,"inherits":10,"path":23}],6:[function(require,module,exports){
1112var pSlice = Array.prototype.slice;
1113var objectKeys = require('./lib/keys.js');
1114var isArguments = require('./lib/is_arguments.js');
1115
1116var deepEqual = module.exports = function (actual, expected, opts) {
1117 if (!opts) opts = {};
1118 // 7.1. All identical values are equivalent, as determined by ===.
1119 if (actual === expected) {
1120 return true;
1121
1122 } else if (actual instanceof Date && expected instanceof Date) {
1123 return actual.getTime() === expected.getTime();
1124
1125 // 7.3. Other pairs that do not both pass typeof value == 'object',
1126 // equivalence is determined by ==.
1127 } else if (typeof actual != 'object' && typeof expected != 'object') {
1128 return opts.strict ? actual === expected : actual == expected;
1129
1130 // 7.4. For all other Object pairs, including Array objects, equivalence is
1131 // determined by having the same number of owned properties (as verified
1132 // with Object.prototype.hasOwnProperty.call), the same set of keys
1133 // (although not necessarily the same order), equivalent values for every
1134 // corresponding key, and an identical 'prototype' property. Note: this
1135 // accounts for both named and indexed properties on Arrays.
1136 } else {
1137 return objEquiv(actual, expected, opts);
1138 }
1139}
1140
1141function isUndefinedOrNull(value) {
1142 return value === null || value === undefined;
1143}
1144
1145function isBuffer (x) {
1146 if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
1147 if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
1148 return false;
1149 }
1150 if (x.length > 0 && typeof x[0] !== 'number') return false;
1151 return true;
1152}
1153
1154function objEquiv(a, b, opts) {
1155 var i, key;
1156 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
1157 return false;
1158 // an identical 'prototype' property.
1159 if (a.prototype !== b.prototype) return false;
1160 //~~~I've managed to break Object.keys through screwy arguments passing.
1161 // Converting to array solves the problem.
1162 if (isArguments(a)) {
1163 if (!isArguments(b)) {
1164 return false;
1165 }
1166 a = pSlice.call(a);
1167 b = pSlice.call(b);
1168 return deepEqual(a, b, opts);
1169 }
1170 if (isBuffer(a)) {
1171 if (!isBuffer(b)) {
1172 return false;
1173 }
1174 if (a.length !== b.length) return false;
1175 for (i = 0; i < a.length; i++) {
1176 if (a[i] !== b[i]) return false;
1177 }
1178 return true;
1179 }
1180 try {
1181 var ka = objectKeys(a),
1182 kb = objectKeys(b);
1183 } catch (e) {//happens when one is a string literal and the other isn't
1184 return false;
1185 }
1186 // having the same number of owned properties (keys incorporates
1187 // hasOwnProperty)
1188 if (ka.length != kb.length)
1189 return false;
1190 //the same set of keys (although not necessarily the same order),
1191 ka.sort();
1192 kb.sort();
1193 //~~~cheap key test
1194 for (i = ka.length - 1; i >= 0; i--) {
1195 if (ka[i] != kb[i])
1196 return false;
1197 }
1198 //equivalent values for every corresponding key, and
1199 //~~~possibly expensive deep test
1200 for (i = ka.length - 1; i >= 0; i--) {
1201 key = ka[i];
1202 if (!deepEqual(a[key], b[key], opts)) return false;
1203 }
1204 return typeof a === typeof b;
1205}
1206
1207},{"./lib/is_arguments.js":7,"./lib/keys.js":8}],7:[function(require,module,exports){
1208var supportsArgumentsClass = (function(){
1209 return Object.prototype.toString.call(arguments)
1210})() == '[object Arguments]';
1211
1212exports = module.exports = supportsArgumentsClass ? supported : unsupported;
1213
1214exports.supported = supported;
1215function supported(object) {
1216 return Object.prototype.toString.call(object) == '[object Arguments]';
1217};
1218
1219exports.unsupported = unsupported;
1220function unsupported(object){
1221 return object &&
1222 typeof object == 'object' &&
1223 typeof object.length == 'number' &&
1224 Object.prototype.hasOwnProperty.call(object, 'callee') &&
1225 !Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
1226 false;
1227};
1228
1229},{}],8:[function(require,module,exports){
1230exports = module.exports = typeof Object.keys === 'function'
1231 ? Object.keys : shim;
1232
1233exports.shim = shim;
1234function shim (obj) {
1235 var keys = [];
1236 for (var key in obj) keys.push(key);
1237 return keys;
1238}
1239
1240},{}],9:[function(require,module,exports){
1241module.exports = function () {
1242 for (var i = 0; i < arguments.length; i++) {
1243 if (arguments[i] !== undefined) return arguments[i];
1244 }
1245};
1246
1247},{}],10:[function(require,module,exports){
1248if (typeof Object.create === 'function') {
1249 // implementation from standard node.js 'util' module
1250 module.exports = function inherits(ctor, superCtor) {
1251 ctor.super_ = superCtor
1252 ctor.prototype = Object.create(superCtor.prototype, {
1253 constructor: {
1254 value: ctor,
1255 enumerable: false,
1256 writable: true,
1257 configurable: true
1258 }
1259 });
1260 };
1261} else {
1262 // old school shim for old browsers
1263 module.exports = function inherits(ctor, superCtor) {
1264 ctor.super_ = superCtor
1265 var TempCtor = function () {}
1266 TempCtor.prototype = superCtor.prototype
1267 ctor.prototype = new TempCtor()
1268 ctor.prototype.constructor = ctor
1269 }
1270}
1271
1272},{}],11:[function(require,module,exports){
1273module.exports = function inspect_ (obj, opts, depth, seen) {
1274 if (!opts) opts = {};
1275
1276 var maxDepth = opts.depth === undefined ? 5 : opts.depth;
1277 if (depth === undefined) depth = 0;
1278 if (depth >= maxDepth && maxDepth > 0
1279 && obj && typeof obj === 'object') {
1280 return '[Object]';
1281 }
1282
1283 if (seen === undefined) seen = [];
1284 else if (indexOf(seen, obj) >= 0) {
1285 return '[Circular]';
1286 }
1287
1288 function inspect (value, from) {
1289 if (from) {
1290 seen = seen.slice();
1291 seen.push(from);
1292 }
1293 return inspect_(value, opts, depth + 1, seen);
1294 }
1295
1296 if (typeof obj === 'string') {
1297 return inspectString(obj);
1298 }
1299 else if (typeof obj === 'function') {
1300 var name = nameOf(obj);
1301 return '[Function' + (name ? ': ' + name : '') + ']';
1302 }
1303 else if (obj === null) {
1304 return 'null';
1305 }
1306 else if (isElement(obj)) {
1307 var s = '<' + String(obj.nodeName).toLowerCase();
1308 var attrs = obj.attributes || [];
1309 for (var i = 0; i < attrs.length; i++) {
1310 s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
1311 }
1312 s += '>';
1313 if (obj.childNodes && obj.childNodes.length) s += '...';
1314 s += '</' + String(obj.nodeName).toLowerCase() + '>';
1315 return s;
1316 }
1317 else if (isArray(obj)) {
1318 if (obj.length === 0) return '[]';
1319 var xs = Array(obj.length);
1320 for (var i = 0; i < obj.length; i++) {
1321 xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
1322 }
1323 return '[ ' + xs.join(', ') + ' ]';
1324 }
1325 else if (isError(obj)) {
1326 var parts = [];
1327 for (var key in obj) {
1328 if (!has(obj, key)) continue;
1329
1330 if (/[^\w$]/.test(key)) {
1331 parts.push(inspect(key) + ': ' + inspect(obj[key]));
1332 }
1333 else {
1334 parts.push(key + ': ' + inspect(obj[key]));
1335 }
1336 }
1337 if (parts.length === 0) return '[' + obj + ']';
1338 return '{ [' + obj + '] ' + parts.join(', ') + ' }';
1339 }
1340 else if (typeof obj === 'object' && typeof obj.inspect === 'function') {
1341 return obj.inspect();
1342 }
1343 else if (typeof obj === 'object' && !isDate(obj) && !isRegExp(obj)) {
1344 var xs = [], keys = [];
1345 for (var key in obj) {
1346 if (has(obj, key)) keys.push(key);
1347 }
1348 keys.sort();
1349 for (var i = 0; i < keys.length; i++) {
1350 var key = keys[i];
1351 if (/[^\w$]/.test(key)) {
1352 xs.push(inspect(key) + ': ' + inspect(obj[key], obj));
1353 }
1354 else xs.push(key + ': ' + inspect(obj[key], obj));
1355 }
1356 if (xs.length === 0) return '{}';
1357 return '{ ' + xs.join(', ') + ' }';
1358 }
1359 else return String(obj);
1360};
1361
1362function quote (s) {
1363 return String(s).replace(/"/g, '&quot;');
1364}
1365
1366function isArray (obj) { return toStr(obj) === '[object Array]' }
1367function isDate (obj) { return toStr(obj) === '[object Date]' }
1368function isRegExp (obj) { return toStr(obj) === '[object RegExp]' }
1369function isError (obj) { return toStr(obj) === '[object Error]' }
1370
1371function has (obj, key) {
1372 if (!{}.hasOwnProperty) return key in obj;
1373 return {}.hasOwnProperty.call(obj, key);
1374}
1375
1376function toStr (obj) {
1377 return Object.prototype.toString.call(obj);
1378}
1379
1380function nameOf (f) {
1381 if (f.name) return f.name;
1382 var m = f.toString().match(/^function\s*([\w$]+)/);
1383 if (m) return m[1];
1384}
1385
1386function indexOf (xs, x) {
1387 if (xs.indexOf) return xs.indexOf(x);
1388 for (var i = 0, l = xs.length; i < l; i++) {
1389 if (xs[i] === x) return i;
1390 }
1391 return -1;
1392}
1393
1394function isElement (x) {
1395 if (!x || typeof x !== 'object') return false;
1396 if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
1397 return true;
1398 }
1399 return typeof x.nodeName === 'string'
1400 && typeof x.getAttribute === 'function'
1401 ;
1402}
1403
1404function inspectString (str) {
1405 var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
1406 return "'" + s + "'";
1407
1408 function lowbyte (c) {
1409 var n = c.charCodeAt(0);
1410 var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
1411 if (x) return '\\' + x;
1412 return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
1413 }
1414}
1415
1416},{}],12:[function(require,module,exports){
1417(function (process){
1418var through = require('through');
1419var nextTick = typeof setImmediate !== 'undefined'
1420 ? setImmediate
1421 : process.nextTick
1422;
1423
1424module.exports = function (write, end) {
1425 var tr = through(write, end);
1426 tr.pause();
1427 var resume = tr.resume;
1428 var pause = tr.pause;
1429 var paused = false;
1430
1431 tr.pause = function () {
1432 paused = true;
1433 return pause.apply(this, arguments);
1434 };
1435
1436 tr.resume = function () {
1437 paused = false;
1438 return resume.apply(this, arguments);
1439 };
1440
1441 nextTick(function () {
1442 if (!paused) tr.resume();
1443 });
1444
1445 return tr;
1446};
1447
1448}).call(this,require('_process'))
1449},{"_process":24,"through":13}],13:[function(require,module,exports){
1450(function (process){
1451var Stream = require('stream')
1452
1453// through
1454//
1455// a stream that does nothing but re-emit the input.
1456// useful for aggregating a series of changing but not ending streams into one stream)
1457
1458exports = module.exports = through
1459through.through = through
1460
1461//create a readable writable stream.
1462
1463function through (write, end, opts) {
1464 write = write || function (data) { this.queue(data) }
1465 end = end || function () { this.queue(null) }
1466
1467 var ended = false, destroyed = false, buffer = [], _ended = false
1468 var stream = new Stream()
1469 stream.readable = stream.writable = true
1470 stream.paused = false
1471
1472// stream.autoPause = !(opts && opts.autoPause === false)
1473 stream.autoDestroy = !(opts && opts.autoDestroy === false)
1474
1475 stream.write = function (data) {
1476 write.call(this, data)
1477 return !stream.paused
1478 }
1479
1480 function drain() {
1481 while(buffer.length && !stream.paused) {
1482 var data = buffer.shift()
1483 if(null === data)
1484 return stream.emit('end')
1485 else
1486 stream.emit('data', data)
1487 }
1488 }
1489
1490 stream.queue = stream.push = function (data) {
1491// console.error(ended)
1492 if(_ended) return stream
1493 if(data === null) _ended = true
1494 buffer.push(data)
1495 drain()
1496 return stream
1497 }
1498
1499 //this will be registered as the first 'end' listener
1500 //must call destroy next tick, to make sure we're after any
1501 //stream piped from here.
1502 //this is only a problem if end is not emitted synchronously.
1503 //a nicer way to do this is to make sure this is the last listener for 'end'
1504
1505 stream.on('end', function () {
1506 stream.readable = false
1507 if(!stream.writable && stream.autoDestroy)
1508 process.nextTick(function () {
1509 stream.destroy()
1510 })
1511 })
1512
1513 function _end () {
1514 stream.writable = false
1515 end.call(stream)
1516 if(!stream.readable && stream.autoDestroy)
1517 stream.destroy()
1518 }
1519
1520 stream.end = function (data) {
1521 if(ended) return
1522 ended = true
1523 if(arguments.length) stream.write(data)
1524 _end() // will emit or queue
1525 return stream
1526 }
1527
1528 stream.destroy = function () {
1529 if(destroyed) return
1530 destroyed = true
1531 ended = true
1532 buffer.length = 0
1533 stream.writable = stream.readable = false
1534 stream.emit('close')
1535 return stream
1536 }
1537
1538 stream.pause = function () {
1539 if(stream.paused) return
1540 stream.paused = true
1541 return stream
1542 }
1543
1544 stream.resume = function () {
1545 if(stream.paused) {
1546 stream.paused = false
1547 stream.emit('resume')
1548 }
1549 drain()
1550 //may have become paused again,
1551 //as drain emits 'data'.
1552 if(!stream.paused)
1553 stream.emit('drain')
1554 return stream
1555 }
1556 return stream
1557}
1558
1559
1560}).call(this,require('_process'))
1561},{"_process":24,"stream":36}],14:[function(require,module,exports){
1562
1563},{}],15:[function(require,module,exports){
1564arguments[4][14][0].apply(exports,arguments)
1565},{"dup":14}],16:[function(require,module,exports){
1566/*!
1567 * The buffer module from node.js, for the browser.
1568 *
1569 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
1570 * @license MIT
1571 */
1572
1573var base64 = require('base64-js')
1574var ieee754 = require('ieee754')
1575var isArray = require('is-array')
1576
1577exports.Buffer = Buffer
1578exports.SlowBuffer = SlowBuffer
1579exports.INSPECT_MAX_BYTES = 50
1580Buffer.poolSize = 8192 // not used by this implementation
1581
1582var kMaxLength = 0x3fffffff
1583var rootParent = {}
1584
1585/**
1586 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1587 * === true Use Uint8Array implementation (fastest)
1588 * === false Use Object implementation (most compatible, even IE6)
1589 *
1590 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1591 * Opera 11.6+, iOS 4.2+.
1592 *
1593 * Note:
1594 *
1595 * - Implementation must support adding new properties to `Uint8Array` instances.
1596 * Firefox 4-29 lacked support, fixed in Firefox 30+.
1597 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
1598 *
1599 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
1600 *
1601 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
1602 * incorrect length in some situations.
1603 *
1604 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
1605 * get the Object implementation, which is slower but will work correctly.
1606 */
1607Buffer.TYPED_ARRAY_SUPPORT = (function () {
1608 try {
1609 var buf = new ArrayBuffer(0)
1610 var arr = new Uint8Array(buf)
1611 arr.foo = function () { return 42 }
1612 return arr.foo() === 42 && // typed array instances can be augmented
1613 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
1614 new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
1615 } catch (e) {
1616 return false
1617 }
1618})()
1619
1620/**
1621 * Class: Buffer
1622 * =============
1623 *
1624 * The Buffer constructor returns instances of `Uint8Array` that are augmented
1625 * with function properties for all the node `Buffer` API functions. We use
1626 * `Uint8Array` so that square bracket notation works as expected -- it returns
1627 * a single octet.
1628 *
1629 * By augmenting the instances, we can avoid modifying the `Uint8Array`
1630 * prototype.
1631 */
1632function Buffer (arg) {
1633 if (!(this instanceof Buffer)) {
1634 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
1635 if (arguments.length > 1) return new Buffer(arg, arguments[1])
1636 return new Buffer(arg)
1637 }
1638
1639 this.length = 0
1640 this.parent = undefined
1641
1642 // Common case.
1643 if (typeof arg === 'number') {
1644 return fromNumber(this, arg)
1645 }
1646
1647 // Slightly less common case.
1648 if (typeof arg === 'string') {
1649 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
1650 }
1651
1652 // Unusual.
1653 return fromObject(this, arg)
1654}
1655
1656function fromNumber (that, length) {
1657 that = allocate(that, length < 0 ? 0 : checked(length) | 0)
1658 if (!Buffer.TYPED_ARRAY_SUPPORT) {
1659 for (var i = 0; i < length; i++) {
1660 that[i] = 0
1661 }
1662 }
1663 return that
1664}
1665
1666function fromString (that, string, encoding) {
1667 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
1668
1669 // Assumption: byteLength() return value is always < kMaxLength.
1670 var length = byteLength(string, encoding) | 0
1671 that = allocate(that, length)
1672
1673 that.write(string, encoding)
1674 return that
1675}
1676
1677function fromObject (that, object) {
1678 if (Buffer.isBuffer(object)) return fromBuffer(that, object)
1679
1680 if (isArray(object)) return fromArray(that, object)
1681
1682 if (object == null) {
1683 throw new TypeError('must start with number, buffer, array or string')
1684 }
1685
1686 if (typeof ArrayBuffer !== 'undefined' && object.buffer instanceof ArrayBuffer) {
1687 return fromTypedArray(that, object)
1688 }
1689
1690 if (object.length) return fromArrayLike(that, object)
1691
1692 return fromJsonObject(that, object)
1693}
1694
1695function fromBuffer (that, buffer) {
1696 var length = checked(buffer.length) | 0
1697 that = allocate(that, length)
1698 buffer.copy(that, 0, 0, length)
1699 return that
1700}
1701
1702function fromArray (that, array) {
1703 var length = checked(array.length) | 0
1704 that = allocate(that, length)
1705 for (var i = 0; i < length; i += 1) {
1706 that[i] = array[i] & 255
1707 }
1708 return that
1709}
1710
1711// Duplicate of fromArray() to keep fromArray() monomorphic.
1712function fromTypedArray (that, array) {
1713 var length = checked(array.length) | 0
1714 that = allocate(that, length)
1715 // Truncating the elements is probably not what people expect from typed
1716 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
1717 // of the old Buffer constructor.
1718 for (var i = 0; i < length; i += 1) {
1719 that[i] = array[i] & 255
1720 }
1721 return that
1722}
1723
1724function fromArrayLike (that, array) {
1725 var length = checked(array.length) | 0
1726 that = allocate(that, length)
1727 for (var i = 0; i < length; i += 1) {
1728 that[i] = array[i] & 255
1729 }
1730 return that
1731}
1732
1733// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
1734// Returns a zero-length buffer for inputs that don't conform to the spec.
1735function fromJsonObject (that, object) {
1736 var array
1737 var length = 0
1738
1739 if (object.type === 'Buffer' && isArray(object.data)) {
1740 array = object.data
1741 length = checked(array.length) | 0
1742 }
1743 that = allocate(that, length)
1744
1745 for (var i = 0; i < length; i += 1) {
1746 that[i] = array[i] & 255
1747 }
1748 return that
1749}
1750
1751function allocate (that, length) {
1752 if (Buffer.TYPED_ARRAY_SUPPORT) {
1753 // Return an augmented `Uint8Array` instance, for best performance
1754 that = Buffer._augment(new Uint8Array(length))
1755 } else {
1756 // Fallback: Return an object instance of the Buffer class
1757 that.length = length
1758 that._isBuffer = true
1759 }
1760
1761 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
1762 if (fromPool) that.parent = rootParent
1763
1764 return that
1765}
1766
1767function checked (length) {
1768 // Note: cannot use `length < kMaxLength` here because that fails when
1769 // length is NaN (which is otherwise coerced to zero.)
1770 if (length >= kMaxLength) {
1771 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1772 'size: 0x' + kMaxLength.toString(16) + ' bytes')
1773 }
1774 return length | 0
1775}
1776
1777function SlowBuffer (subject, encoding) {
1778 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
1779
1780 var buf = new Buffer(subject, encoding)
1781 delete buf.parent
1782 return buf
1783}
1784
1785Buffer.isBuffer = function isBuffer (b) {
1786 return !!(b != null && b._isBuffer)
1787}
1788
1789Buffer.compare = function compare (a, b) {
1790 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1791 throw new TypeError('Arguments must be Buffers')
1792 }
1793
1794 if (a === b) return 0
1795
1796 var x = a.length
1797 var y = b.length
1798
1799 var i = 0
1800 var len = Math.min(x, y)
1801 while (i < len) {
1802 if (a[i] !== b[i]) break
1803
1804 ++i
1805 }
1806
1807 if (i !== len) {
1808 x = a[i]
1809 y = b[i]
1810 }
1811
1812 if (x < y) return -1
1813 if (y < x) return 1
1814 return 0
1815}
1816
1817Buffer.isEncoding = function isEncoding (encoding) {
1818 switch (String(encoding).toLowerCase()) {
1819 case 'hex':
1820 case 'utf8':
1821 case 'utf-8':
1822 case 'ascii':
1823 case 'binary':
1824 case 'base64':
1825 case 'raw':
1826 case 'ucs2':
1827 case 'ucs-2':
1828 case 'utf16le':
1829 case 'utf-16le':
1830 return true
1831 default:
1832 return false
1833 }
1834}
1835
1836Buffer.concat = function concat (list, length) {
1837 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
1838
1839 if (list.length === 0) {
1840 return new Buffer(0)
1841 } else if (list.length === 1) {
1842 return list[0]
1843 }
1844
1845 var i
1846 if (length === undefined) {
1847 length = 0
1848 for (i = 0; i < list.length; i++) {
1849 length += list[i].length
1850 }
1851 }
1852
1853 var buf = new Buffer(length)
1854 var pos = 0
1855 for (i = 0; i < list.length; i++) {
1856 var item = list[i]
1857 item.copy(buf, pos)
1858 pos += item.length
1859 }
1860 return buf
1861}
1862
1863function byteLength (string, encoding) {
1864 if (typeof string !== 'string') string = String(string)
1865
1866 if (string.length === 0) return 0
1867
1868 switch (encoding || 'utf8') {
1869 case 'ascii':
1870 case 'binary':
1871 case 'raw':
1872 return string.length
1873 case 'ucs2':
1874 case 'ucs-2':
1875 case 'utf16le':
1876 case 'utf-16le':
1877 return string.length * 2
1878 case 'hex':
1879 return string.length >>> 1
1880 case 'utf8':
1881 case 'utf-8':
1882 return utf8ToBytes(string).length
1883 case 'base64':
1884 return base64ToBytes(string).length
1885 default:
1886 return string.length
1887 }
1888}
1889Buffer.byteLength = byteLength
1890
1891// pre-set for values that may exist in the future
1892Buffer.prototype.length = undefined
1893Buffer.prototype.parent = undefined
1894
1895// toString(encoding, start=0, end=buffer.length)
1896Buffer.prototype.toString = function toString (encoding, start, end) {
1897 var loweredCase = false
1898
1899 start = start | 0
1900 end = end === undefined || end === Infinity ? this.length : end | 0
1901
1902 if (!encoding) encoding = 'utf8'
1903 if (start < 0) start = 0
1904 if (end > this.length) end = this.length
1905 if (end <= start) return ''
1906
1907 while (true) {
1908 switch (encoding) {
1909 case 'hex':
1910 return hexSlice(this, start, end)
1911
1912 case 'utf8':
1913 case 'utf-8':
1914 return utf8Slice(this, start, end)
1915
1916 case 'ascii':
1917 return asciiSlice(this, start, end)
1918
1919 case 'binary':
1920 return binarySlice(this, start, end)
1921
1922 case 'base64':
1923 return base64Slice(this, start, end)
1924
1925 case 'ucs2':
1926 case 'ucs-2':
1927 case 'utf16le':
1928 case 'utf-16le':
1929 return utf16leSlice(this, start, end)
1930
1931 default:
1932 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1933 encoding = (encoding + '').toLowerCase()
1934 loweredCase = true
1935 }
1936 }
1937}
1938
1939Buffer.prototype.equals = function equals (b) {
1940 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1941 if (this === b) return true
1942 return Buffer.compare(this, b) === 0
1943}
1944
1945Buffer.prototype.inspect = function inspect () {
1946 var str = ''
1947 var max = exports.INSPECT_MAX_BYTES
1948 if (this.length > 0) {
1949 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1950 if (this.length > max) str += ' ... '
1951 }
1952 return '<Buffer ' + str + '>'
1953}
1954
1955Buffer.prototype.compare = function compare (b) {
1956 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1957 if (this === b) return 0
1958 return Buffer.compare(this, b)
1959}
1960
1961Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
1962 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
1963 else if (byteOffset < -0x80000000) byteOffset = -0x80000000
1964 byteOffset >>= 0
1965
1966 if (this.length === 0) return -1
1967 if (byteOffset >= this.length) return -1
1968
1969 // Negative offsets start from the end of the buffer
1970 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
1971
1972 if (typeof val === 'string') {
1973 if (val.length === 0) return -1 // special case: looking for empty string always fails
1974 return String.prototype.indexOf.call(this, val, byteOffset)
1975 }
1976 if (Buffer.isBuffer(val)) {
1977 return arrayIndexOf(this, val, byteOffset)
1978 }
1979 if (typeof val === 'number') {
1980 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
1981 return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
1982 }
1983 return arrayIndexOf(this, [ val ], byteOffset)
1984 }
1985
1986 function arrayIndexOf (arr, val, byteOffset) {
1987 var foundIndex = -1
1988 for (var i = 0; byteOffset + i < arr.length; i++) {
1989 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
1990 if (foundIndex === -1) foundIndex = i
1991 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
1992 } else {
1993 foundIndex = -1
1994 }
1995 }
1996 return -1
1997 }
1998
1999 throw new TypeError('val must be string, number or Buffer')
2000}
2001
2002// `get` will be removed in Node 0.13+
2003Buffer.prototype.get = function get (offset) {
2004 console.log('.get() is deprecated. Access using array indexes instead.')
2005 return this.readUInt8(offset)
2006}
2007
2008// `set` will be removed in Node 0.13+
2009Buffer.prototype.set = function set (v, offset) {
2010 console.log('.set() is deprecated. Access using array indexes instead.')
2011 return this.writeUInt8(v, offset)
2012}
2013
2014function hexWrite (buf, string, offset, length) {
2015 offset = Number(offset) || 0
2016 var remaining = buf.length - offset
2017 if (!length) {
2018 length = remaining
2019 } else {
2020 length = Number(length)
2021 if (length > remaining) {
2022 length = remaining
2023 }
2024 }
2025
2026 // must be an even number of digits
2027 var strLen = string.length
2028 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
2029
2030 if (length > strLen / 2) {
2031 length = strLen / 2
2032 }
2033 for (var i = 0; i < length; i++) {
2034 var parsed = parseInt(string.substr(i * 2, 2), 16)
2035 if (isNaN(parsed)) throw new Error('Invalid hex string')
2036 buf[offset + i] = parsed
2037 }
2038 return i
2039}
2040
2041function utf8Write (buf, string, offset, length) {
2042 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2043}
2044
2045function asciiWrite (buf, string, offset, length) {
2046 return blitBuffer(asciiToBytes(string), buf, offset, length)
2047}
2048
2049function binaryWrite (buf, string, offset, length) {
2050 return asciiWrite(buf, string, offset, length)
2051}
2052
2053function base64Write (buf, string, offset, length) {
2054 return blitBuffer(base64ToBytes(string), buf, offset, length)
2055}
2056
2057function ucs2Write (buf, string, offset, length) {
2058 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2059}
2060
2061Buffer.prototype.write = function write (string, offset, length, encoding) {
2062 // Buffer#write(string)
2063 if (offset === undefined) {
2064 encoding = 'utf8'
2065 length = this.length
2066 offset = 0
2067 // Buffer#write(string, encoding)
2068 } else if (length === undefined && typeof offset === 'string') {
2069 encoding = offset
2070 length = this.length
2071 offset = 0
2072 // Buffer#write(string, offset[, length][, encoding])
2073 } else if (isFinite(offset)) {
2074 offset = offset | 0
2075 if (isFinite(length)) {
2076 length = length | 0
2077 if (encoding === undefined) encoding = 'utf8'
2078 } else {
2079 encoding = length
2080 length = undefined
2081 }
2082 // legacy write(string, encoding, offset, length) - remove in v0.13
2083 } else {
2084 var swap = encoding
2085 encoding = offset
2086 offset = length | 0
2087 length = swap
2088 }
2089
2090 var remaining = this.length - offset
2091 if (length === undefined || length > remaining) length = remaining
2092
2093 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2094 throw new RangeError('attempt to write outside buffer bounds')
2095 }
2096
2097 if (!encoding) encoding = 'utf8'
2098
2099 var loweredCase = false
2100 for (;;) {
2101 switch (encoding) {
2102 case 'hex':
2103 return hexWrite(this, string, offset, length)
2104
2105 case 'utf8':
2106 case 'utf-8':
2107 return utf8Write(this, string, offset, length)
2108
2109 case 'ascii':
2110 return asciiWrite(this, string, offset, length)
2111
2112 case 'binary':
2113 return binaryWrite(this, string, offset, length)
2114
2115 case 'base64':
2116 // Warning: maxLength not taken into account in base64Write
2117 return base64Write(this, string, offset, length)
2118
2119 case 'ucs2':
2120 case 'ucs-2':
2121 case 'utf16le':
2122 case 'utf-16le':
2123 return ucs2Write(this, string, offset, length)
2124
2125 default:
2126 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2127 encoding = ('' + encoding).toLowerCase()
2128 loweredCase = true
2129 }
2130 }
2131}
2132
2133Buffer.prototype.toJSON = function toJSON () {
2134 return {
2135 type: 'Buffer',
2136 data: Array.prototype.slice.call(this._arr || this, 0)
2137 }
2138}
2139
2140function base64Slice (buf, start, end) {
2141 if (start === 0 && end === buf.length) {
2142 return base64.fromByteArray(buf)
2143 } else {
2144 return base64.fromByteArray(buf.slice(start, end))
2145 }
2146}
2147
2148function utf8Slice (buf, start, end) {
2149 var res = ''
2150 var tmp = ''
2151 end = Math.min(buf.length, end)
2152
2153 for (var i = start; i < end; i++) {
2154 if (buf[i] <= 0x7F) {
2155 res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
2156 tmp = ''
2157 } else {
2158 tmp += '%' + buf[i].toString(16)
2159 }
2160 }
2161
2162 return res + decodeUtf8Char(tmp)
2163}
2164
2165function asciiSlice (buf, start, end) {
2166 var ret = ''
2167 end = Math.min(buf.length, end)
2168
2169 for (var i = start; i < end; i++) {
2170 ret += String.fromCharCode(buf[i] & 0x7F)
2171 }
2172 return ret
2173}
2174
2175function binarySlice (buf, start, end) {
2176 var ret = ''
2177 end = Math.min(buf.length, end)
2178
2179 for (var i = start; i < end; i++) {
2180 ret += String.fromCharCode(buf[i])
2181 }
2182 return ret
2183}
2184
2185function hexSlice (buf, start, end) {
2186 var len = buf.length
2187
2188 if (!start || start < 0) start = 0
2189 if (!end || end < 0 || end > len) end = len
2190
2191 var out = ''
2192 for (var i = start; i < end; i++) {
2193 out += toHex(buf[i])
2194 }
2195 return out
2196}
2197
2198function utf16leSlice (buf, start, end) {
2199 var bytes = buf.slice(start, end)
2200 var res = ''
2201 for (var i = 0; i < bytes.length; i += 2) {
2202 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
2203 }
2204 return res
2205}
2206
2207Buffer.prototype.slice = function slice (start, end) {
2208 var len = this.length
2209 start = ~~start
2210 end = end === undefined ? len : ~~end
2211
2212 if (start < 0) {
2213 start += len
2214 if (start < 0) start = 0
2215 } else if (start > len) {
2216 start = len
2217 }
2218
2219 if (end < 0) {
2220 end += len
2221 if (end < 0) end = 0
2222 } else if (end > len) {
2223 end = len
2224 }
2225
2226 if (end < start) end = start
2227
2228 var newBuf
2229 if (Buffer.TYPED_ARRAY_SUPPORT) {
2230 newBuf = Buffer._augment(this.subarray(start, end))
2231 } else {
2232 var sliceLen = end - start
2233 newBuf = new Buffer(sliceLen, undefined)
2234 for (var i = 0; i < sliceLen; i++) {
2235 newBuf[i] = this[i + start]
2236 }
2237 }
2238
2239 if (newBuf.length) newBuf.parent = this.parent || this
2240
2241 return newBuf
2242}
2243
2244/*
2245 * Need to make sure that buffer isn't trying to write out of bounds.
2246 */
2247function checkOffset (offset, ext, length) {
2248 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2249 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2250}
2251
2252Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2253 offset = offset | 0
2254 byteLength = byteLength | 0
2255 if (!noAssert) checkOffset(offset, byteLength, this.length)
2256
2257 var val = this[offset]
2258 var mul = 1
2259 var i = 0
2260 while (++i < byteLength && (mul *= 0x100)) {
2261 val += this[offset + i] * mul
2262 }
2263
2264 return val
2265}
2266
2267Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2268 offset = offset | 0
2269 byteLength = byteLength | 0
2270 if (!noAssert) {
2271 checkOffset(offset, byteLength, this.length)
2272 }
2273
2274 var val = this[offset + --byteLength]
2275 var mul = 1
2276 while (byteLength > 0 && (mul *= 0x100)) {
2277 val += this[offset + --byteLength] * mul
2278 }
2279
2280 return val
2281}
2282
2283Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2284 if (!noAssert) checkOffset(offset, 1, this.length)
2285 return this[offset]
2286}
2287
2288Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2289 if (!noAssert) checkOffset(offset, 2, this.length)
2290 return this[offset] | (this[offset + 1] << 8)
2291}
2292
2293Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2294 if (!noAssert) checkOffset(offset, 2, this.length)
2295 return (this[offset] << 8) | this[offset + 1]
2296}
2297
2298Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2299 if (!noAssert) checkOffset(offset, 4, this.length)
2300
2301 return ((this[offset]) |
2302 (this[offset + 1] << 8) |
2303 (this[offset + 2] << 16)) +
2304 (this[offset + 3] * 0x1000000)
2305}
2306
2307Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2308 if (!noAssert) checkOffset(offset, 4, this.length)
2309
2310 return (this[offset] * 0x1000000) +
2311 ((this[offset + 1] << 16) |
2312 (this[offset + 2] << 8) |
2313 this[offset + 3])
2314}
2315
2316Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2317 offset = offset | 0
2318 byteLength = byteLength | 0
2319 if (!noAssert) checkOffset(offset, byteLength, this.length)
2320
2321 var val = this[offset]
2322 var mul = 1
2323 var i = 0
2324 while (++i < byteLength && (mul *= 0x100)) {
2325 val += this[offset + i] * mul
2326 }
2327 mul *= 0x80
2328
2329 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2330
2331 return val
2332}
2333
2334Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2335 offset = offset | 0
2336 byteLength = byteLength | 0
2337 if (!noAssert) checkOffset(offset, byteLength, this.length)
2338
2339 var i = byteLength
2340 var mul = 1
2341 var val = this[offset + --i]
2342 while (i > 0 && (mul *= 0x100)) {
2343 val += this[offset + --i] * mul
2344 }
2345 mul *= 0x80
2346
2347 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2348
2349 return val
2350}
2351
2352Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2353 if (!noAssert) checkOffset(offset, 1, this.length)
2354 if (!(this[offset] & 0x80)) return (this[offset])
2355 return ((0xff - this[offset] + 1) * -1)
2356}
2357
2358Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2359 if (!noAssert) checkOffset(offset, 2, this.length)
2360 var val = this[offset] | (this[offset + 1] << 8)
2361 return (val & 0x8000) ? val | 0xFFFF0000 : val
2362}
2363
2364Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2365 if (!noAssert) checkOffset(offset, 2, this.length)
2366 var val = this[offset + 1] | (this[offset] << 8)
2367 return (val & 0x8000) ? val | 0xFFFF0000 : val
2368}
2369
2370Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2371 if (!noAssert) checkOffset(offset, 4, this.length)
2372
2373 return (this[offset]) |
2374 (this[offset + 1] << 8) |
2375 (this[offset + 2] << 16) |
2376 (this[offset + 3] << 24)
2377}
2378
2379Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2380 if (!noAssert) checkOffset(offset, 4, this.length)
2381
2382 return (this[offset] << 24) |
2383 (this[offset + 1] << 16) |
2384 (this[offset + 2] << 8) |
2385 (this[offset + 3])
2386}
2387
2388Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2389 if (!noAssert) checkOffset(offset, 4, this.length)
2390 return ieee754.read(this, offset, true, 23, 4)
2391}
2392
2393Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2394 if (!noAssert) checkOffset(offset, 4, this.length)
2395 return ieee754.read(this, offset, false, 23, 4)
2396}
2397
2398Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2399 if (!noAssert) checkOffset(offset, 8, this.length)
2400 return ieee754.read(this, offset, true, 52, 8)
2401}
2402
2403Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2404 if (!noAssert) checkOffset(offset, 8, this.length)
2405 return ieee754.read(this, offset, false, 52, 8)
2406}
2407
2408function checkInt (buf, value, offset, ext, max, min) {
2409 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
2410 if (value > max || value < min) throw new RangeError('value is out of bounds')
2411 if (offset + ext > buf.length) throw new RangeError('index out of range')
2412}
2413
2414Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2415 value = +value
2416 offset = offset | 0
2417 byteLength = byteLength | 0
2418 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
2419
2420 var mul = 1
2421 var i = 0
2422 this[offset] = value & 0xFF
2423 while (++i < byteLength && (mul *= 0x100)) {
2424 this[offset + i] = (value / mul) & 0xFF
2425 }
2426
2427 return offset + byteLength
2428}
2429
2430Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2431 value = +value
2432 offset = offset | 0
2433 byteLength = byteLength | 0
2434 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
2435
2436 var i = byteLength - 1
2437 var mul = 1
2438 this[offset + i] = value & 0xFF
2439 while (--i >= 0 && (mul *= 0x100)) {
2440 this[offset + i] = (value / mul) & 0xFF
2441 }
2442
2443 return offset + byteLength
2444}
2445
2446Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2447 value = +value
2448 offset = offset | 0
2449 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2450 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
2451 this[offset] = value
2452 return offset + 1
2453}
2454
2455function objectWriteUInt16 (buf, value, offset, littleEndian) {
2456 if (value < 0) value = 0xffff + value + 1
2457 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
2458 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
2459 (littleEndian ? i : 1 - i) * 8
2460 }
2461}
2462
2463Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2464 value = +value
2465 offset = offset | 0
2466 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2467 if (Buffer.TYPED_ARRAY_SUPPORT) {
2468 this[offset] = value
2469 this[offset + 1] = (value >>> 8)
2470 } else {
2471 objectWriteUInt16(this, value, offset, true)
2472 }
2473 return offset + 2
2474}
2475
2476Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2477 value = +value
2478 offset = offset | 0
2479 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2480 if (Buffer.TYPED_ARRAY_SUPPORT) {
2481 this[offset] = (value >>> 8)
2482 this[offset + 1] = value
2483 } else {
2484 objectWriteUInt16(this, value, offset, false)
2485 }
2486 return offset + 2
2487}
2488
2489function objectWriteUInt32 (buf, value, offset, littleEndian) {
2490 if (value < 0) value = 0xffffffff + value + 1
2491 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
2492 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
2493 }
2494}
2495
2496Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2497 value = +value
2498 offset = offset | 0
2499 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2500 if (Buffer.TYPED_ARRAY_SUPPORT) {
2501 this[offset + 3] = (value >>> 24)
2502 this[offset + 2] = (value >>> 16)
2503 this[offset + 1] = (value >>> 8)
2504 this[offset] = value
2505 } else {
2506 objectWriteUInt32(this, value, offset, true)
2507 }
2508 return offset + 4
2509}
2510
2511Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2512 value = +value
2513 offset = offset | 0
2514 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2515 if (Buffer.TYPED_ARRAY_SUPPORT) {
2516 this[offset] = (value >>> 24)
2517 this[offset + 1] = (value >>> 16)
2518 this[offset + 2] = (value >>> 8)
2519 this[offset + 3] = value
2520 } else {
2521 objectWriteUInt32(this, value, offset, false)
2522 }
2523 return offset + 4
2524}
2525
2526Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2527 value = +value
2528 offset = offset | 0
2529 if (!noAssert) {
2530 var limit = Math.pow(2, 8 * byteLength - 1)
2531
2532 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2533 }
2534
2535 var i = 0
2536 var mul = 1
2537 var sub = value < 0 ? 1 : 0
2538 this[offset] = value & 0xFF
2539 while (++i < byteLength && (mul *= 0x100)) {
2540 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2541 }
2542
2543 return offset + byteLength
2544}
2545
2546Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2547 value = +value
2548 offset = offset | 0
2549 if (!noAssert) {
2550 var limit = Math.pow(2, 8 * byteLength - 1)
2551
2552 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2553 }
2554
2555 var i = byteLength - 1
2556 var mul = 1
2557 var sub = value < 0 ? 1 : 0
2558 this[offset + i] = value & 0xFF
2559 while (--i >= 0 && (mul *= 0x100)) {
2560 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2561 }
2562
2563 return offset + byteLength
2564}
2565
2566Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2567 value = +value
2568 offset = offset | 0
2569 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2570 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
2571 if (value < 0) value = 0xff + value + 1
2572 this[offset] = value
2573 return offset + 1
2574}
2575
2576Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2577 value = +value
2578 offset = offset | 0
2579 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2580 if (Buffer.TYPED_ARRAY_SUPPORT) {
2581 this[offset] = value
2582 this[offset + 1] = (value >>> 8)
2583 } else {
2584 objectWriteUInt16(this, value, offset, true)
2585 }
2586 return offset + 2
2587}
2588
2589Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2590 value = +value
2591 offset = offset | 0
2592 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2593 if (Buffer.TYPED_ARRAY_SUPPORT) {
2594 this[offset] = (value >>> 8)
2595 this[offset + 1] = value
2596 } else {
2597 objectWriteUInt16(this, value, offset, false)
2598 }
2599 return offset + 2
2600}
2601
2602Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2603 value = +value
2604 offset = offset | 0
2605 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2606 if (Buffer.TYPED_ARRAY_SUPPORT) {
2607 this[offset] = value
2608 this[offset + 1] = (value >>> 8)
2609 this[offset + 2] = (value >>> 16)
2610 this[offset + 3] = (value >>> 24)
2611 } else {
2612 objectWriteUInt32(this, value, offset, true)
2613 }
2614 return offset + 4
2615}
2616
2617Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2618 value = +value
2619 offset = offset | 0
2620 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2621 if (value < 0) value = 0xffffffff + value + 1
2622 if (Buffer.TYPED_ARRAY_SUPPORT) {
2623 this[offset] = (value >>> 24)
2624 this[offset + 1] = (value >>> 16)
2625 this[offset + 2] = (value >>> 8)
2626 this[offset + 3] = value
2627 } else {
2628 objectWriteUInt32(this, value, offset, false)
2629 }
2630 return offset + 4
2631}
2632
2633function checkIEEE754 (buf, value, offset, ext, max, min) {
2634 if (value > max || value < min) throw new RangeError('value is out of bounds')
2635 if (offset + ext > buf.length) throw new RangeError('index out of range')
2636 if (offset < 0) throw new RangeError('index out of range')
2637}
2638
2639function writeFloat (buf, value, offset, littleEndian, noAssert) {
2640 if (!noAssert) {
2641 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2642 }
2643 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2644 return offset + 4
2645}
2646
2647Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2648 return writeFloat(this, value, offset, true, noAssert)
2649}
2650
2651Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2652 return writeFloat(this, value, offset, false, noAssert)
2653}
2654
2655function writeDouble (buf, value, offset, littleEndian, noAssert) {
2656 if (!noAssert) {
2657 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2658 }
2659 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2660 return offset + 8
2661}
2662
2663Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2664 return writeDouble(this, value, offset, true, noAssert)
2665}
2666
2667Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2668 return writeDouble(this, value, offset, false, noAssert)
2669}
2670
2671// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2672Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2673 if (!start) start = 0
2674 if (!end && end !== 0) end = this.length
2675 if (targetStart >= target.length) targetStart = target.length
2676 if (!targetStart) targetStart = 0
2677 if (end > 0 && end < start) end = start
2678
2679 // Copy 0 bytes; we're done
2680 if (end === start) return 0
2681 if (target.length === 0 || this.length === 0) return 0
2682
2683 // Fatal error conditions
2684 if (targetStart < 0) {
2685 throw new RangeError('targetStart out of bounds')
2686 }
2687 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2688 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2689
2690 // Are we oob?
2691 if (end > this.length) end = this.length
2692 if (target.length - targetStart < end - start) {
2693 end = target.length - targetStart + start
2694 }
2695
2696 var len = end - start
2697
2698 if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
2699 for (var i = 0; i < len; i++) {
2700 target[i + targetStart] = this[i + start]
2701 }
2702 } else {
2703 target._set(this.subarray(start, start + len), targetStart)
2704 }
2705
2706 return len
2707}
2708
2709// fill(value, start=0, end=buffer.length)
2710Buffer.prototype.fill = function fill (value, start, end) {
2711 if (!value) value = 0
2712 if (!start) start = 0
2713 if (!end) end = this.length
2714
2715 if (end < start) throw new RangeError('end < start')
2716
2717 // Fill 0 bytes; we're done
2718 if (end === start) return
2719 if (this.length === 0) return
2720
2721 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
2722 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
2723
2724 var i
2725 if (typeof value === 'number') {
2726 for (i = start; i < end; i++) {
2727 this[i] = value
2728 }
2729 } else {
2730 var bytes = utf8ToBytes(value.toString())
2731 var len = bytes.length
2732 for (i = start; i < end; i++) {
2733 this[i] = bytes[i % len]
2734 }
2735 }
2736
2737 return this
2738}
2739
2740/**
2741 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
2742 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
2743 */
2744Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
2745 if (typeof Uint8Array !== 'undefined') {
2746 if (Buffer.TYPED_ARRAY_SUPPORT) {
2747 return (new Buffer(this)).buffer
2748 } else {
2749 var buf = new Uint8Array(this.length)
2750 for (var i = 0, len = buf.length; i < len; i += 1) {
2751 buf[i] = this[i]
2752 }
2753 return buf.buffer
2754 }
2755 } else {
2756 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
2757 }
2758}
2759
2760// HELPER FUNCTIONS
2761// ================
2762
2763var BP = Buffer.prototype
2764
2765/**
2766 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
2767 */
2768Buffer._augment = function _augment (arr) {
2769 arr.constructor = Buffer
2770 arr._isBuffer = true
2771
2772 // save reference to original Uint8Array set method before overwriting
2773 arr._set = arr.set
2774
2775 // deprecated, will be removed in node 0.13+
2776 arr.get = BP.get
2777 arr.set = BP.set
2778
2779 arr.write = BP.write
2780 arr.toString = BP.toString
2781 arr.toLocaleString = BP.toString
2782 arr.toJSON = BP.toJSON
2783 arr.equals = BP.equals
2784 arr.compare = BP.compare
2785 arr.indexOf = BP.indexOf
2786 arr.copy = BP.copy
2787 arr.slice = BP.slice
2788 arr.readUIntLE = BP.readUIntLE
2789 arr.readUIntBE = BP.readUIntBE
2790 arr.readUInt8 = BP.readUInt8
2791 arr.readUInt16LE = BP.readUInt16LE
2792 arr.readUInt16BE = BP.readUInt16BE
2793 arr.readUInt32LE = BP.readUInt32LE
2794 arr.readUInt32BE = BP.readUInt32BE
2795 arr.readIntLE = BP.readIntLE
2796 arr.readIntBE = BP.readIntBE
2797 arr.readInt8 = BP.readInt8
2798 arr.readInt16LE = BP.readInt16LE
2799 arr.readInt16BE = BP.readInt16BE
2800 arr.readInt32LE = BP.readInt32LE
2801 arr.readInt32BE = BP.readInt32BE
2802 arr.readFloatLE = BP.readFloatLE
2803 arr.readFloatBE = BP.readFloatBE
2804 arr.readDoubleLE = BP.readDoubleLE
2805 arr.readDoubleBE = BP.readDoubleBE
2806 arr.writeUInt8 = BP.writeUInt8
2807 arr.writeUIntLE = BP.writeUIntLE
2808 arr.writeUIntBE = BP.writeUIntBE
2809 arr.writeUInt16LE = BP.writeUInt16LE
2810 arr.writeUInt16BE = BP.writeUInt16BE
2811 arr.writeUInt32LE = BP.writeUInt32LE
2812 arr.writeUInt32BE = BP.writeUInt32BE
2813 arr.writeIntLE = BP.writeIntLE
2814 arr.writeIntBE = BP.writeIntBE
2815 arr.writeInt8 = BP.writeInt8
2816 arr.writeInt16LE = BP.writeInt16LE
2817 arr.writeInt16BE = BP.writeInt16BE
2818 arr.writeInt32LE = BP.writeInt32LE
2819 arr.writeInt32BE = BP.writeInt32BE
2820 arr.writeFloatLE = BP.writeFloatLE
2821 arr.writeFloatBE = BP.writeFloatBE
2822 arr.writeDoubleLE = BP.writeDoubleLE
2823 arr.writeDoubleBE = BP.writeDoubleBE
2824 arr.fill = BP.fill
2825 arr.inspect = BP.inspect
2826 arr.toArrayBuffer = BP.toArrayBuffer
2827
2828 return arr
2829}
2830
2831var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
2832
2833function base64clean (str) {
2834 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2835 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
2836 // Node converts strings with length < 2 to ''
2837 if (str.length < 2) return ''
2838 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2839 while (str.length % 4 !== 0) {
2840 str = str + '='
2841 }
2842 return str
2843}
2844
2845function stringtrim (str) {
2846 if (str.trim) return str.trim()
2847 return str.replace(/^\s+|\s+$/g, '')
2848}
2849
2850function toHex (n) {
2851 if (n < 16) return '0' + n.toString(16)
2852 return n.toString(16)
2853}
2854
2855function utf8ToBytes (string, units) {
2856 units = units || Infinity
2857 var codePoint
2858 var length = string.length
2859 var leadSurrogate = null
2860 var bytes = []
2861 var i = 0
2862
2863 for (; i < length; i++) {
2864 codePoint = string.charCodeAt(i)
2865
2866 // is surrogate component
2867 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2868 // last char was a lead
2869 if (leadSurrogate) {
2870 // 2 leads in a row
2871 if (codePoint < 0xDC00) {
2872 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2873 leadSurrogate = codePoint
2874 continue
2875 } else {
2876 // valid surrogate pair
2877 codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
2878 leadSurrogate = null
2879 }
2880 } else {
2881 // no lead yet
2882
2883 if (codePoint > 0xDBFF) {
2884 // unexpected trail
2885 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2886 continue
2887 } else if (i + 1 === length) {
2888 // unpaired lead
2889 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2890 continue
2891 } else {
2892 // valid lead
2893 leadSurrogate = codePoint
2894 continue
2895 }
2896 }
2897 } else if (leadSurrogate) {
2898 // valid bmp char, but last char was a lead
2899 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2900 leadSurrogate = null
2901 }
2902
2903 // encode utf8
2904 if (codePoint < 0x80) {
2905 if ((units -= 1) < 0) break
2906 bytes.push(codePoint)
2907 } else if (codePoint < 0x800) {
2908 if ((units -= 2) < 0) break
2909 bytes.push(
2910 codePoint >> 0x6 | 0xC0,
2911 codePoint & 0x3F | 0x80
2912 )
2913 } else if (codePoint < 0x10000) {
2914 if ((units -= 3) < 0) break
2915 bytes.push(
2916 codePoint >> 0xC | 0xE0,
2917 codePoint >> 0x6 & 0x3F | 0x80,
2918 codePoint & 0x3F | 0x80
2919 )
2920 } else if (codePoint < 0x200000) {
2921 if ((units -= 4) < 0) break
2922 bytes.push(
2923 codePoint >> 0x12 | 0xF0,
2924 codePoint >> 0xC & 0x3F | 0x80,
2925 codePoint >> 0x6 & 0x3F | 0x80,
2926 codePoint & 0x3F | 0x80
2927 )
2928 } else {
2929 throw new Error('Invalid code point')
2930 }
2931 }
2932
2933 return bytes
2934}
2935
2936function asciiToBytes (str) {
2937 var byteArray = []
2938 for (var i = 0; i < str.length; i++) {
2939 // Node's code seems to be doing this and not & 0x7F..
2940 byteArray.push(str.charCodeAt(i) & 0xFF)
2941 }
2942 return byteArray
2943}
2944
2945function utf16leToBytes (str, units) {
2946 var c, hi, lo
2947 var byteArray = []
2948 for (var i = 0; i < str.length; i++) {
2949 if ((units -= 2) < 0) break
2950
2951 c = str.charCodeAt(i)
2952 hi = c >> 8
2953 lo = c % 256
2954 byteArray.push(lo)
2955 byteArray.push(hi)
2956 }
2957
2958 return byteArray
2959}
2960
2961function base64ToBytes (str) {
2962 return base64.toByteArray(base64clean(str))
2963}
2964
2965function blitBuffer (src, dst, offset, length) {
2966 for (var i = 0; i < length; i++) {
2967 if ((i + offset >= dst.length) || (i >= src.length)) break
2968 dst[i + offset] = src[i]
2969 }
2970 return i
2971}
2972
2973function decodeUtf8Char (str) {
2974 try {
2975 return decodeURIComponent(str)
2976 } catch (err) {
2977 return String.fromCharCode(0xFFFD) // UTF 8 invalid char
2978 }
2979}
2980
2981},{"base64-js":17,"ieee754":18,"is-array":19}],17:[function(require,module,exports){
2982var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2983
2984;(function (exports) {
2985 'use strict';
2986
2987 var Arr = (typeof Uint8Array !== 'undefined')
2988 ? Uint8Array
2989 : Array
2990
2991 var PLUS = '+'.charCodeAt(0)
2992 var SLASH = '/'.charCodeAt(0)
2993 var NUMBER = '0'.charCodeAt(0)
2994 var LOWER = 'a'.charCodeAt(0)
2995 var UPPER = 'A'.charCodeAt(0)
2996 var PLUS_URL_SAFE = '-'.charCodeAt(0)
2997 var SLASH_URL_SAFE = '_'.charCodeAt(0)
2998
2999 function decode (elt) {
3000 var code = elt.charCodeAt(0)
3001 if (code === PLUS ||
3002 code === PLUS_URL_SAFE)
3003 return 62 // '+'
3004 if (code === SLASH ||
3005 code === SLASH_URL_SAFE)
3006 return 63 // '/'
3007 if (code < NUMBER)
3008 return -1 //no match
3009 if (code < NUMBER + 10)
3010 return code - NUMBER + 26 + 26
3011 if (code < UPPER + 26)
3012 return code - UPPER
3013 if (code < LOWER + 26)
3014 return code - LOWER + 26
3015 }
3016
3017 function b64ToByteArray (b64) {
3018 var i, j, l, tmp, placeHolders, arr
3019
3020 if (b64.length % 4 > 0) {
3021 throw new Error('Invalid string. Length must be a multiple of 4')
3022 }
3023
3024 // the number of equal signs (place holders)
3025 // if there are two placeholders, than the two characters before it
3026 // represent one byte
3027 // if there is only one, then the three characters before it represent 2 bytes
3028 // this is just a cheap hack to not do indexOf twice
3029 var len = b64.length
3030 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
3031
3032 // base64 is 4/3 + up to two characters of the original data
3033 arr = new Arr(b64.length * 3 / 4 - placeHolders)
3034
3035 // if there are placeholders, only get up to the last complete 4 chars
3036 l = placeHolders > 0 ? b64.length - 4 : b64.length
3037
3038 var L = 0
3039
3040 function push (v) {
3041 arr[L++] = v
3042 }
3043
3044 for (i = 0, j = 0; i < l; i += 4, j += 3) {
3045 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
3046 push((tmp & 0xFF0000) >> 16)
3047 push((tmp & 0xFF00) >> 8)
3048 push(tmp & 0xFF)
3049 }
3050
3051 if (placeHolders === 2) {
3052 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
3053 push(tmp & 0xFF)
3054 } else if (placeHolders === 1) {
3055 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
3056 push((tmp >> 8) & 0xFF)
3057 push(tmp & 0xFF)
3058 }
3059
3060 return arr
3061 }
3062
3063 function uint8ToBase64 (uint8) {
3064 var i,
3065 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
3066 output = "",
3067 temp, length
3068
3069 function encode (num) {
3070 return lookup.charAt(num)
3071 }
3072
3073 function tripletToBase64 (num) {
3074 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
3075 }
3076
3077 // go through the array every three bytes, we'll deal with trailing stuff later
3078 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
3079 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
3080 output += tripletToBase64(temp)
3081 }
3082
3083 // pad the end with zeros, but make sure to not forget the extra bytes
3084 switch (extraBytes) {
3085 case 1:
3086 temp = uint8[uint8.length - 1]
3087 output += encode(temp >> 2)
3088 output += encode((temp << 4) & 0x3F)
3089 output += '=='
3090 break
3091 case 2:
3092 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
3093 output += encode(temp >> 10)
3094 output += encode((temp >> 4) & 0x3F)
3095 output += encode((temp << 2) & 0x3F)
3096 output += '='
3097 break
3098 }
3099
3100 return output
3101 }
3102
3103 exports.toByteArray = b64ToByteArray
3104 exports.fromByteArray = uint8ToBase64
3105}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
3106
3107},{}],18:[function(require,module,exports){
3108exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3109 var e, m,
3110 eLen = nBytes * 8 - mLen - 1,
3111 eMax = (1 << eLen) - 1,
3112 eBias = eMax >> 1,
3113 nBits = -7,
3114 i = isLE ? (nBytes - 1) : 0,
3115 d = isLE ? -1 : 1,
3116 s = buffer[offset + i]
3117
3118 i += d
3119
3120 e = s & ((1 << (-nBits)) - 1)
3121 s >>= (-nBits)
3122 nBits += eLen
3123 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3124
3125 m = e & ((1 << (-nBits)) - 1)
3126 e >>= (-nBits)
3127 nBits += mLen
3128 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3129
3130 if (e === 0) {
3131 e = 1 - eBias
3132 } else if (e === eMax) {
3133 return m ? NaN : ((s ? -1 : 1) * Infinity)
3134 } else {
3135 m = m + Math.pow(2, mLen)
3136 e = e - eBias
3137 }
3138 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3139}
3140
3141exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3142 var e, m, c,
3143 eLen = nBytes * 8 - mLen - 1,
3144 eMax = (1 << eLen) - 1,
3145 eBias = eMax >> 1,
3146 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
3147 i = isLE ? 0 : (nBytes - 1),
3148 d = isLE ? 1 : -1,
3149 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3150
3151 value = Math.abs(value)
3152
3153 if (isNaN(value) || value === Infinity) {
3154 m = isNaN(value) ? 1 : 0
3155 e = eMax
3156 } else {
3157 e = Math.floor(Math.log(value) / Math.LN2)
3158 if (value * (c = Math.pow(2, -e)) < 1) {
3159 e--
3160 c *= 2
3161 }
3162 if (e + eBias >= 1) {
3163 value += rt / c
3164 } else {
3165 value += rt * Math.pow(2, 1 - eBias)
3166 }
3167 if (value * c >= 2) {
3168 e++
3169 c /= 2
3170 }
3171
3172 if (e + eBias >= eMax) {
3173 m = 0
3174 e = eMax
3175 } else if (e + eBias >= 1) {
3176 m = (value * c - 1) * Math.pow(2, mLen)
3177 e = e + eBias
3178 } else {
3179 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3180 e = 0
3181 }
3182 }
3183
3184 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3185
3186 e = (e << mLen) | m
3187 eLen += mLen
3188 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3189
3190 buffer[offset + i - d] |= s * 128
3191}
3192
3193},{}],19:[function(require,module,exports){
3194
3195/**
3196 * isArray
3197 */
3198
3199var isArray = Array.isArray;
3200
3201/**
3202 * toString
3203 */
3204
3205var str = Object.prototype.toString;
3206
3207/**
3208 * Whether or not the given `val`
3209 * is an array.
3210 *
3211 * example:
3212 *
3213 * isArray([]);
3214 * // > true
3215 * isArray(arguments);
3216 * // > false
3217 * isArray('');
3218 * // > false
3219 *
3220 * @param {mixed} val
3221 * @return {bool}
3222 */
3223
3224module.exports = isArray || function (val) {
3225 return !! val && '[object Array]' == str.call(val);
3226};
3227
3228},{}],20:[function(require,module,exports){
3229// Copyright Joyent, Inc. and other Node contributors.
3230//
3231// Permission is hereby granted, free of charge, to any person obtaining a
3232// copy of this software and associated documentation files (the
3233// "Software"), to deal in the Software without restriction, including
3234// without limitation the rights to use, copy, modify, merge, publish,
3235// distribute, sublicense, and/or sell copies of the Software, and to permit
3236// persons to whom the Software is furnished to do so, subject to the
3237// following conditions:
3238//
3239// The above copyright notice and this permission notice shall be included
3240// in all copies or substantial portions of the Software.
3241//
3242// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3243// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3244// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3245// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3246// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3247// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3248// USE OR OTHER DEALINGS IN THE SOFTWARE.
3249
3250function EventEmitter() {
3251 this._events = this._events || {};
3252 this._maxListeners = this._maxListeners || undefined;
3253}
3254module.exports = EventEmitter;
3255
3256// Backwards-compat with node 0.10.x
3257EventEmitter.EventEmitter = EventEmitter;
3258
3259EventEmitter.prototype._events = undefined;
3260EventEmitter.prototype._maxListeners = undefined;
3261
3262// By default EventEmitters will print a warning if more than 10 listeners are
3263// added to it. This is a useful default which helps finding memory leaks.
3264EventEmitter.defaultMaxListeners = 10;
3265
3266// Obviously not all Emitters should be limited to 10. This function allows
3267// that to be increased. Set to zero for unlimited.
3268EventEmitter.prototype.setMaxListeners = function(n) {
3269 if (!isNumber(n) || n < 0 || isNaN(n))
3270 throw TypeError('n must be a positive number');
3271 this._maxListeners = n;
3272 return this;
3273};
3274
3275EventEmitter.prototype.emit = function(type) {
3276 var er, handler, len, args, i, listeners;
3277
3278 if (!this._events)
3279 this._events = {};
3280
3281 // If there is no 'error' event listener then throw.
3282 if (type === 'error') {
3283 if (!this._events.error ||
3284 (isObject(this._events.error) && !this._events.error.length)) {
3285 er = arguments[1];
3286 if (er instanceof Error) {
3287 throw er; // Unhandled 'error' event
3288 }
3289 throw TypeError('Uncaught, unspecified "error" event.');
3290 }
3291 }
3292
3293 handler = this._events[type];
3294
3295 if (isUndefined(handler))
3296 return false;
3297
3298 if (isFunction(handler)) {
3299 switch (arguments.length) {
3300 // fast cases
3301 case 1:
3302 handler.call(this);
3303 break;
3304 case 2:
3305 handler.call(this, arguments[1]);
3306 break;
3307 case 3:
3308 handler.call(this, arguments[1], arguments[2]);
3309 break;
3310 // slower
3311 default:
3312 len = arguments.length;
3313 args = new Array(len - 1);
3314 for (i = 1; i < len; i++)
3315 args[i - 1] = arguments[i];
3316 handler.apply(this, args);
3317 }
3318 } else if (isObject(handler)) {
3319 len = arguments.length;
3320 args = new Array(len - 1);
3321 for (i = 1; i < len; i++)
3322 args[i - 1] = arguments[i];
3323
3324 listeners = handler.slice();
3325 len = listeners.length;
3326 for (i = 0; i < len; i++)
3327 listeners[i].apply(this, args);
3328 }
3329
3330 return true;
3331};
3332
3333EventEmitter.prototype.addListener = function(type, listener) {
3334 var m;
3335
3336 if (!isFunction(listener))
3337 throw TypeError('listener must be a function');
3338
3339 if (!this._events)
3340 this._events = {};
3341
3342 // To avoid recursion in the case that type === "newListener"! Before
3343 // adding it to the listeners, first emit "newListener".
3344 if (this._events.newListener)
3345 this.emit('newListener', type,
3346 isFunction(listener.listener) ?
3347 listener.listener : listener);
3348
3349 if (!this._events[type])
3350 // Optimize the case of one listener. Don't need the extra array object.
3351 this._events[type] = listener;
3352 else if (isObject(this._events[type]))
3353 // If we've already got an array, just append.
3354 this._events[type].push(listener);
3355 else
3356 // Adding the second element, need to change to array.
3357 this._events[type] = [this._events[type], listener];
3358
3359 // Check for listener leak
3360 if (isObject(this._events[type]) && !this._events[type].warned) {
3361 var m;
3362 if (!isUndefined(this._maxListeners)) {
3363 m = this._maxListeners;
3364 } else {
3365 m = EventEmitter.defaultMaxListeners;
3366 }
3367
3368 if (m && m > 0 && this._events[type].length > m) {
3369 this._events[type].warned = true;
3370 console.error('(node) warning: possible EventEmitter memory ' +
3371 'leak detected. %d listeners added. ' +
3372 'Use emitter.setMaxListeners() to increase limit.',
3373 this._events[type].length);
3374 if (typeof console.trace === 'function') {
3375 // not supported in IE 10
3376 console.trace();
3377 }
3378 }
3379 }
3380
3381 return this;
3382};
3383
3384EventEmitter.prototype.on = EventEmitter.prototype.addListener;
3385
3386EventEmitter.prototype.once = function(type, listener) {
3387 if (!isFunction(listener))
3388 throw TypeError('listener must be a function');
3389
3390 var fired = false;
3391
3392 function g() {
3393 this.removeListener(type, g);
3394
3395 if (!fired) {
3396 fired = true;
3397 listener.apply(this, arguments);
3398 }
3399 }
3400
3401 g.listener = listener;
3402 this.on(type, g);
3403
3404 return this;
3405};
3406
3407// emits a 'removeListener' event iff the listener was removed
3408EventEmitter.prototype.removeListener = function(type, listener) {
3409 var list, position, length, i;
3410
3411 if (!isFunction(listener))
3412 throw TypeError('listener must be a function');
3413
3414 if (!this._events || !this._events[type])
3415 return this;
3416
3417 list = this._events[type];
3418 length = list.length;
3419 position = -1;
3420
3421 if (list === listener ||
3422 (isFunction(list.listener) && list.listener === listener)) {
3423 delete this._events[type];
3424 if (this._events.removeListener)
3425 this.emit('removeListener', type, listener);
3426
3427 } else if (isObject(list)) {
3428 for (i = length; i-- > 0;) {
3429 if (list[i] === listener ||
3430 (list[i].listener && list[i].listener === listener)) {
3431 position = i;
3432 break;
3433 }
3434 }
3435
3436 if (position < 0)
3437 return this;
3438
3439 if (list.length === 1) {
3440 list.length = 0;
3441 delete this._events[type];
3442 } else {
3443 list.splice(position, 1);
3444 }
3445
3446 if (this._events.removeListener)
3447 this.emit('removeListener', type, listener);
3448 }
3449
3450 return this;
3451};
3452
3453EventEmitter.prototype.removeAllListeners = function(type) {
3454 var key, listeners;
3455
3456 if (!this._events)
3457 return this;
3458
3459 // not listening for removeListener, no need to emit
3460 if (!this._events.removeListener) {
3461 if (arguments.length === 0)
3462 this._events = {};
3463 else if (this._events[type])
3464 delete this._events[type];
3465 return this;
3466 }
3467
3468 // emit removeListener for all listeners on all events
3469 if (arguments.length === 0) {
3470 for (key in this._events) {
3471 if (key === 'removeListener') continue;
3472 this.removeAllListeners(key);
3473 }
3474 this.removeAllListeners('removeListener');
3475 this._events = {};
3476 return this;
3477 }
3478
3479 listeners = this._events[type];
3480
3481 if (isFunction(listeners)) {
3482 this.removeListener(type, listeners);
3483 } else {
3484 // LIFO order
3485 while (listeners.length)
3486 this.removeListener(type, listeners[listeners.length - 1]);
3487 }
3488 delete this._events[type];
3489
3490 return this;
3491};
3492
3493EventEmitter.prototype.listeners = function(type) {
3494 var ret;
3495 if (!this._events || !this._events[type])
3496 ret = [];
3497 else if (isFunction(this._events[type]))
3498 ret = [this._events[type]];
3499 else
3500 ret = this._events[type].slice();
3501 return ret;
3502};
3503
3504EventEmitter.listenerCount = function(emitter, type) {
3505 var ret;
3506 if (!emitter._events || !emitter._events[type])
3507 ret = 0;
3508 else if (isFunction(emitter._events[type]))
3509 ret = 1;
3510 else
3511 ret = emitter._events[type].length;
3512 return ret;
3513};
3514
3515function isFunction(arg) {
3516 return typeof arg === 'function';
3517}
3518
3519function isNumber(arg) {
3520 return typeof arg === 'number';
3521}
3522
3523function isObject(arg) {
3524 return typeof arg === 'object' && arg !== null;
3525}
3526
3527function isUndefined(arg) {
3528 return arg === void 0;
3529}
3530
3531},{}],21:[function(require,module,exports){
3532arguments[4][10][0].apply(exports,arguments)
3533},{"dup":10}],22:[function(require,module,exports){
3534module.exports = Array.isArray || function (arr) {
3535 return Object.prototype.toString.call(arr) == '[object Array]';
3536};
3537
3538},{}],23:[function(require,module,exports){
3539(function (process){
3540// Copyright Joyent, Inc. and other Node contributors.
3541//
3542// Permission is hereby granted, free of charge, to any person obtaining a
3543// copy of this software and associated documentation files (the
3544// "Software"), to deal in the Software without restriction, including
3545// without limitation the rights to use, copy, modify, merge, publish,
3546// distribute, sublicense, and/or sell copies of the Software, and to permit
3547// persons to whom the Software is furnished to do so, subject to the
3548// following conditions:
3549//
3550// The above copyright notice and this permission notice shall be included
3551// in all copies or substantial portions of the Software.
3552//
3553// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3554// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3555// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3556// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3557// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3558// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3559// USE OR OTHER DEALINGS IN THE SOFTWARE.
3560
3561// resolves . and .. elements in a path array with directory names there
3562// must be no slashes, empty elements, or device names (c:\) in the array
3563// (so also no leading and trailing slashes - it does not distinguish
3564// relative and absolute paths)
3565function normalizeArray(parts, allowAboveRoot) {
3566 // if the path tries to go above the root, `up` ends up > 0
3567 var up = 0;
3568 for (var i = parts.length - 1; i >= 0; i--) {
3569 var last = parts[i];
3570 if (last === '.') {
3571 parts.splice(i, 1);
3572 } else if (last === '..') {
3573 parts.splice(i, 1);
3574 up++;
3575 } else if (up) {
3576 parts.splice(i, 1);
3577 up--;
3578 }
3579 }
3580
3581 // if the path is allowed to go above the root, restore leading ..s
3582 if (allowAboveRoot) {
3583 for (; up--; up) {
3584 parts.unshift('..');
3585 }
3586 }
3587
3588 return parts;
3589}
3590
3591// Split a filename into [root, dir, basename, ext], unix version
3592// 'root' is just a slash, or nothing.
3593var splitPathRe =
3594 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3595var splitPath = function(filename) {
3596 return splitPathRe.exec(filename).slice(1);
3597};
3598
3599// path.resolve([from ...], to)
3600// posix version
3601exports.resolve = function() {
3602 var resolvedPath = '',
3603 resolvedAbsolute = false;
3604
3605 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3606 var path = (i >= 0) ? arguments[i] : process.cwd();
3607
3608 // Skip empty and invalid entries
3609 if (typeof path !== 'string') {
3610 throw new TypeError('Arguments to path.resolve must be strings');
3611 } else if (!path) {
3612 continue;
3613 }
3614
3615 resolvedPath = path + '/' + resolvedPath;
3616 resolvedAbsolute = path.charAt(0) === '/';
3617 }
3618
3619 // At this point the path should be resolved to a full absolute path, but
3620 // handle relative paths to be safe (might happen when process.cwd() fails)
3621
3622 // Normalize the path
3623 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3624 return !!p;
3625 }), !resolvedAbsolute).join('/');
3626
3627 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3628};
3629
3630// path.normalize(path)
3631// posix version
3632exports.normalize = function(path) {
3633 var isAbsolute = exports.isAbsolute(path),
3634 trailingSlash = substr(path, -1) === '/';
3635
3636 // Normalize the path
3637 path = normalizeArray(filter(path.split('/'), function(p) {
3638 return !!p;
3639 }), !isAbsolute).join('/');
3640
3641 if (!path && !isAbsolute) {
3642 path = '.';
3643 }
3644 if (path && trailingSlash) {
3645 path += '/';
3646 }
3647
3648 return (isAbsolute ? '/' : '') + path;
3649};
3650
3651// posix version
3652exports.isAbsolute = function(path) {
3653 return path.charAt(0) === '/';
3654};
3655
3656// posix version
3657exports.join = function() {
3658 var paths = Array.prototype.slice.call(arguments, 0);
3659 return exports.normalize(filter(paths, function(p, index) {
3660 if (typeof p !== 'string') {
3661 throw new TypeError('Arguments to path.join must be strings');
3662 }
3663 return p;
3664 }).join('/'));
3665};
3666
3667
3668// path.relative(from, to)
3669// posix version
3670exports.relative = function(from, to) {
3671 from = exports.resolve(from).substr(1);
3672 to = exports.resolve(to).substr(1);
3673
3674 function trim(arr) {
3675 var start = 0;
3676 for (; start < arr.length; start++) {
3677 if (arr[start] !== '') break;
3678 }
3679
3680 var end = arr.length - 1;
3681 for (; end >= 0; end--) {
3682 if (arr[end] !== '') break;
3683 }
3684
3685 if (start > end) return [];
3686 return arr.slice(start, end - start + 1);
3687 }
3688
3689 var fromParts = trim(from.split('/'));
3690 var toParts = trim(to.split('/'));
3691
3692 var length = Math.min(fromParts.length, toParts.length);
3693 var samePartsLength = length;
3694 for (var i = 0; i < length; i++) {
3695 if (fromParts[i] !== toParts[i]) {
3696 samePartsLength = i;
3697 break;
3698 }
3699 }
3700
3701 var outputParts = [];
3702 for (var i = samePartsLength; i < fromParts.length; i++) {
3703 outputParts.push('..');
3704 }
3705
3706 outputParts = outputParts.concat(toParts.slice(samePartsLength));
3707
3708 return outputParts.join('/');
3709};
3710
3711exports.sep = '/';
3712exports.delimiter = ':';
3713
3714exports.dirname = function(path) {
3715 var result = splitPath(path),
3716 root = result[0],
3717 dir = result[1];
3718
3719 if (!root && !dir) {
3720 // No dirname whatsoever
3721 return '.';
3722 }
3723
3724 if (dir) {
3725 // It has a dirname, strip trailing slash
3726 dir = dir.substr(0, dir.length - 1);
3727 }
3728
3729 return root + dir;
3730};
3731
3732
3733exports.basename = function(path, ext) {
3734 var f = splitPath(path)[2];
3735 // TODO: make this comparison case-insensitive on windows?
3736 if (ext && f.substr(-1 * ext.length) === ext) {
3737 f = f.substr(0, f.length - ext.length);
3738 }
3739 return f;
3740};
3741
3742
3743exports.extname = function(path) {
3744 return splitPath(path)[3];
3745};
3746
3747function filter (xs, f) {
3748 if (xs.filter) return xs.filter(f);
3749 var res = [];
3750 for (var i = 0; i < xs.length; i++) {
3751 if (f(xs[i], i, xs)) res.push(xs[i]);
3752 }
3753 return res;
3754}
3755
3756// String.prototype.substr - negative index don't work in IE8
3757var substr = 'ab'.substr(-1) === 'b'
3758 ? function (str, start, len) { return str.substr(start, len) }
3759 : function (str, start, len) {
3760 if (start < 0) start = str.length + start;
3761 return str.substr(start, len);
3762 }
3763;
3764
3765}).call(this,require('_process'))
3766},{"_process":24}],24:[function(require,module,exports){
3767// shim for using process in browser
3768
3769var process = module.exports = {};
3770var queue = [];
3771var draining = false;
3772var currentQueue;
3773var queueIndex = -1;
3774
3775function cleanUpNextTick() {
3776 draining = false;
3777 if (currentQueue.length) {
3778 queue = currentQueue.concat(queue);
3779 } else {
3780 queueIndex = -1;
3781 }
3782 if (queue.length) {
3783 drainQueue();
3784 }
3785}
3786
3787function drainQueue() {
3788 if (draining) {
3789 return;
3790 }
3791 var timeout = setTimeout(cleanUpNextTick);
3792 draining = true;
3793
3794 var len = queue.length;
3795 while(len) {
3796 currentQueue = queue;
3797 queue = [];
3798 while (++queueIndex < len) {
3799 currentQueue[queueIndex].run();
3800 }
3801 queueIndex = -1;
3802 len = queue.length;
3803 }
3804 currentQueue = null;
3805 draining = false;
3806 clearTimeout(timeout);
3807}
3808
3809process.nextTick = function (fun) {
3810 var args = new Array(arguments.length - 1);
3811 if (arguments.length > 1) {
3812 for (var i = 1; i < arguments.length; i++) {
3813 args[i - 1] = arguments[i];
3814 }
3815 }
3816 queue.push(new Item(fun, args));
3817 if (queue.length === 1 && !draining) {
3818 setTimeout(drainQueue, 0);
3819 }
3820};
3821
3822// v8 likes predictible objects
3823function Item(fun, array) {
3824 this.fun = fun;
3825 this.array = array;
3826}
3827Item.prototype.run = function () {
3828 this.fun.apply(null, this.array);
3829};
3830process.title = 'browser';
3831process.browser = true;
3832process.env = {};
3833process.argv = [];
3834process.version = ''; // empty string to avoid regexp issues
3835process.versions = {};
3836
3837function noop() {}
3838
3839process.on = noop;
3840process.addListener = noop;
3841process.once = noop;
3842process.off = noop;
3843process.removeListener = noop;
3844process.removeAllListeners = noop;
3845process.emit = noop;
3846
3847process.binding = function (name) {
3848 throw new Error('process.binding is not supported');
3849};
3850
3851// TODO(shtylman)
3852process.cwd = function () { return '/' };
3853process.chdir = function (dir) {
3854 throw new Error('process.chdir is not supported');
3855};
3856process.umask = function() { return 0; };
3857
3858},{}],25:[function(require,module,exports){
3859module.exports = require("./lib/_stream_duplex.js")
3860
3861},{"./lib/_stream_duplex.js":26}],26:[function(require,module,exports){
3862(function (process){
3863// Copyright Joyent, Inc. and other Node contributors.
3864//
3865// Permission is hereby granted, free of charge, to any person obtaining a
3866// copy of this software and associated documentation files (the
3867// "Software"), to deal in the Software without restriction, including
3868// without limitation the rights to use, copy, modify, merge, publish,
3869// distribute, sublicense, and/or sell copies of the Software, and to permit
3870// persons to whom the Software is furnished to do so, subject to the
3871// following conditions:
3872//
3873// The above copyright notice and this permission notice shall be included
3874// in all copies or substantial portions of the Software.
3875//
3876// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3877// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3878// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3879// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3880// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3881// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3882// USE OR OTHER DEALINGS IN THE SOFTWARE.
3883
3884// a duplex stream is just a stream that is both readable and writable.
3885// Since JS doesn't have multiple prototypal inheritance, this class
3886// prototypally inherits from Readable, and then parasitically from
3887// Writable.
3888
3889module.exports = Duplex;
3890
3891/*<replacement>*/
3892var objectKeys = Object.keys || function (obj) {
3893 var keys = [];
3894 for (var key in obj) keys.push(key);
3895 return keys;
3896}
3897/*</replacement>*/
3898
3899
3900/*<replacement>*/
3901var util = require('core-util-is');
3902util.inherits = require('inherits');
3903/*</replacement>*/
3904
3905var Readable = require('./_stream_readable');
3906var Writable = require('./_stream_writable');
3907
3908util.inherits(Duplex, Readable);
3909
3910forEach(objectKeys(Writable.prototype), function(method) {
3911 if (!Duplex.prototype[method])
3912 Duplex.prototype[method] = Writable.prototype[method];
3913});
3914
3915function Duplex(options) {
3916 if (!(this instanceof Duplex))
3917 return new Duplex(options);
3918
3919 Readable.call(this, options);
3920 Writable.call(this, options);
3921
3922 if (options && options.readable === false)
3923 this.readable = false;
3924
3925 if (options && options.writable === false)
3926 this.writable = false;
3927
3928 this.allowHalfOpen = true;
3929 if (options && options.allowHalfOpen === false)
3930 this.allowHalfOpen = false;
3931
3932 this.once('end', onend);
3933}
3934
3935// the no-half-open enforcer
3936function onend() {
3937 // if we allow half-open state, or if the writable side ended,
3938 // then we're ok.
3939 if (this.allowHalfOpen || this._writableState.ended)
3940 return;
3941
3942 // no more data can be written.
3943 // But allow more writes to happen in this tick.
3944 process.nextTick(this.end.bind(this));
3945}
3946
3947function forEach (xs, f) {
3948 for (var i = 0, l = xs.length; i < l; i++) {
3949 f(xs[i], i);
3950 }
3951}
3952
3953}).call(this,require('_process'))
3954},{"./_stream_readable":28,"./_stream_writable":30,"_process":24,"core-util-is":31,"inherits":21}],27:[function(require,module,exports){
3955// Copyright Joyent, Inc. and other Node contributors.
3956//
3957// Permission is hereby granted, free of charge, to any person obtaining a
3958// copy of this software and associated documentation files (the
3959// "Software"), to deal in the Software without restriction, including
3960// without limitation the rights to use, copy, modify, merge, publish,
3961// distribute, sublicense, and/or sell copies of the Software, and to permit
3962// persons to whom the Software is furnished to do so, subject to the
3963// following conditions:
3964//
3965// The above copyright notice and this permission notice shall be included
3966// in all copies or substantial portions of the Software.
3967//
3968// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3969// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3970// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3971// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3972// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3973// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3974// USE OR OTHER DEALINGS IN THE SOFTWARE.
3975
3976// a passthrough stream.
3977// basically just the most minimal sort of Transform stream.
3978// Every written chunk gets output as-is.
3979
3980module.exports = PassThrough;
3981
3982var Transform = require('./_stream_transform');
3983
3984/*<replacement>*/
3985var util = require('core-util-is');
3986util.inherits = require('inherits');
3987/*</replacement>*/
3988
3989util.inherits(PassThrough, Transform);
3990
3991function PassThrough(options) {
3992 if (!(this instanceof PassThrough))
3993 return new PassThrough(options);
3994
3995 Transform.call(this, options);
3996}
3997
3998PassThrough.prototype._transform = function(chunk, encoding, cb) {
3999 cb(null, chunk);
4000};
4001
4002},{"./_stream_transform":29,"core-util-is":31,"inherits":21}],28:[function(require,module,exports){
4003(function (process){
4004// Copyright Joyent, Inc. and other Node contributors.
4005//
4006// Permission is hereby granted, free of charge, to any person obtaining a
4007// copy of this software and associated documentation files (the
4008// "Software"), to deal in the Software without restriction, including
4009// without limitation the rights to use, copy, modify, merge, publish,
4010// distribute, sublicense, and/or sell copies of the Software, and to permit
4011// persons to whom the Software is furnished to do so, subject to the
4012// following conditions:
4013//
4014// The above copyright notice and this permission notice shall be included
4015// in all copies or substantial portions of the Software.
4016//
4017// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4018// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4019// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4020// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4021// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4022// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4023// USE OR OTHER DEALINGS IN THE SOFTWARE.
4024
4025module.exports = Readable;
4026
4027/*<replacement>*/
4028var isArray = require('isarray');
4029/*</replacement>*/
4030
4031
4032/*<replacement>*/
4033var Buffer = require('buffer').Buffer;
4034/*</replacement>*/
4035
4036Readable.ReadableState = ReadableState;
4037
4038var EE = require('events').EventEmitter;
4039
4040/*<replacement>*/
4041if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
4042 return emitter.listeners(type).length;
4043};
4044/*</replacement>*/
4045
4046var Stream = require('stream');
4047
4048/*<replacement>*/
4049var util = require('core-util-is');
4050util.inherits = require('inherits');
4051/*</replacement>*/
4052
4053var StringDecoder;
4054
4055
4056/*<replacement>*/
4057var debug = require('util');
4058if (debug && debug.debuglog) {
4059 debug = debug.debuglog('stream');
4060} else {
4061 debug = function () {};
4062}
4063/*</replacement>*/
4064
4065
4066util.inherits(Readable, Stream);
4067
4068function ReadableState(options, stream) {
4069 var Duplex = require('./_stream_duplex');
4070
4071 options = options || {};
4072
4073 // the point at which it stops calling _read() to fill the buffer
4074 // Note: 0 is a valid value, means "don't call _read preemptively ever"
4075 var hwm = options.highWaterMark;
4076 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
4077 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
4078
4079 // cast to ints.
4080 this.highWaterMark = ~~this.highWaterMark;
4081
4082 this.buffer = [];
4083 this.length = 0;
4084 this.pipes = null;
4085 this.pipesCount = 0;
4086 this.flowing = null;
4087 this.ended = false;
4088 this.endEmitted = false;
4089 this.reading = false;
4090
4091 // a flag to be able to tell if the onwrite cb is called immediately,
4092 // or on a later tick. We set this to true at first, because any
4093 // actions that shouldn't happen until "later" should generally also
4094 // not happen before the first write call.
4095 this.sync = true;
4096
4097 // whenever we return null, then we set a flag to say
4098 // that we're awaiting a 'readable' event emission.
4099 this.needReadable = false;
4100 this.emittedReadable = false;
4101 this.readableListening = false;
4102
4103
4104 // object stream flag. Used to make read(n) ignore n and to
4105 // make all the buffer merging and length checks go away
4106 this.objectMode = !!options.objectMode;
4107
4108 if (stream instanceof Duplex)
4109 this.objectMode = this.objectMode || !!options.readableObjectMode;
4110
4111 // Crypto is kind of old and crusty. Historically, its default string
4112 // encoding is 'binary' so we have to make this configurable.
4113 // Everything else in the universe uses 'utf8', though.
4114 this.defaultEncoding = options.defaultEncoding || 'utf8';
4115
4116 // when piping, we only care about 'readable' events that happen
4117 // after read()ing all the bytes and not getting any pushback.
4118 this.ranOut = false;
4119
4120 // the number of writers that are awaiting a drain event in .pipe()s
4121 this.awaitDrain = 0;
4122
4123 // if true, a maybeReadMore has been scheduled
4124 this.readingMore = false;
4125
4126 this.decoder = null;
4127 this.encoding = null;
4128 if (options.encoding) {
4129 if (!StringDecoder)
4130 StringDecoder = require('string_decoder/').StringDecoder;
4131 this.decoder = new StringDecoder(options.encoding);
4132 this.encoding = options.encoding;
4133 }
4134}
4135
4136function Readable(options) {
4137 var Duplex = require('./_stream_duplex');
4138
4139 if (!(this instanceof Readable))
4140 return new Readable(options);
4141
4142 this._readableState = new ReadableState(options, this);
4143
4144 // legacy
4145 this.readable = true;
4146
4147 Stream.call(this);
4148}
4149
4150// Manually shove something into the read() buffer.
4151// This returns true if the highWaterMark has not been hit yet,
4152// similar to how Writable.write() returns true if you should
4153// write() some more.
4154Readable.prototype.push = function(chunk, encoding) {
4155 var state = this._readableState;
4156
4157 if (util.isString(chunk) && !state.objectMode) {
4158 encoding = encoding || state.defaultEncoding;
4159 if (encoding !== state.encoding) {
4160 chunk = new Buffer(chunk, encoding);
4161 encoding = '';
4162 }
4163 }
4164
4165 return readableAddChunk(this, state, chunk, encoding, false);
4166};
4167
4168// Unshift should *always* be something directly out of read()
4169Readable.prototype.unshift = function(chunk) {
4170 var state = this._readableState;
4171 return readableAddChunk(this, state, chunk, '', true);
4172};
4173
4174function readableAddChunk(stream, state, chunk, encoding, addToFront) {
4175 var er = chunkInvalid(state, chunk);
4176 if (er) {
4177 stream.emit('error', er);
4178 } else if (util.isNullOrUndefined(chunk)) {
4179 state.reading = false;
4180 if (!state.ended)
4181 onEofChunk(stream, state);
4182 } else if (state.objectMode || chunk && chunk.length > 0) {
4183 if (state.ended && !addToFront) {
4184 var e = new Error('stream.push() after EOF');
4185 stream.emit('error', e);
4186 } else if (state.endEmitted && addToFront) {
4187 var e = new Error('stream.unshift() after end event');
4188 stream.emit('error', e);
4189 } else {
4190 if (state.decoder && !addToFront && !encoding)
4191 chunk = state.decoder.write(chunk);
4192
4193 if (!addToFront)
4194 state.reading = false;
4195
4196 // if we want the data now, just emit it.
4197 if (state.flowing && state.length === 0 && !state.sync) {
4198 stream.emit('data', chunk);
4199 stream.read(0);
4200 } else {
4201 // update the buffer info.
4202 state.length += state.objectMode ? 1 : chunk.length;
4203 if (addToFront)
4204 state.buffer.unshift(chunk);
4205 else
4206 state.buffer.push(chunk);
4207
4208 if (state.needReadable)
4209 emitReadable(stream);
4210 }
4211
4212 maybeReadMore(stream, state);
4213 }
4214 } else if (!addToFront) {
4215 state.reading = false;
4216 }
4217
4218 return needMoreData(state);
4219}
4220
4221
4222
4223// if it's past the high water mark, we can push in some more.
4224// Also, if we have no data yet, we can stand some
4225// more bytes. This is to work around cases where hwm=0,
4226// such as the repl. Also, if the push() triggered a
4227// readable event, and the user called read(largeNumber) such that
4228// needReadable was set, then we ought to push more, so that another
4229// 'readable' event will be triggered.
4230function needMoreData(state) {
4231 return !state.ended &&
4232 (state.needReadable ||
4233 state.length < state.highWaterMark ||
4234 state.length === 0);
4235}
4236
4237// backwards compatibility.
4238Readable.prototype.setEncoding = function(enc) {
4239 if (!StringDecoder)
4240 StringDecoder = require('string_decoder/').StringDecoder;
4241 this._readableState.decoder = new StringDecoder(enc);
4242 this._readableState.encoding = enc;
4243 return this;
4244};
4245
4246// Don't raise the hwm > 128MB
4247var MAX_HWM = 0x800000;
4248function roundUpToNextPowerOf2(n) {
4249 if (n >= MAX_HWM) {
4250 n = MAX_HWM;
4251 } else {
4252 // Get the next highest power of 2
4253 n--;
4254 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
4255 n++;
4256 }
4257 return n;
4258}
4259
4260function howMuchToRead(n, state) {
4261 if (state.length === 0 && state.ended)
4262 return 0;
4263
4264 if (state.objectMode)
4265 return n === 0 ? 0 : 1;
4266
4267 if (isNaN(n) || util.isNull(n)) {
4268 // only flow one buffer at a time
4269 if (state.flowing && state.buffer.length)
4270 return state.buffer[0].length;
4271 else
4272 return state.length;
4273 }
4274
4275 if (n <= 0)
4276 return 0;
4277
4278 // If we're asking for more than the target buffer level,
4279 // then raise the water mark. Bump up to the next highest
4280 // power of 2, to prevent increasing it excessively in tiny
4281 // amounts.
4282 if (n > state.highWaterMark)
4283 state.highWaterMark = roundUpToNextPowerOf2(n);
4284
4285 // don't have that much. return null, unless we've ended.
4286 if (n > state.length) {
4287 if (!state.ended) {
4288 state.needReadable = true;
4289 return 0;
4290 } else
4291 return state.length;
4292 }
4293
4294 return n;
4295}
4296
4297// you can override either this method, or the async _read(n) below.
4298Readable.prototype.read = function(n) {
4299 debug('read', n);
4300 var state = this._readableState;
4301 var nOrig = n;
4302
4303 if (!util.isNumber(n) || n > 0)
4304 state.emittedReadable = false;
4305
4306 // if we're doing read(0) to trigger a readable event, but we
4307 // already have a bunch of data in the buffer, then just trigger
4308 // the 'readable' event and move on.
4309 if (n === 0 &&
4310 state.needReadable &&
4311 (state.length >= state.highWaterMark || state.ended)) {
4312 debug('read: emitReadable', state.length, state.ended);
4313 if (state.length === 0 && state.ended)
4314 endReadable(this);
4315 else
4316 emitReadable(this);
4317 return null;
4318 }
4319
4320 n = howMuchToRead(n, state);
4321
4322 // if we've ended, and we're now clear, then finish it up.
4323 if (n === 0 && state.ended) {
4324 if (state.length === 0)
4325 endReadable(this);
4326 return null;
4327 }
4328
4329 // All the actual chunk generation logic needs to be
4330 // *below* the call to _read. The reason is that in certain
4331 // synthetic stream cases, such as passthrough streams, _read
4332 // may be a completely synchronous operation which may change
4333 // the state of the read buffer, providing enough data when
4334 // before there was *not* enough.
4335 //
4336 // So, the steps are:
4337 // 1. Figure out what the state of things will be after we do
4338 // a read from the buffer.
4339 //
4340 // 2. If that resulting state will trigger a _read, then call _read.
4341 // Note that this may be asynchronous, or synchronous. Yes, it is
4342 // deeply ugly to write APIs this way, but that still doesn't mean
4343 // that the Readable class should behave improperly, as streams are
4344 // designed to be sync/async agnostic.
4345 // Take note if the _read call is sync or async (ie, if the read call
4346 // has returned yet), so that we know whether or not it's safe to emit
4347 // 'readable' etc.
4348 //
4349 // 3. Actually pull the requested chunks out of the buffer and return.
4350
4351 // if we need a readable event, then we need to do some reading.
4352 var doRead = state.needReadable;
4353 debug('need readable', doRead);
4354
4355 // if we currently have less than the highWaterMark, then also read some
4356 if (state.length === 0 || state.length - n < state.highWaterMark) {
4357 doRead = true;
4358 debug('length less than watermark', doRead);
4359 }
4360
4361 // however, if we've ended, then there's no point, and if we're already
4362 // reading, then it's unnecessary.
4363 if (state.ended || state.reading) {
4364 doRead = false;
4365 debug('reading or ended', doRead);
4366 }
4367
4368 if (doRead) {
4369 debug('do read');
4370 state.reading = true;
4371 state.sync = true;
4372 // if the length is currently zero, then we *need* a readable event.
4373 if (state.length === 0)
4374 state.needReadable = true;
4375 // call internal read method
4376 this._read(state.highWaterMark);
4377 state.sync = false;
4378 }
4379
4380 // If _read pushed data synchronously, then `reading` will be false,
4381 // and we need to re-evaluate how much data we can return to the user.
4382 if (doRead && !state.reading)
4383 n = howMuchToRead(nOrig, state);
4384
4385 var ret;
4386 if (n > 0)
4387 ret = fromList(n, state);
4388 else
4389 ret = null;
4390
4391 if (util.isNull(ret)) {
4392 state.needReadable = true;
4393 n = 0;
4394 }
4395
4396 state.length -= n;
4397
4398 // If we have nothing in the buffer, then we want to know
4399 // as soon as we *do* get something into the buffer.
4400 if (state.length === 0 && !state.ended)
4401 state.needReadable = true;
4402
4403 // If we tried to read() past the EOF, then emit end on the next tick.
4404 if (nOrig !== n && state.ended && state.length === 0)
4405 endReadable(this);
4406
4407 if (!util.isNull(ret))
4408 this.emit('data', ret);
4409
4410 return ret;
4411};
4412
4413function chunkInvalid(state, chunk) {
4414 var er = null;
4415 if (!util.isBuffer(chunk) &&
4416 !util.isString(chunk) &&
4417 !util.isNullOrUndefined(chunk) &&
4418 !state.objectMode) {
4419 er = new TypeError('Invalid non-string/buffer chunk');
4420 }
4421 return er;
4422}
4423
4424
4425function onEofChunk(stream, state) {
4426 if (state.decoder && !state.ended) {
4427 var chunk = state.decoder.end();
4428 if (chunk && chunk.length) {
4429 state.buffer.push(chunk);
4430 state.length += state.objectMode ? 1 : chunk.length;
4431 }
4432 }
4433 state.ended = true;
4434
4435 // emit 'readable' now to make sure it gets picked up.
4436 emitReadable(stream);
4437}
4438
4439// Don't emit readable right away in sync mode, because this can trigger
4440// another read() call => stack overflow. This way, it might trigger
4441// a nextTick recursion warning, but that's not so bad.
4442function emitReadable(stream) {
4443 var state = stream._readableState;
4444 state.needReadable = false;
4445 if (!state.emittedReadable) {
4446 debug('emitReadable', state.flowing);
4447 state.emittedReadable = true;
4448 if (state.sync)
4449 process.nextTick(function() {
4450 emitReadable_(stream);
4451 });
4452 else
4453 emitReadable_(stream);
4454 }
4455}
4456
4457function emitReadable_(stream) {
4458 debug('emit readable');
4459 stream.emit('readable');
4460 flow(stream);
4461}
4462
4463
4464// at this point, the user has presumably seen the 'readable' event,
4465// and called read() to consume some data. that may have triggered
4466// in turn another _read(n) call, in which case reading = true if
4467// it's in progress.
4468// However, if we're not ended, or reading, and the length < hwm,
4469// then go ahead and try to read some more preemptively.
4470function maybeReadMore(stream, state) {
4471 if (!state.readingMore) {
4472 state.readingMore = true;
4473 process.nextTick(function() {
4474 maybeReadMore_(stream, state);
4475 });
4476 }
4477}
4478
4479function maybeReadMore_(stream, state) {
4480 var len = state.length;
4481 while (!state.reading && !state.flowing && !state.ended &&
4482 state.length < state.highWaterMark) {
4483 debug('maybeReadMore read 0');
4484 stream.read(0);
4485 if (len === state.length)
4486 // didn't get any data, stop spinning.
4487 break;
4488 else
4489 len = state.length;
4490 }
4491 state.readingMore = false;
4492}
4493
4494// abstract method. to be overridden in specific implementation classes.
4495// call cb(er, data) where data is <= n in length.
4496// for virtual (non-string, non-buffer) streams, "length" is somewhat
4497// arbitrary, and perhaps not very meaningful.
4498Readable.prototype._read = function(n) {
4499 this.emit('error', new Error('not implemented'));
4500};
4501
4502Readable.prototype.pipe = function(dest, pipeOpts) {
4503 var src = this;
4504 var state = this._readableState;
4505
4506 switch (state.pipesCount) {
4507 case 0:
4508 state.pipes = dest;
4509 break;
4510 case 1:
4511 state.pipes = [state.pipes, dest];
4512 break;
4513 default:
4514 state.pipes.push(dest);
4515 break;
4516 }
4517 state.pipesCount += 1;
4518 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
4519
4520 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
4521 dest !== process.stdout &&
4522 dest !== process.stderr;
4523
4524 var endFn = doEnd ? onend : cleanup;
4525 if (state.endEmitted)
4526 process.nextTick(endFn);
4527 else
4528 src.once('end', endFn);
4529
4530 dest.on('unpipe', onunpipe);
4531 function onunpipe(readable) {
4532 debug('onunpipe');
4533 if (readable === src) {
4534 cleanup();
4535 }
4536 }
4537
4538 function onend() {
4539 debug('onend');
4540 dest.end();
4541 }
4542
4543 // when the dest drains, it reduces the awaitDrain counter
4544 // on the source. This would be more elegant with a .once()
4545 // handler in flow(), but adding and removing repeatedly is
4546 // too slow.
4547 var ondrain = pipeOnDrain(src);
4548 dest.on('drain', ondrain);
4549
4550 function cleanup() {
4551 debug('cleanup');
4552 // cleanup event handlers once the pipe is broken
4553 dest.removeListener('close', onclose);
4554 dest.removeListener('finish', onfinish);
4555 dest.removeListener('drain', ondrain);
4556 dest.removeListener('error', onerror);
4557 dest.removeListener('unpipe', onunpipe);
4558 src.removeListener('end', onend);
4559 src.removeListener('end', cleanup);
4560 src.removeListener('data', ondata);
4561
4562 // if the reader is waiting for a drain event from this
4563 // specific writer, then it would cause it to never start
4564 // flowing again.
4565 // So, if this is awaiting a drain, then we just call it now.
4566 // If we don't know, then assume that we are waiting for one.
4567 if (state.awaitDrain &&
4568 (!dest._writableState || dest._writableState.needDrain))
4569 ondrain();
4570 }
4571
4572 src.on('data', ondata);
4573 function ondata(chunk) {
4574 debug('ondata');
4575 var ret = dest.write(chunk);
4576 if (false === ret) {
4577 debug('false write response, pause',
4578 src._readableState.awaitDrain);
4579 src._readableState.awaitDrain++;
4580 src.pause();
4581 }
4582 }
4583
4584 // if the dest has an error, then stop piping into it.
4585 // however, don't suppress the throwing behavior for this.
4586 function onerror(er) {
4587 debug('onerror', er);
4588 unpipe();
4589 dest.removeListener('error', onerror);
4590 if (EE.listenerCount(dest, 'error') === 0)
4591 dest.emit('error', er);
4592 }
4593 // This is a brutally ugly hack to make sure that our error handler
4594 // is attached before any userland ones. NEVER DO THIS.
4595 if (!dest._events || !dest._events.error)
4596 dest.on('error', onerror);
4597 else if (isArray(dest._events.error))
4598 dest._events.error.unshift(onerror);
4599 else
4600 dest._events.error = [onerror, dest._events.error];
4601
4602
4603
4604 // Both close and finish should trigger unpipe, but only once.
4605 function onclose() {
4606 dest.removeListener('finish', onfinish);
4607 unpipe();
4608 }
4609 dest.once('close', onclose);
4610 function onfinish() {
4611 debug('onfinish');
4612 dest.removeListener('close', onclose);
4613 unpipe();
4614 }
4615 dest.once('finish', onfinish);
4616
4617 function unpipe() {
4618 debug('unpipe');
4619 src.unpipe(dest);
4620 }
4621
4622 // tell the dest that it's being piped to
4623 dest.emit('pipe', src);
4624
4625 // start the flow if it hasn't been started already.
4626 if (!state.flowing) {
4627 debug('pipe resume');
4628 src.resume();
4629 }
4630
4631 return dest;
4632};
4633
4634function pipeOnDrain(src) {
4635 return function() {
4636 var state = src._readableState;
4637 debug('pipeOnDrain', state.awaitDrain);
4638 if (state.awaitDrain)
4639 state.awaitDrain--;
4640 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
4641 state.flowing = true;
4642 flow(src);
4643 }
4644 };
4645}
4646
4647
4648Readable.prototype.unpipe = function(dest) {
4649 var state = this._readableState;
4650
4651 // if we're not piping anywhere, then do nothing.
4652 if (state.pipesCount === 0)
4653 return this;
4654
4655 // just one destination. most common case.
4656 if (state.pipesCount === 1) {
4657 // passed in one, but it's not the right one.
4658 if (dest && dest !== state.pipes)
4659 return this;
4660
4661 if (!dest)
4662 dest = state.pipes;
4663
4664 // got a match.
4665 state.pipes = null;
4666 state.pipesCount = 0;
4667 state.flowing = false;
4668 if (dest)
4669 dest.emit('unpipe', this);
4670 return this;
4671 }
4672
4673 // slow case. multiple pipe destinations.
4674
4675 if (!dest) {
4676 // remove all.
4677 var dests = state.pipes;
4678 var len = state.pipesCount;
4679 state.pipes = null;
4680 state.pipesCount = 0;
4681 state.flowing = false;
4682
4683 for (var i = 0; i < len; i++)
4684 dests[i].emit('unpipe', this);
4685 return this;
4686 }
4687
4688 // try to find the right one.
4689 var i = indexOf(state.pipes, dest);
4690 if (i === -1)
4691 return this;
4692
4693 state.pipes.splice(i, 1);
4694 state.pipesCount -= 1;
4695 if (state.pipesCount === 1)
4696 state.pipes = state.pipes[0];
4697
4698 dest.emit('unpipe', this);
4699
4700 return this;
4701};
4702
4703// set up data events if they are asked for
4704// Ensure readable listeners eventually get something
4705Readable.prototype.on = function(ev, fn) {
4706 var res = Stream.prototype.on.call(this, ev, fn);
4707
4708 // If listening to data, and it has not explicitly been paused,
4709 // then call resume to start the flow of data on the next tick.
4710 if (ev === 'data' && false !== this._readableState.flowing) {
4711 this.resume();
4712 }
4713
4714 if (ev === 'readable' && this.readable) {
4715 var state = this._readableState;
4716 if (!state.readableListening) {
4717 state.readableListening = true;
4718 state.emittedReadable = false;
4719 state.needReadable = true;
4720 if (!state.reading) {
4721 var self = this;
4722 process.nextTick(function() {
4723 debug('readable nexttick read 0');
4724 self.read(0);
4725 });
4726 } else if (state.length) {
4727 emitReadable(this, state);
4728 }
4729 }
4730 }
4731
4732 return res;
4733};
4734Readable.prototype.addListener = Readable.prototype.on;
4735
4736// pause() and resume() are remnants of the legacy readable stream API
4737// If the user uses them, then switch into old mode.
4738Readable.prototype.resume = function() {
4739 var state = this._readableState;
4740 if (!state.flowing) {
4741 debug('resume');
4742 state.flowing = true;
4743 if (!state.reading) {
4744 debug('resume read 0');
4745 this.read(0);
4746 }
4747 resume(this, state);
4748 }
4749 return this;
4750};
4751
4752function resume(stream, state) {
4753 if (!state.resumeScheduled) {
4754 state.resumeScheduled = true;
4755 process.nextTick(function() {
4756 resume_(stream, state);
4757 });
4758 }
4759}
4760
4761function resume_(stream, state) {
4762 state.resumeScheduled = false;
4763 stream.emit('resume');
4764 flow(stream);
4765 if (state.flowing && !state.reading)
4766 stream.read(0);
4767}
4768
4769Readable.prototype.pause = function() {
4770 debug('call pause flowing=%j', this._readableState.flowing);
4771 if (false !== this._readableState.flowing) {
4772 debug('pause');
4773 this._readableState.flowing = false;
4774 this.emit('pause');
4775 }
4776 return this;
4777};
4778
4779function flow(stream) {
4780 var state = stream._readableState;
4781 debug('flow', state.flowing);
4782 if (state.flowing) {
4783 do {
4784 var chunk = stream.read();
4785 } while (null !== chunk && state.flowing);
4786 }
4787}
4788
4789// wrap an old-style stream as the async data source.
4790// This is *not* part of the readable stream interface.
4791// It is an ugly unfortunate mess of history.
4792Readable.prototype.wrap = function(stream) {
4793 var state = this._readableState;
4794 var paused = false;
4795
4796 var self = this;
4797 stream.on('end', function() {
4798 debug('wrapped end');
4799 if (state.decoder && !state.ended) {
4800 var chunk = state.decoder.end();
4801 if (chunk && chunk.length)
4802 self.push(chunk);
4803 }
4804
4805 self.push(null);
4806 });
4807
4808 stream.on('data', function(chunk) {
4809 debug('wrapped data');
4810 if (state.decoder)
4811 chunk = state.decoder.write(chunk);
4812 if (!chunk || !state.objectMode && !chunk.length)
4813 return;
4814
4815 var ret = self.push(chunk);
4816 if (!ret) {
4817 paused = true;
4818 stream.pause();
4819 }
4820 });
4821
4822 // proxy all the other methods.
4823 // important when wrapping filters and duplexes.
4824 for (var i in stream) {
4825 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
4826 this[i] = function(method) { return function() {
4827 return stream[method].apply(stream, arguments);
4828 }}(i);
4829 }
4830 }
4831
4832 // proxy certain important events.
4833 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
4834 forEach(events, function(ev) {
4835 stream.on(ev, self.emit.bind(self, ev));
4836 });
4837
4838 // when we try to consume some more bytes, simply unpause the
4839 // underlying stream.
4840 self._read = function(n) {
4841 debug('wrapped _read', n);
4842 if (paused) {
4843 paused = false;
4844 stream.resume();
4845 }
4846 };
4847
4848 return self;
4849};
4850
4851
4852
4853// exposed for testing purposes only.
4854Readable._fromList = fromList;
4855
4856// Pluck off n bytes from an array of buffers.
4857// Length is the combined lengths of all the buffers in the list.
4858function fromList(n, state) {
4859 var list = state.buffer;
4860 var length = state.length;
4861 var stringMode = !!state.decoder;
4862 var objectMode = !!state.objectMode;
4863 var ret;
4864
4865 // nothing in the list, definitely empty.
4866 if (list.length === 0)
4867 return null;
4868
4869 if (length === 0)
4870 ret = null;
4871 else if (objectMode)
4872 ret = list.shift();
4873 else if (!n || n >= length) {
4874 // read it all, truncate the array.
4875 if (stringMode)
4876 ret = list.join('');
4877 else
4878 ret = Buffer.concat(list, length);
4879 list.length = 0;
4880 } else {
4881 // read just some of it.
4882 if (n < list[0].length) {
4883 // just take a part of the first list item.
4884 // slice is the same for buffers and strings.
4885 var buf = list[0];
4886 ret = buf.slice(0, n);
4887 list[0] = buf.slice(n);
4888 } else if (n === list[0].length) {
4889 // first list is a perfect match
4890 ret = list.shift();
4891 } else {
4892 // complex case.
4893 // we have enough to cover it, but it spans past the first buffer.
4894 if (stringMode)
4895 ret = '';
4896 else
4897 ret = new Buffer(n);
4898
4899 var c = 0;
4900 for (var i = 0, l = list.length; i < l && c < n; i++) {
4901 var buf = list[0];
4902 var cpy = Math.min(n - c, buf.length);
4903
4904 if (stringMode)
4905 ret += buf.slice(0, cpy);
4906 else
4907 buf.copy(ret, c, 0, cpy);
4908
4909 if (cpy < buf.length)
4910 list[0] = buf.slice(cpy);
4911 else
4912 list.shift();
4913
4914 c += cpy;
4915 }
4916 }
4917 }
4918
4919 return ret;
4920}
4921
4922function endReadable(stream) {
4923 var state = stream._readableState;
4924
4925 // If we get here before consuming all the bytes, then that is a
4926 // bug in node. Should never happen.
4927 if (state.length > 0)
4928 throw new Error('endReadable called on non-empty stream');
4929
4930 if (!state.endEmitted) {
4931 state.ended = true;
4932 process.nextTick(function() {
4933 // Check that we didn't get one last unshift.
4934 if (!state.endEmitted && state.length === 0) {
4935 state.endEmitted = true;
4936 stream.readable = false;
4937 stream.emit('end');
4938 }
4939 });
4940 }
4941}
4942
4943function forEach (xs, f) {
4944 for (var i = 0, l = xs.length; i < l; i++) {
4945 f(xs[i], i);
4946 }
4947}
4948
4949function indexOf (xs, x) {
4950 for (var i = 0, l = xs.length; i < l; i++) {
4951 if (xs[i] === x) return i;
4952 }
4953 return -1;
4954}
4955
4956}).call(this,require('_process'))
4957},{"./_stream_duplex":26,"_process":24,"buffer":16,"core-util-is":31,"events":20,"inherits":21,"isarray":22,"stream":36,"string_decoder/":37,"util":15}],29:[function(require,module,exports){
4958// Copyright Joyent, Inc. and other Node contributors.
4959//
4960// Permission is hereby granted, free of charge, to any person obtaining a
4961// copy of this software and associated documentation files (the
4962// "Software"), to deal in the Software without restriction, including
4963// without limitation the rights to use, copy, modify, merge, publish,
4964// distribute, sublicense, and/or sell copies of the Software, and to permit
4965// persons to whom the Software is furnished to do so, subject to the
4966// following conditions:
4967//
4968// The above copyright notice and this permission notice shall be included
4969// in all copies or substantial portions of the Software.
4970//
4971// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4972// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4973// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4974// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4975// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4976// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4977// USE OR OTHER DEALINGS IN THE SOFTWARE.
4978
4979
4980// a transform stream is a readable/writable stream where you do
4981// something with the data. Sometimes it's called a "filter",
4982// but that's not a great name for it, since that implies a thing where
4983// some bits pass through, and others are simply ignored. (That would
4984// be a valid example of a transform, of course.)
4985//
4986// While the output is causally related to the input, it's not a
4987// necessarily symmetric or synchronous transformation. For example,
4988// a zlib stream might take multiple plain-text writes(), and then
4989// emit a single compressed chunk some time in the future.
4990//
4991// Here's how this works:
4992//
4993// The Transform stream has all the aspects of the readable and writable
4994// stream classes. When you write(chunk), that calls _write(chunk,cb)
4995// internally, and returns false if there's a lot of pending writes
4996// buffered up. When you call read(), that calls _read(n) until
4997// there's enough pending readable data buffered up.
4998//
4999// In a transform stream, the written data is placed in a buffer. When
5000// _read(n) is called, it transforms the queued up data, calling the
5001// buffered _write cb's as it consumes chunks. If consuming a single
5002// written chunk would result in multiple output chunks, then the first
5003// outputted bit calls the readcb, and subsequent chunks just go into
5004// the read buffer, and will cause it to emit 'readable' if necessary.
5005//
5006// This way, back-pressure is actually determined by the reading side,
5007// since _read has to be called to start processing a new chunk. However,
5008// a pathological inflate type of transform can cause excessive buffering
5009// here. For example, imagine a stream where every byte of input is
5010// interpreted as an integer from 0-255, and then results in that many
5011// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
5012// 1kb of data being output. In this case, you could write a very small
5013// amount of input, and end up with a very large amount of output. In
5014// such a pathological inflating mechanism, there'd be no way to tell
5015// the system to stop doing the transform. A single 4MB write could
5016// cause the system to run out of memory.
5017//
5018// However, even in such a pathological case, only a single written chunk
5019// would be consumed, and then the rest would wait (un-transformed) until
5020// the results of the previous transformed chunk were consumed.
5021
5022module.exports = Transform;
5023
5024var Duplex = require('./_stream_duplex');
5025
5026/*<replacement>*/
5027var util = require('core-util-is');
5028util.inherits = require('inherits');
5029/*</replacement>*/
5030
5031util.inherits(Transform, Duplex);
5032
5033
5034function TransformState(options, stream) {
5035 this.afterTransform = function(er, data) {
5036 return afterTransform(stream, er, data);
5037 };
5038
5039 this.needTransform = false;
5040 this.transforming = false;
5041 this.writecb = null;
5042 this.writechunk = null;
5043}
5044
5045function afterTransform(stream, er, data) {
5046 var ts = stream._transformState;
5047 ts.transforming = false;
5048
5049 var cb = ts.writecb;
5050
5051 if (!cb)
5052 return stream.emit('error', new Error('no writecb in Transform class'));
5053
5054 ts.writechunk = null;
5055 ts.writecb = null;
5056
5057 if (!util.isNullOrUndefined(data))
5058 stream.push(data);
5059
5060 if (cb)
5061 cb(er);
5062
5063 var rs = stream._readableState;
5064 rs.reading = false;
5065 if (rs.needReadable || rs.length < rs.highWaterMark) {
5066 stream._read(rs.highWaterMark);
5067 }
5068}
5069
5070
5071function Transform(options) {
5072 if (!(this instanceof Transform))
5073 return new Transform(options);
5074
5075 Duplex.call(this, options);
5076
5077 this._transformState = new TransformState(options, this);
5078
5079 // when the writable side finishes, then flush out anything remaining.
5080 var stream = this;
5081
5082 // start out asking for a readable event once data is transformed.
5083 this._readableState.needReadable = true;
5084
5085 // we have implemented the _read method, and done the other things
5086 // that Readable wants before the first _read call, so unset the
5087 // sync guard flag.
5088 this._readableState.sync = false;
5089
5090 this.once('prefinish', function() {
5091 if (util.isFunction(this._flush))
5092 this._flush(function(er) {
5093 done(stream, er);
5094 });
5095 else
5096 done(stream);
5097 });
5098}
5099
5100Transform.prototype.push = function(chunk, encoding) {
5101 this._transformState.needTransform = false;
5102 return Duplex.prototype.push.call(this, chunk, encoding);
5103};
5104
5105// This is the part where you do stuff!
5106// override this function in implementation classes.
5107// 'chunk' is an input chunk.
5108//
5109// Call `push(newChunk)` to pass along transformed output
5110// to the readable side. You may call 'push' zero or more times.
5111//
5112// Call `cb(err)` when you are done with this chunk. If you pass
5113// an error, then that'll put the hurt on the whole operation. If you
5114// never call cb(), then you'll never get another chunk.
5115Transform.prototype._transform = function(chunk, encoding, cb) {
5116 throw new Error('not implemented');
5117};
5118
5119Transform.prototype._write = function(chunk, encoding, cb) {
5120 var ts = this._transformState;
5121 ts.writecb = cb;
5122 ts.writechunk = chunk;
5123 ts.writeencoding = encoding;
5124 if (!ts.transforming) {
5125 var rs = this._readableState;
5126 if (ts.needTransform ||
5127 rs.needReadable ||
5128 rs.length < rs.highWaterMark)
5129 this._read(rs.highWaterMark);
5130 }
5131};
5132
5133// Doesn't matter what the args are here.
5134// _transform does all the work.
5135// That we got here means that the readable side wants more data.
5136Transform.prototype._read = function(n) {
5137 var ts = this._transformState;
5138
5139 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
5140 ts.transforming = true;
5141 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
5142 } else {
5143 // mark that we need a transform, so that any data that comes in
5144 // will get processed, now that we've asked for it.
5145 ts.needTransform = true;
5146 }
5147};
5148
5149
5150function done(stream, er) {
5151 if (er)
5152 return stream.emit('error', er);
5153
5154 // if there's nothing in the write buffer, then that means
5155 // that nothing more will ever be provided
5156 var ws = stream._writableState;
5157 var ts = stream._transformState;
5158
5159 if (ws.length)
5160 throw new Error('calling transform done when ws.length != 0');
5161
5162 if (ts.transforming)
5163 throw new Error('calling transform done when still transforming');
5164
5165 return stream.push(null);
5166}
5167
5168},{"./_stream_duplex":26,"core-util-is":31,"inherits":21}],30:[function(require,module,exports){
5169(function (process){
5170// Copyright Joyent, Inc. and other Node contributors.
5171//
5172// Permission is hereby granted, free of charge, to any person obtaining a
5173// copy of this software and associated documentation files (the
5174// "Software"), to deal in the Software without restriction, including
5175// without limitation the rights to use, copy, modify, merge, publish,
5176// distribute, sublicense, and/or sell copies of the Software, and to permit
5177// persons to whom the Software is furnished to do so, subject to the
5178// following conditions:
5179//
5180// The above copyright notice and this permission notice shall be included
5181// in all copies or substantial portions of the Software.
5182//
5183// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5184// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5185// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5186// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5187// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5188// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5189// USE OR OTHER DEALINGS IN THE SOFTWARE.
5190
5191// A bit simpler than readable streams.
5192// Implement an async ._write(chunk, cb), and it'll handle all
5193// the drain event emission and buffering.
5194
5195module.exports = Writable;
5196
5197/*<replacement>*/
5198var Buffer = require('buffer').Buffer;
5199/*</replacement>*/
5200
5201Writable.WritableState = WritableState;
5202
5203
5204/*<replacement>*/
5205var util = require('core-util-is');
5206util.inherits = require('inherits');
5207/*</replacement>*/
5208
5209var Stream = require('stream');
5210
5211util.inherits(Writable, Stream);
5212
5213function WriteReq(chunk, encoding, cb) {
5214 this.chunk = chunk;
5215 this.encoding = encoding;
5216 this.callback = cb;
5217}
5218
5219function WritableState(options, stream) {
5220 var Duplex = require('./_stream_duplex');
5221
5222 options = options || {};
5223
5224 // the point at which write() starts returning false
5225 // Note: 0 is a valid value, means that we always return false if
5226 // the entire buffer is not flushed immediately on write()
5227 var hwm = options.highWaterMark;
5228 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
5229 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
5230
5231 // object stream flag to indicate whether or not this stream
5232 // contains buffers or objects.
5233 this.objectMode = !!options.objectMode;
5234
5235 if (stream instanceof Duplex)
5236 this.objectMode = this.objectMode || !!options.writableObjectMode;
5237
5238 // cast to ints.
5239 this.highWaterMark = ~~this.highWaterMark;
5240
5241 this.needDrain = false;
5242 // at the start of calling end()
5243 this.ending = false;
5244 // when end() has been called, and returned
5245 this.ended = false;
5246 // when 'finish' is emitted
5247 this.finished = false;
5248
5249 // should we decode strings into buffers before passing to _write?
5250 // this is here so that some node-core streams can optimize string
5251 // handling at a lower level.
5252 var noDecode = options.decodeStrings === false;
5253 this.decodeStrings = !noDecode;
5254
5255 // Crypto is kind of old and crusty. Historically, its default string
5256 // encoding is 'binary' so we have to make this configurable.
5257 // Everything else in the universe uses 'utf8', though.
5258 this.defaultEncoding = options.defaultEncoding || 'utf8';
5259
5260 // not an actual buffer we keep track of, but a measurement
5261 // of how much we're waiting to get pushed to some underlying
5262 // socket or file.
5263 this.length = 0;
5264
5265 // a flag to see when we're in the middle of a write.
5266 this.writing = false;
5267
5268 // when true all writes will be buffered until .uncork() call
5269 this.corked = 0;
5270
5271 // a flag to be able to tell if the onwrite cb is called immediately,
5272 // or on a later tick. We set this to true at first, because any
5273 // actions that shouldn't happen until "later" should generally also
5274 // not happen before the first write call.
5275 this.sync = true;
5276
5277 // a flag to know if we're processing previously buffered items, which
5278 // may call the _write() callback in the same tick, so that we don't
5279 // end up in an overlapped onwrite situation.
5280 this.bufferProcessing = false;
5281
5282 // the callback that's passed to _write(chunk,cb)
5283 this.onwrite = function(er) {
5284 onwrite(stream, er);
5285 };
5286
5287 // the callback that the user supplies to write(chunk,encoding,cb)
5288 this.writecb = null;
5289
5290 // the amount that is being written when _write is called.
5291 this.writelen = 0;
5292
5293 this.buffer = [];
5294
5295 // number of pending user-supplied write callbacks
5296 // this must be 0 before 'finish' can be emitted
5297 this.pendingcb = 0;
5298
5299 // emit prefinish if the only thing we're waiting for is _write cbs
5300 // This is relevant for synchronous Transform streams
5301 this.prefinished = false;
5302
5303 // True if the error was already emitted and should not be thrown again
5304 this.errorEmitted = false;
5305}
5306
5307function Writable(options) {
5308 var Duplex = require('./_stream_duplex');
5309
5310 // Writable ctor is applied to Duplexes, though they're not
5311 // instanceof Writable, they're instanceof Readable.
5312 if (!(this instanceof Writable) && !(this instanceof Duplex))
5313 return new Writable(options);
5314
5315 this._writableState = new WritableState(options, this);
5316
5317 // legacy.
5318 this.writable = true;
5319
5320 Stream.call(this);
5321}
5322
5323// Otherwise people can pipe Writable streams, which is just wrong.
5324Writable.prototype.pipe = function() {
5325 this.emit('error', new Error('Cannot pipe. Not readable.'));
5326};
5327
5328
5329function writeAfterEnd(stream, state, cb) {
5330 var er = new Error('write after end');
5331 // TODO: defer error events consistently everywhere, not just the cb
5332 stream.emit('error', er);
5333 process.nextTick(function() {
5334 cb(er);
5335 });
5336}
5337
5338// If we get something that is not a buffer, string, null, or undefined,
5339// and we're not in objectMode, then that's an error.
5340// Otherwise stream chunks are all considered to be of length=1, and the
5341// watermarks determine how many objects to keep in the buffer, rather than
5342// how many bytes or characters.
5343function validChunk(stream, state, chunk, cb) {
5344 var valid = true;
5345 if (!util.isBuffer(chunk) &&
5346 !util.isString(chunk) &&
5347 !util.isNullOrUndefined(chunk) &&
5348 !state.objectMode) {
5349 var er = new TypeError('Invalid non-string/buffer chunk');
5350 stream.emit('error', er);
5351 process.nextTick(function() {
5352 cb(er);
5353 });
5354 valid = false;
5355 }
5356 return valid;
5357}
5358
5359Writable.prototype.write = function(chunk, encoding, cb) {
5360 var state = this._writableState;
5361 var ret = false;
5362
5363 if (util.isFunction(encoding)) {
5364 cb = encoding;
5365 encoding = null;
5366 }
5367
5368 if (util.isBuffer(chunk))
5369 encoding = 'buffer';
5370 else if (!encoding)
5371 encoding = state.defaultEncoding;
5372
5373 if (!util.isFunction(cb))
5374 cb = function() {};
5375
5376 if (state.ended)
5377 writeAfterEnd(this, state, cb);
5378 else if (validChunk(this, state, chunk, cb)) {
5379 state.pendingcb++;
5380 ret = writeOrBuffer(this, state, chunk, encoding, cb);
5381 }
5382
5383 return ret;
5384};
5385
5386Writable.prototype.cork = function() {
5387 var state = this._writableState;
5388
5389 state.corked++;
5390};
5391
5392Writable.prototype.uncork = function() {
5393 var state = this._writableState;
5394
5395 if (state.corked) {
5396 state.corked--;
5397
5398 if (!state.writing &&
5399 !state.corked &&
5400 !state.finished &&
5401 !state.bufferProcessing &&
5402 state.buffer.length)
5403 clearBuffer(this, state);
5404 }
5405};
5406
5407function decodeChunk(state, chunk, encoding) {
5408 if (!state.objectMode &&
5409 state.decodeStrings !== false &&
5410 util.isString(chunk)) {
5411 chunk = new Buffer(chunk, encoding);
5412 }
5413 return chunk;
5414}
5415
5416// if we're already writing something, then just put this
5417// in the queue, and wait our turn. Otherwise, call _write
5418// If we return false, then we need a drain event, so set that flag.
5419function writeOrBuffer(stream, state, chunk, encoding, cb) {
5420 chunk = decodeChunk(state, chunk, encoding);
5421 if (util.isBuffer(chunk))
5422 encoding = 'buffer';
5423 var len = state.objectMode ? 1 : chunk.length;
5424
5425 state.length += len;
5426
5427 var ret = state.length < state.highWaterMark;
5428 // we must ensure that previous needDrain will not be reset to false.
5429 if (!ret)
5430 state.needDrain = true;
5431
5432 if (state.writing || state.corked)
5433 state.buffer.push(new WriteReq(chunk, encoding, cb));
5434 else
5435 doWrite(stream, state, false, len, chunk, encoding, cb);
5436
5437 return ret;
5438}
5439
5440function doWrite(stream, state, writev, len, chunk, encoding, cb) {
5441 state.writelen = len;
5442 state.writecb = cb;
5443 state.writing = true;
5444 state.sync = true;
5445 if (writev)
5446 stream._writev(chunk, state.onwrite);
5447 else
5448 stream._write(chunk, encoding, state.onwrite);
5449 state.sync = false;
5450}
5451
5452function onwriteError(stream, state, sync, er, cb) {
5453 if (sync)
5454 process.nextTick(function() {
5455 state.pendingcb--;
5456 cb(er);
5457 });
5458 else {
5459 state.pendingcb--;
5460 cb(er);
5461 }
5462
5463 stream._writableState.errorEmitted = true;
5464 stream.emit('error', er);
5465}
5466
5467function onwriteStateUpdate(state) {
5468 state.writing = false;
5469 state.writecb = null;
5470 state.length -= state.writelen;
5471 state.writelen = 0;
5472}
5473
5474function onwrite(stream, er) {
5475 var state = stream._writableState;
5476 var sync = state.sync;
5477 var cb = state.writecb;
5478
5479 onwriteStateUpdate(state);
5480
5481 if (er)
5482 onwriteError(stream, state, sync, er, cb);
5483 else {
5484 // Check if we're actually ready to finish, but don't emit yet
5485 var finished = needFinish(stream, state);
5486
5487 if (!finished &&
5488 !state.corked &&
5489 !state.bufferProcessing &&
5490 state.buffer.length) {
5491 clearBuffer(stream, state);
5492 }
5493
5494 if (sync) {
5495 process.nextTick(function() {
5496 afterWrite(stream, state, finished, cb);
5497 });
5498 } else {
5499 afterWrite(stream, state, finished, cb);
5500 }
5501 }
5502}
5503
5504function afterWrite(stream, state, finished, cb) {
5505 if (!finished)
5506 onwriteDrain(stream, state);
5507 state.pendingcb--;
5508 cb();
5509 finishMaybe(stream, state);
5510}
5511
5512// Must force callback to be called on nextTick, so that we don't
5513// emit 'drain' before the write() consumer gets the 'false' return
5514// value, and has a chance to attach a 'drain' listener.
5515function onwriteDrain(stream, state) {
5516 if (state.length === 0 && state.needDrain) {
5517 state.needDrain = false;
5518 stream.emit('drain');
5519 }
5520}
5521
5522
5523// if there's something in the buffer waiting, then process it
5524function clearBuffer(stream, state) {
5525 state.bufferProcessing = true;
5526
5527 if (stream._writev && state.buffer.length > 1) {
5528 // Fast case, write everything using _writev()
5529 var cbs = [];
5530 for (var c = 0; c < state.buffer.length; c++)
5531 cbs.push(state.buffer[c].callback);
5532
5533 // count the one we are adding, as well.
5534 // TODO(isaacs) clean this up
5535 state.pendingcb++;
5536 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
5537 for (var i = 0; i < cbs.length; i++) {
5538 state.pendingcb--;
5539 cbs[i](err);
5540 }
5541 });
5542
5543 // Clear buffer
5544 state.buffer = [];
5545 } else {
5546 // Slow case, write chunks one-by-one
5547 for (var c = 0; c < state.buffer.length; c++) {
5548 var entry = state.buffer[c];
5549 var chunk = entry.chunk;
5550 var encoding = entry.encoding;
5551 var cb = entry.callback;
5552 var len = state.objectMode ? 1 : chunk.length;
5553
5554 doWrite(stream, state, false, len, chunk, encoding, cb);
5555
5556 // if we didn't call the onwrite immediately, then
5557 // it means that we need to wait until it does.
5558 // also, that means that the chunk and cb are currently
5559 // being processed, so move the buffer counter past them.
5560 if (state.writing) {
5561 c++;
5562 break;
5563 }
5564 }
5565
5566 if (c < state.buffer.length)
5567 state.buffer = state.buffer.slice(c);
5568 else
5569 state.buffer.length = 0;
5570 }
5571
5572 state.bufferProcessing = false;
5573}
5574
5575Writable.prototype._write = function(chunk, encoding, cb) {
5576 cb(new Error('not implemented'));
5577
5578};
5579
5580Writable.prototype._writev = null;
5581
5582Writable.prototype.end = function(chunk, encoding, cb) {
5583 var state = this._writableState;
5584
5585 if (util.isFunction(chunk)) {
5586 cb = chunk;
5587 chunk = null;
5588 encoding = null;
5589 } else if (util.isFunction(encoding)) {
5590 cb = encoding;
5591 encoding = null;
5592 }
5593
5594 if (!util.isNullOrUndefined(chunk))
5595 this.write(chunk, encoding);
5596
5597 // .end() fully uncorks
5598 if (state.corked) {
5599 state.corked = 1;
5600 this.uncork();
5601 }
5602
5603 // ignore unnecessary end() calls.
5604 if (!state.ending && !state.finished)
5605 endWritable(this, state, cb);
5606};
5607
5608
5609function needFinish(stream, state) {
5610 return (state.ending &&
5611 state.length === 0 &&
5612 !state.finished &&
5613 !state.writing);
5614}
5615
5616function prefinish(stream, state) {
5617 if (!state.prefinished) {
5618 state.prefinished = true;
5619 stream.emit('prefinish');
5620 }
5621}
5622
5623function finishMaybe(stream, state) {
5624 var need = needFinish(stream, state);
5625 if (need) {
5626 if (state.pendingcb === 0) {
5627 prefinish(stream, state);
5628 state.finished = true;
5629 stream.emit('finish');
5630 } else
5631 prefinish(stream, state);
5632 }
5633 return need;
5634}
5635
5636function endWritable(stream, state, cb) {
5637 state.ending = true;
5638 finishMaybe(stream, state);
5639 if (cb) {
5640 if (state.finished)
5641 process.nextTick(cb);
5642 else
5643 stream.once('finish', cb);
5644 }
5645 state.ended = true;
5646}
5647
5648}).call(this,require('_process'))
5649},{"./_stream_duplex":26,"_process":24,"buffer":16,"core-util-is":31,"inherits":21,"stream":36}],31:[function(require,module,exports){
5650(function (Buffer){
5651// Copyright Joyent, Inc. and other Node contributors.
5652//
5653// Permission is hereby granted, free of charge, to any person obtaining a
5654// copy of this software and associated documentation files (the
5655// "Software"), to deal in the Software without restriction, including
5656// without limitation the rights to use, copy, modify, merge, publish,
5657// distribute, sublicense, and/or sell copies of the Software, and to permit
5658// persons to whom the Software is furnished to do so, subject to the
5659// following conditions:
5660//
5661// The above copyright notice and this permission notice shall be included
5662// in all copies or substantial portions of the Software.
5663//
5664// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5665// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5666// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5667// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5668// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5669// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5670// USE OR OTHER DEALINGS IN THE SOFTWARE.
5671
5672// NOTE: These type checking functions intentionally don't use `instanceof`
5673// because it is fragile and can be easily faked with `Object.create()`.
5674function isArray(ar) {
5675 return Array.isArray(ar);
5676}
5677exports.isArray = isArray;
5678
5679function isBoolean(arg) {
5680 return typeof arg === 'boolean';
5681}
5682exports.isBoolean = isBoolean;
5683
5684function isNull(arg) {
5685 return arg === null;
5686}
5687exports.isNull = isNull;
5688
5689function isNullOrUndefined(arg) {
5690 return arg == null;
5691}
5692exports.isNullOrUndefined = isNullOrUndefined;
5693
5694function isNumber(arg) {
5695 return typeof arg === 'number';
5696}
5697exports.isNumber = isNumber;
5698
5699function isString(arg) {
5700 return typeof arg === 'string';
5701}
5702exports.isString = isString;
5703
5704function isSymbol(arg) {
5705 return typeof arg === 'symbol';
5706}
5707exports.isSymbol = isSymbol;
5708
5709function isUndefined(arg) {
5710 return arg === void 0;
5711}
5712exports.isUndefined = isUndefined;
5713
5714function isRegExp(re) {
5715 return isObject(re) && objectToString(re) === '[object RegExp]';
5716}
5717exports.isRegExp = isRegExp;
5718
5719function isObject(arg) {
5720 return typeof arg === 'object' && arg !== null;
5721}
5722exports.isObject = isObject;
5723
5724function isDate(d) {
5725 return isObject(d) && objectToString(d) === '[object Date]';
5726}
5727exports.isDate = isDate;
5728
5729function isError(e) {
5730 return isObject(e) &&
5731 (objectToString(e) === '[object Error]' || e instanceof Error);
5732}
5733exports.isError = isError;
5734
5735function isFunction(arg) {
5736 return typeof arg === 'function';
5737}
5738exports.isFunction = isFunction;
5739
5740function isPrimitive(arg) {
5741 return arg === null ||
5742 typeof arg === 'boolean' ||
5743 typeof arg === 'number' ||
5744 typeof arg === 'string' ||
5745 typeof arg === 'symbol' || // ES6 symbol
5746 typeof arg === 'undefined';
5747}
5748exports.isPrimitive = isPrimitive;
5749
5750function isBuffer(arg) {
5751 return Buffer.isBuffer(arg);
5752}
5753exports.isBuffer = isBuffer;
5754
5755function objectToString(o) {
5756 return Object.prototype.toString.call(o);
5757}
5758}).call(this,require("buffer").Buffer)
5759},{"buffer":16}],32:[function(require,module,exports){
5760module.exports = require("./lib/_stream_passthrough.js")
5761
5762},{"./lib/_stream_passthrough.js":27}],33:[function(require,module,exports){
5763exports = module.exports = require('./lib/_stream_readable.js');
5764exports.Stream = require('stream');
5765exports.Readable = exports;
5766exports.Writable = require('./lib/_stream_writable.js');
5767exports.Duplex = require('./lib/_stream_duplex.js');
5768exports.Transform = require('./lib/_stream_transform.js');
5769exports.PassThrough = require('./lib/_stream_passthrough.js');
5770
5771},{"./lib/_stream_duplex.js":26,"./lib/_stream_passthrough.js":27,"./lib/_stream_readable.js":28,"./lib/_stream_transform.js":29,"./lib/_stream_writable.js":30,"stream":36}],34:[function(require,module,exports){
5772module.exports = require("./lib/_stream_transform.js")
5773
5774},{"./lib/_stream_transform.js":29}],35:[function(require,module,exports){
5775module.exports = require("./lib/_stream_writable.js")
5776
5777},{"./lib/_stream_writable.js":30}],36:[function(require,module,exports){
5778// Copyright Joyent, Inc. and other Node contributors.
5779//
5780// Permission is hereby granted, free of charge, to any person obtaining a
5781// copy of this software and associated documentation files (the
5782// "Software"), to deal in the Software without restriction, including
5783// without limitation the rights to use, copy, modify, merge, publish,
5784// distribute, sublicense, and/or sell copies of the Software, and to permit
5785// persons to whom the Software is furnished to do so, subject to the
5786// following conditions:
5787//
5788// The above copyright notice and this permission notice shall be included
5789// in all copies or substantial portions of the Software.
5790//
5791// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5792// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5793// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5794// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5795// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5796// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5797// USE OR OTHER DEALINGS IN THE SOFTWARE.
5798
5799module.exports = Stream;
5800
5801var EE = require('events').EventEmitter;
5802var inherits = require('inherits');
5803
5804inherits(Stream, EE);
5805Stream.Readable = require('readable-stream/readable.js');
5806Stream.Writable = require('readable-stream/writable.js');
5807Stream.Duplex = require('readable-stream/duplex.js');
5808Stream.Transform = require('readable-stream/transform.js');
5809Stream.PassThrough = require('readable-stream/passthrough.js');
5810
5811// Backwards-compat with node 0.4.x
5812Stream.Stream = Stream;
5813
5814
5815
5816// old-style streams. Note that the pipe method (the only relevant
5817// part of this class) is overridden in the Readable class.
5818
5819function Stream() {
5820 EE.call(this);
5821}
5822
5823Stream.prototype.pipe = function(dest, options) {
5824 var source = this;
5825
5826 function ondata(chunk) {
5827 if (dest.writable) {
5828 if (false === dest.write(chunk) && source.pause) {
5829 source.pause();
5830 }
5831 }
5832 }
5833
5834 source.on('data', ondata);
5835
5836 function ondrain() {
5837 if (source.readable && source.resume) {
5838 source.resume();
5839 }
5840 }
5841
5842 dest.on('drain', ondrain);
5843
5844 // If the 'end' option is not supplied, dest.end() will be called when
5845 // source gets the 'end' or 'close' events. Only dest.end() once.
5846 if (!dest._isStdio && (!options || options.end !== false)) {
5847 source.on('end', onend);
5848 source.on('close', onclose);
5849 }
5850
5851 var didOnEnd = false;
5852 function onend() {
5853 if (didOnEnd) return;
5854 didOnEnd = true;
5855
5856 dest.end();
5857 }
5858
5859
5860 function onclose() {
5861 if (didOnEnd) return;
5862 didOnEnd = true;
5863
5864 if (typeof dest.destroy === 'function') dest.destroy();
5865 }
5866
5867 // don't leave dangling pipes when there are errors.
5868 function onerror(er) {
5869 cleanup();
5870 if (EE.listenerCount(this, 'error') === 0) {
5871 throw er; // Unhandled stream error in pipe.
5872 }
5873 }
5874
5875 source.on('error', onerror);
5876 dest.on('error', onerror);
5877
5878 // remove all the event listeners that were added.
5879 function cleanup() {
5880 source.removeListener('data', ondata);
5881 dest.removeListener('drain', ondrain);
5882
5883 source.removeListener('end', onend);
5884 source.removeListener('close', onclose);
5885
5886 source.removeListener('error', onerror);
5887 dest.removeListener('error', onerror);
5888
5889 source.removeListener('end', cleanup);
5890 source.removeListener('close', cleanup);
5891
5892 dest.removeListener('close', cleanup);
5893 }
5894
5895 source.on('end', cleanup);
5896 source.on('close', cleanup);
5897
5898 dest.on('close', cleanup);
5899
5900 dest.emit('pipe', source);
5901
5902 // Allow for unix-like usage: A.pipe(B).pipe(C)
5903 return dest;
5904};
5905
5906},{"events":20,"inherits":21,"readable-stream/duplex.js":25,"readable-stream/passthrough.js":32,"readable-stream/readable.js":33,"readable-stream/transform.js":34,"readable-stream/writable.js":35}],37:[function(require,module,exports){
5907// Copyright Joyent, Inc. and other Node contributors.
5908//
5909// Permission is hereby granted, free of charge, to any person obtaining a
5910// copy of this software and associated documentation files (the
5911// "Software"), to deal in the Software without restriction, including
5912// without limitation the rights to use, copy, modify, merge, publish,
5913// distribute, sublicense, and/or sell copies of the Software, and to permit
5914// persons to whom the Software is furnished to do so, subject to the
5915// following conditions:
5916//
5917// The above copyright notice and this permission notice shall be included
5918// in all copies or substantial portions of the Software.
5919//
5920// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5921// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5922// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5923// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5924// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5925// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5926// USE OR OTHER DEALINGS IN THE SOFTWARE.
5927
5928var Buffer = require('buffer').Buffer;
5929
5930var isBufferEncoding = Buffer.isEncoding
5931 || function(encoding) {
5932 switch (encoding && encoding.toLowerCase()) {
5933 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
5934 default: return false;
5935 }
5936 }
5937
5938
5939function assertEncoding(encoding) {
5940 if (encoding && !isBufferEncoding(encoding)) {
5941 throw new Error('Unknown encoding: ' + encoding);
5942 }
5943}
5944
5945// StringDecoder provides an interface for efficiently splitting a series of
5946// buffers into a series of JS strings without breaking apart multi-byte
5947// characters. CESU-8 is handled as part of the UTF-8 encoding.
5948//
5949// @TODO Handling all encodings inside a single object makes it very difficult
5950// to reason about this code, so it should be split up in the future.
5951// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
5952// points as used by CESU-8.
5953var StringDecoder = exports.StringDecoder = function(encoding) {
5954 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
5955 assertEncoding(encoding);
5956 switch (this.encoding) {
5957 case 'utf8':
5958 // CESU-8 represents each of Surrogate Pair by 3-bytes
5959 this.surrogateSize = 3;
5960 break;
5961 case 'ucs2':
5962 case 'utf16le':
5963 // UTF-16 represents each of Surrogate Pair by 2-bytes
5964 this.surrogateSize = 2;
5965 this.detectIncompleteChar = utf16DetectIncompleteChar;
5966 break;
5967 case 'base64':
5968 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
5969 this.surrogateSize = 3;
5970 this.detectIncompleteChar = base64DetectIncompleteChar;
5971 break;
5972 default:
5973 this.write = passThroughWrite;
5974 return;
5975 }
5976
5977 // Enough space to store all bytes of a single character. UTF-8 needs 4
5978 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
5979 this.charBuffer = new Buffer(6);
5980 // Number of bytes received for the current incomplete multi-byte character.
5981 this.charReceived = 0;
5982 // Number of bytes expected for the current incomplete multi-byte character.
5983 this.charLength = 0;
5984};
5985
5986
5987// write decodes the given buffer and returns it as JS string that is
5988// guaranteed to not contain any partial multi-byte characters. Any partial
5989// character found at the end of the buffer is buffered up, and will be
5990// returned when calling write again with the remaining bytes.
5991//
5992// Note: Converting a Buffer containing an orphan surrogate to a String
5993// currently works, but converting a String to a Buffer (via `new Buffer`, or
5994// Buffer#write) will replace incomplete surrogates with the unicode
5995// replacement character. See https://codereview.chromium.org/121173009/ .
5996StringDecoder.prototype.write = function(buffer) {
5997 var charStr = '';
5998 // if our last write ended with an incomplete multibyte character
5999 while (this.charLength) {
6000 // determine how many remaining bytes this buffer has to offer for this char
6001 var available = (buffer.length >= this.charLength - this.charReceived) ?
6002 this.charLength - this.charReceived :
6003 buffer.length;
6004
6005 // add the new bytes to the char buffer
6006 buffer.copy(this.charBuffer, this.charReceived, 0, available);
6007 this.charReceived += available;
6008
6009 if (this.charReceived < this.charLength) {
6010 // still not enough chars in this buffer? wait for more ...
6011 return '';
6012 }
6013
6014 // remove bytes belonging to the current character from the buffer
6015 buffer = buffer.slice(available, buffer.length);
6016
6017 // get the character that was split
6018 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
6019
6020 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
6021 var charCode = charStr.charCodeAt(charStr.length - 1);
6022 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
6023 this.charLength += this.surrogateSize;
6024 charStr = '';
6025 continue;
6026 }
6027 this.charReceived = this.charLength = 0;
6028
6029 // if there are no more bytes in this buffer, just emit our char
6030 if (buffer.length === 0) {
6031 return charStr;
6032 }
6033 break;
6034 }
6035
6036 // determine and set charLength / charReceived
6037 this.detectIncompleteChar(buffer);
6038
6039 var end = buffer.length;
6040 if (this.charLength) {
6041 // buffer the incomplete character bytes we got
6042 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
6043 end -= this.charReceived;
6044 }
6045
6046 charStr += buffer.toString(this.encoding, 0, end);
6047
6048 var end = charStr.length - 1;
6049 var charCode = charStr.charCodeAt(end);
6050 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
6051 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
6052 var size = this.surrogateSize;
6053 this.charLength += size;
6054 this.charReceived += size;
6055 this.charBuffer.copy(this.charBuffer, size, 0, size);
6056 buffer.copy(this.charBuffer, 0, 0, size);
6057 return charStr.substring(0, end);
6058 }
6059
6060 // or just emit the charStr
6061 return charStr;
6062};
6063
6064// detectIncompleteChar determines if there is an incomplete UTF-8 character at
6065// the end of the given buffer. If so, it sets this.charLength to the byte
6066// length that character, and sets this.charReceived to the number of bytes
6067// that are available for this character.
6068StringDecoder.prototype.detectIncompleteChar = function(buffer) {
6069 // determine how many bytes we have to check at the end of this buffer
6070 var i = (buffer.length >= 3) ? 3 : buffer.length;
6071
6072 // Figure out if one of the last i bytes of our buffer announces an
6073 // incomplete char.
6074 for (; i > 0; i--) {
6075 var c = buffer[buffer.length - i];
6076
6077 // See http://en.wikipedia.org/wiki/UTF-8#Description
6078
6079 // 110XXXXX
6080 if (i == 1 && c >> 5 == 0x06) {
6081 this.charLength = 2;
6082 break;
6083 }
6084
6085 // 1110XXXX
6086 if (i <= 2 && c >> 4 == 0x0E) {
6087 this.charLength = 3;
6088 break;
6089 }
6090
6091 // 11110XXX
6092 if (i <= 3 && c >> 3 == 0x1E) {
6093 this.charLength = 4;
6094 break;
6095 }
6096 }
6097 this.charReceived = i;
6098};
6099
6100StringDecoder.prototype.end = function(buffer) {
6101 var res = '';
6102 if (buffer && buffer.length)
6103 res = this.write(buffer);
6104
6105 if (this.charReceived) {
6106 var cr = this.charReceived;
6107 var buf = this.charBuffer;
6108 var enc = this.encoding;
6109 res += buf.slice(0, cr).toString(enc);
6110 }
6111
6112 return res;
6113};
6114
6115function passThroughWrite(buffer) {
6116 return buffer.toString(this.encoding);
6117}
6118
6119function utf16DetectIncompleteChar(buffer) {
6120 this.charReceived = buffer.length % 2;
6121 this.charLength = this.charReceived ? 2 : 0;
6122}
6123
6124function base64DetectIncompleteChar(buffer) {
6125 this.charReceived = buffer.length % 3;
6126 this.charLength = this.charReceived ? 3 : 0;
6127}
6128
6129},{"buffer":16}],38:[function(require,module,exports){
6130// This is a basic test file for use with testling.
6131// The test script language comes from tape.
6132var test = require('tape');
6133
6134m = require('../adapter.js');
6135
6136test('Browser identified', function(t) {
6137 t.plan(2);
6138 t.ok(m.webrtcDetectedBrowser);
6139 t.ok(m.webrtcDetectedVersion);
6140});
6141
6142},{"../adapter.js":1,"tape":2}]},{},[38]);