s-pipe
Version:
Functional streams, with a lisp-inspired chaining syntax
1,642 lines (1,640 loc) • 149 kB
JavaScript
(function(exported) {
if (typeof exports === 'object') {
module.exports = exported;
} else if (typeof define === 'function' && define.amd) {
define(function() {
return exported;
});
} else {
}
})((function(require, undefined) { var global = this;
require.define('1', function(module, exports, __dirname, __filename, undefined){
var spipe = require('2', module);
var TokenStream = require('3', module);
var CalculatorTokenStream = TokenStream.extend({
lib: {
binDigit: /[01]/,
octDigit: /{{binDigit}}|[2-7]/,
decDigit: /{{octDigit}}|[89]/,
hexDigit: /{{decDigit}}|[a-fA-F]/,
exponent: /[eE][+-]?{{decDigit}}/,
dot: /\./,
space: /[ \t]+/,
newline: /(?:\r\n|\r|\n)+/,
base2int: /0[bB]{{binDigit}}+/,
base8int: /0[oO]{{octDigit}}+/,
base10int: /{{decDigit}}+{{exponent}}?/,
base16int: /0[xX]{{hexDigit}}+/,
dotFloat: /{{dot}}{{decDigit}}+{{exponent}}?/,
normalFloat: /{{decDigit}}+{{dotFloat}}?/,
float: /{{dotFloat}}|{{normalFloat}}|{{base10int}}/,
boolean: /true|false/,
name: /^[_$a-zA-Z\xa0-\uffff][_$a-zA-Z0-9\xa0-\uffff]*$/,
operator: /<=|>=|[=<>+.\-*\/%&|^]/,
stringStart: /"/
},
states: {
start: [
'space',
'newline',
'base2int',
'base8int',
'base16int',
'float',
'boolean',
'name',
'operator',
'stringStart'
]
},
factory: {
space: function () {
},
newline: function () {
}
}
});
function tokenize() {
return new CalculatorTokenStream(this);
}
runMocha({
'TokenStream': {
'tokenize synchronously': function () {
deepEqual(spipe('5.5 0xff true+10')(tokenize)(), [
'5.5',
'0xff',
'true',
'+',
'10'
]);
},
'lazily evaluate the stream': function (done) {
var result = [];
var stream = spipe('5.5 0xff true+10')(tokenize)(false);
stream.on('data', function (n) {
result.push(n);
});
stream.on('end', function () {
deepEqual(result, [
'5.5',
'0xff',
'true',
'+',
'10'
]);
done();
});
}
}
});
});
require.define('3', function(module, exports, __dirname, __filename, undefined){
var has = require('4', module);
var is = require('5', module);
var classic = require('6', module);
var PullStream = require('7', module);
function compileRule(rule, lib, cache) {
if (has(cache, rule))
return cache[rule];
if (has(rule, 'source')) {
rule = rule.source;
}
rule = rule.toString();
var compiled = rule.replace(/\((?!\?\:)(.+)\)/, '(?:$1)');
compiled = compiled.replace(/{{(\w+)}}/g, function (match, r) {
var resolved = lib[r];
if (!resolved)
throw new Error('Cant resolve lexer rule \'' + r + '\'');
return '(?:' + compileRule(resolved, lib, cache) + ')';
});
return cache[rule] = compiled;
}
function compile(grammar) {
var rv = {};
var cache = {};
var states = grammar.states;
for (var k in states) {
if (!has(states, k))
continue;
var alts = states[k];
var components = [];
for (var i = 0, l = alts.length; i < l; i++) {
components.push('(' + compileRule('{{' + alts[i] + '}}', grammar.lib, cache) + ')');
}
rv[k] = {
rules: alts,
regexp: new RegExp('^(?:' + components.join('|') + ')')
};
}
return rv;
}
var TokenStream = PullStream.extend({
constructor: function TokenStream(source, grammars, factory) {
PullStream.call(this, source);
this._lexState = {
stack: [grammars.start],
grammars: grammars,
factory: factory,
startPos: 0,
pos: 0,
lineStart: 1,
colStart: 0,
line: 1,
col: 0,
buffered: '',
text: null
};
},
_currentState: function () {
var stack = this._lexState.stack;
return stack[stack.length - 1];
},
_seek: function (count) {
var state = this._lexState, raw, lines;
state.lineStart = state.line;
state.colStart = state.col;
state.startPos = state.pos;
state.pos += count;
raw = state.buffered.slice(state.startPos, state.pos);
state.buffered = state.buffered.slice(count);
lines = raw.split('\n').length - 1;
if (lines) {
state.line += lines;
state.col = /\n(.*)$/.exec(raw)[1].length;
} else {
state.col += raw.length;
}
},
_process: function (chunk) {
var state = this._lexState;
var factory = state.factory;
state.buffered += chunk;
while (state.buffered.length) {
var match;
var currentState = this._currentState();
var rules = currentState.rules;
var regexp = currentState.regexp;
if (!(match = regexp.exec(state.buffered)))
break;
this._seek(match[0].length);
for (var i = 0, l = rules.length; i < l; i++) {
var matchIdx = i + 1;
var rule = rules[i];
if (match[matchIdx]) {
state.text = match[matchIdx];
if (has(factory, rule)) {
var result = factory[rule](state);
if (!is.nil(result))
this.push(result);
} else {
this.push(state.text);
}
break;
}
}
}
}
});
TokenStream.extend = function (grammar) {
var factory = grammar.factory || {};
grammar = compile(grammar);
return classic({
constructor: function (source) {
TokenStream.call(this, source, grammar, factory);
}
}, TokenStream);
};
module.exports = TokenStream;
});
require.define('7', function(module, exports, __dirname, __filename, undefined){
var PassThrough = require('8', module).PassThrough;
var classic = require('6', module);
var AnythingStream = require('9', module);
function PullState(source) {
this.source = source;
this.started = false;
this.ended = false;
this.endEmitted = false;
}
var PullStream = AnythingStream.extend({
constructor: function PullStream(source) {
AnythingStream.call(this);
this._pullState = new PullState(source || new PassThrough());
},
_write: function (chunk, encoding, callback) {
this._pullState.source._write(chunk, encoding, callback);
},
_read: function () {
var _this = this, state = this._pullState;
if (state.started)
return;
state.started = true;
state.ended = false;
this.on('pause', function () {
state.source.pause();
});
this.on('resume', function () {
state.source.resume();
});
state.source.on('close', function () {
_this.emit('close');
});
state.source.on('error', function (err) {
_this.emit('error', err);
});
state.source.on('end', function () {
_this._end();
});
state.source.on('data', function (chunk) {
_this._process(chunk);
});
},
_done: function () {
var state = this._pullState;
return state.ended || (state.ended = state.source._done ? state.source._done() : false);
},
setEncoding: function (encoding) {
return this._pullState.source.setEncoding(encoding);
},
close: function () {
var state = this._pullState;
this.pause();
if (typeof state.source.close === 'function')
state.source.close();
state.ended = true;
},
destroy: function () {
var state = this._pullState;
this.pause();
if (typeof state.source.destroy === 'function')
state.source.destroy();
state.ended = true;
}
});
module.exports = PullStream;
});
require.define('9', function(module, exports, __dirname, __filename, undefined){
var Duplex = require('8', module).Duplex;
var classic = require('6', module);
var is = require('5', module);
var AnythingStream = classic({
constructor: function AnythingStream() {
Duplex.call(this, { objectMode: true });
},
push: function (chunk) {
var state = this._readableState;
state.length += 1;
state.buffer.push(chunk);
state.reading = false;
if (this._done())
this._end();
},
_forward: function (chunk) {
this.emit('data', chunk);
if (this._done())
this._end();
},
_end: function () {
if (is.func(this._ended))
this._ended();
Duplex.prototype.push.call(this, null);
},
_done: function () {
throw new Error('not implemented');
}
}, Duplex);
module.exports = AnythingStream;
});
require.define('6', function(module, exports, __dirname, __filename, undefined){
var inherits = require('10', module);
var has = require('4', module);
module.exports = function classic(protoSetup, superClass) {
var constructor, protoTmp;
if (typeof protoSetup === 'function') {
protoTmp = {};
protoSetup.call(protoTmp);
} else {
protoTmp = protoSetup;
}
constructor = protoTmp.constructor;
if (!has(protoTmp, 'constructor')) {
if (superClass) {
constructor = function () {
superClass.apply(this, arguments);
};
} else {
constructor = function () {
};
}
}
delete protoTmp.constructor;
if (superClass) {
inherits(constructor, superClass);
}
for (var k in protoTmp) {
if (!has(protoTmp, k))
continue;
constructor.prototype[k] = protoTmp[k];
}
constructor.extend = function (protoSetup) {
return classic(protoSetup, constructor);
};
return constructor;
};
});
require.define('4', function(module, exports, __dirname, __filename, undefined){
var hasOwn = Object.prototype.hasOwnProperty;
module.exports = function has(obj, property) {
return hasOwn.call(obj, property);
};
});
require.define('10', function(module, exports, __dirname, __filename, undefined){
if (typeof Object.create === 'function') {
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {
};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
};
}
});
require.define('8', function(module, exports, __dirname, __filename, undefined){
module.exports = Stream;
var EE = require('11', module).EventEmitter;
var util = require('12', module);
util.inherits(Stream, EE);
Stream.Readable = require('13', module);
Stream.Writable = require('14', module);
Stream.Duplex = require('15', module);
Stream.Transform = require('16', module);
Stream.PassThrough = require('17', module);
Stream.Stream = Stream;
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function (dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd)
return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd)
return;
didOnEnd = true;
if (typeof dest.destroy === 'function')
dest.destroy();
}
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er;
}
}
source.on('error', onerror);
dest.on('error', onerror);
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
return dest;
};
});
require.define('17', function(module, exports, __dirname, __filename, undefined){
module.exports = PassThrough;
var Transform = require('16', module);
var util = require('12', module);
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
});
require.define('12', function(module, exports, __dirname, __filename, undefined){
var shims = require('18', module);
var formatRegExp = /%[sdj%]/g;
exports.format = function (f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function (x) {
if (x === '%%')
return '%';
if (i >= len)
return x;
switch (x) {
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
function inspect(obj, opts) {
var ctx = {
seen: [],
stylize: stylizeNoColor
};
if (arguments.length >= 3)
ctx.depth = arguments[2];
if (arguments.length >= 4)
ctx.colors = arguments[3];
if (isBoolean(opts)) {
ctx.showHidden = opts;
} else if (opts) {
exports._extend(ctx, opts);
}
if (isUndefined(ctx.showHidden))
ctx.showHidden = false;
if (isUndefined(ctx.depth))
ctx.depth = 2;
if (isUndefined(ctx.colors))
ctx.colors = false;
if (isUndefined(ctx.customInspect))
ctx.customInspect = true;
if (ctx.colors)
ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
inspect.colors = {
'bold': [
1,
22
],
'italic': [
3,
23
],
'underline': [
4,
24
],
'inverse': [
7,
27
],
'white': [
37,
39
],
'grey': [
90,
39
],
'black': [
30,
39
],
'blue': [
34,
39
],
'cyan': [
36,
39
],
'green': [
32,
39
],
'magenta': [
35,
39
],
'red': [
31,
39
],
'yellow': [
33,
39
]
};
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\x1b[' + inspect.colors[style][0] + 'm' + str + '\x1b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
shims.forEach(array, function (val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
if (ctx.customInspect && value && isFunction(value.inspect) && value.inspect !== exports.inspect && !(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
var keys = shims.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = shims.getOwnPropertyNames(value);
}
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = [
'{',
'}'
];
if (isArray(value)) {
array = true;
braces = [
'[',
']'
];
}
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function (key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, '\\\'').replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true));
} else {
output.push('');
}
}
shims.forEach(keys, function (key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (shims.indexOf(ctx.seen, desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function (line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function (line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, '\\\'').replace(/\\"/g, '"').replace(/(^"|"$)/g, '\'');
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = shims.reduce(output, function (prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0)
numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
function isArray(ar) {
return shims.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) && objectToString(e) === '[object Error]';
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.binarySlice === 'function';
;
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
function timestamp() {
var d = new Date();
var time = [
pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())
].join(':');
return [
d.getDate(),
months[d.getMonth()],
time
].join(' ');
}
exports.log = function () {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
exports.inherits = function (ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = shims.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
exports._extend = function (origin, add) {
if (!add || !isObject(add))
return origin;
var keys = shims.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
});
require.define('18', function(module, exports, __dirname, __filename, undefined){
var toString = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isArray(xs) {
return toString.call(xs) === '[object Array]';
}
exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray;
exports.indexOf = function indexOf(xs, x) {
if (xs.indexOf)
return xs.indexOf(x);
for (var i = 0; i < xs.length; i++) {
if (x === xs[i])
return i;
}
return -1;
};
exports.filter = function filter(xs, fn) {
if (xs.filter)
return xs.filter(fn);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (fn(xs[i], i, xs))
res.push(xs[i]);
}
return res;
};
exports.forEach = function forEach(xs, fn, self) {
if (xs.forEach)
return xs.forEach(fn, self);
for (var i = 0; i < xs.length; i++) {
fn.call(self, xs[i], i, xs);
}
};
exports.map = function map(xs, fn) {
if (xs.map)
return xs.map(fn);
var out = new Array(xs.length);
for (var i = 0; i < xs.length; i++) {
out[i] = fn(xs[i], i, xs);
}
return out;
};
exports.reduce = function reduce(array, callback, opt_initialValue) {
if (array.reduce)
return array.reduce(callback, opt_initialValue);
var value, isValueSet = false;
if (2 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (var i = 0, l = array.length; l > i; ++i) {
if (array.hasOwnProperty(i)) {
if (isValueSet) {
value = callback(value, array[i], i, array);
} else {
value = array[i];
isValueSet = true;
}
}
}
return value;
};
if ('ab'.substr(-1) !== 'b') {
exports.substr = function (str, start, length) {
if (start < 0)
start = str.length + start;
return str.substr(start, length);
};
} else {
exports.substr = function (str, start, length) {
return str.substr(start, length);
};
}
exports.trim = function (str) {
if (str.trim)
return str.trim();
return str.replace(/^\s+|\s+$/g, '');
};
exports.bind = function () {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
if (fn.bind)
return fn.bind.apply(fn, args);
var self = args.shift();
return function () {
fn.apply(self, args.concat([Array.prototype.slice.call(arguments)]));
};
};
function create(prototype, properties) {
var object;
if (prototype === null) {
object = { '__proto__': null };
} else {
if (typeof prototype !== 'object') {
throw new TypeError('typeof prototype[' + typeof prototype + '] != \'object\'');
}
var Type = function () {
};
Type.prototype = prototype;
object = new Type();
object.__proto__ = prototype;
}
if (typeof properties !== 'undefined' && Object.defineProperties) {
Object.defineProperties(object, properties);
}
return object;
}
exports.create = typeof Object.create === 'function' ? Object.create : create;
function notObject(object) {
return typeof object != 'object' && typeof object != 'function' || object === null;
}
function keysShim(object) {
if (notObject(object)) {
throw new TypeError('Object.keys called on a non-object');
}
var result = [];
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result.push(name);
}
}
return result;
}
function propertyShim(object) {
if (notObject(object)) {
throw new TypeError('Object.getOwnPropertyNames called on a non-object');
}
var result = keysShim(object);
if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) {
result.push('length');
}
return result;
}
var keys = typeof Object.keys === 'function' ? Object.keys : keysShim;
var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? Object.getOwnPropertyNames : propertyShim;
if (new Error().hasOwnProperty('description')) {
var ERROR_PROPERTY_FILTER = function (obj, array) {
if (toString.call(obj) === '[object Error]') {
array = exports.filter(array, function (name) {
return name !== 'description' && name !== 'number' && name !== 'message';
});
}
return array;
};
exports.keys = function (object) {
return ERROR_PROPERTY_FILTER(object, keys(object));
};
exports.getOwnPropertyNames = function (object) {
return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object));
};
} else {
exports.keys = keys;
exports.getOwnPropertyNames = getOwnPropertyNames;
}
function valueObject(value, key) {
return { value: value[key] };
}
if (typeof Object.getOwnPropertyDescriptor === 'function') {
try {
Object.getOwnPropertyDescriptor({ 'a': 1 }, 'a');
exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
} catch (e) {
exports.getOwnPropertyDescriptor = function (value, key) {
try {
return Object.getOwnPropertyDescriptor(value, key);
} catch (e) {
return valueObject(value, key);
}
};
}
} else {
exports.getOwnPropertyDescriptor = valueObject;
}
});
require.define('16', function(module, exports, __dirname, __filename, undefined){
module.exports = Transform;
var Duplex = require('15', module);
var util = require('12', module);
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined)
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
var ts = this._transformState = new TransformState(options, this);
var stream = this;
this._readableState.needReadable = true;
this._readableState.sync = false;
this.once('finish', function () {
if ('function' === typeof this._flush)
this._flush(function (er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
var ws = stream._writableState;
var rs = stream._readableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
});
require.define('15', function(module, exports, __dirname, __filename, undefined){
module.exports = Duplex;
var util = require('12', module);
var shims = require('18', module);
var timers = require('19', module);
var Readable = require('13', module);
var Writable = require('14', module);
util.inherits(Duplex, Readable);
shims.forEach(shims.keys(Writable.prototype), function (method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
function onend() {
if (this.allowHalfOpen || this._writableState.ended)
return;
timers.setImmediate(shims.bind(this.end, this));
}
});
require.define('14', function(module, exports, __dirname, __filename, undefined){
module.exports = Writable;
Writable.WritableState = WritableState;
var util = require('12', module);
var Stream = require('8', module);
var timers = require('19', module);
var Buffer = require('20', module).Buffer;
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
options = options || {};
var hwm = options.highWaterMark;
this.highWaterMark = hwm || hwm === 0 ? hwm : 16 * 1024;
this.objectMode = !!options.objectMode;
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
this.ending = false;
this.ended = false;
this.finished = false;
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
this.defaultEncoding = options.defaultEncoding || 'utf8';
this.length = 0;
this.writing = false;
this.sync = true;
this.bufferProcessing = false;
this.onwrite = function (er) {
onwrite(stream, er);
};
this.writecb = null;
this.writelen = 0;
this.buffer = [];
}
function Writable(options) {
if (!(this instanceof Writable) && !(this instanceof Stream.Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
this.writable = true;
Stream.call(this);
}
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
stream.emit('error', er);
timers.setImmediate(function () {
cb(er);
});
}
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!Buffer.isBuffer(chunk) && 'string' !== typeof chunk && chunk !== null && chunk !== undefined && !state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
timers.setImmediate(function () {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (typeof cb !== 'function')
cb = function () {
};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb))
ret = writeOrBuffer(this, state, chunk, encoding, cb);
return ret;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
state.needDrain = !ret;
if (state.writing)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
timers.setImmediate(function () {
cb(er);
});
else
cb(er);
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
var finished = needFinish(stream, state);
if (!finished && !state.bufferProcessing && state.buffer.length)
clearBuffer(stream, state);
if (sync) {
timers.setImmediate(function () {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
cb();
if (finished)
finishMaybe(stream, state);
}
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
function clearBuffer(stream, state) {
state.bufferProcessing = true;
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, len, chunk, encoding, cb);
if (state.writing) {
c++;
break;
}
}
state.bufferProcessing = false;
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (typeof chunk !== 'undefined' && chunk !== null)
this.write(chunk, encoding);
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return state.ending && state.length === 0 && !state.finished && !state.writing;
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
state.finished = true;
stream.emit('finish');
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
timers.setImmediate(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
});
require.define('20', function(module, exports, __dirname, __filename, undefined){
var assert;
exports.Buffer = Buffer;
exports.SlowBuffer = Buffer;
Buffer.poolSize = 8192;
exports.INSPECT_MAX_BYTES = 50;
function stringtrim(str) {
if (str.trim)
return str.trim();
return str.replace(/^\s+|\s+$/g, '');
}
function Buffer(subject, encoding, offset) {
if (!assert)
assert = require('21', module);
if (!(this instanceof Buffer)) {
return new Buffer(subject, encoding, offset);
}
this.parent = this;
this.offset = 0;
if (encoding == 'base64' && typeof subject == 'string') {
subject = stringtrim(subject);
while (subject.length % 4 != 0) {
subject = subject + '=';
}
}
var type;
if (typeof offset === 'number') {
this.length = coerce(encoding);
for (var i = 0; i < this.length; i++) {
this[i] = subject.get(i + offset);
}
} else {
switch (type = typeof subject) {
case 'number':
this.length = coerce(subject);
break;
case 'string':
this.length = Buffer.byteLength(subject, encoding);
break;
case 'object':
this.length = coerce(subject.length);
break;
default:
throw new Error('First argument needs to be a number, ' + 'array or string.');
}
if (isArrayIsh(subject)) {
for (var i = 0; i < this.length; i++) {
if (subject instanceof Buffer) {
this[i] = subject.readUInt8(i);
} else {
this[i] = subject[i];
}
}
} else if (type == 'string') {
this.length = this.write(subject, 0, encoding);
} else if (type === 'number') {
for (var i = 0; i < this.length; i++) {
this[i] = 0;
}
}
}
}
Buffer.prototype.get = function get(i) {
if (i < 0 || i >= this.length)
throw new Error('oob');
return this[i];
};
Buffer.prototype.set = function set(i, v) {
if (i < 0 || i >= this.length)
throw new Error('oob');
return this[i] = v;
};
Buffer.byteLength = function (str, encoding) {
switch (encoding || 'utf8') {
case 'hex':
return str.length / 2;
case 'utf8':
case 'utf-8':
return utf8ToBytes(str).length;
case 'ascii':
case 'binary':
return str.length;
case 'base64':
return base64ToBytes(str).length;
default:
throw new Error('Unknown encoding');
}
};
Buffer.prototype.utf8Write = function (string, offset, length) {
var bytes, pos;
return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length);
};
Buffer.prototype.asciiWrite = function (string, offset, length) {
var bytes, pos;
return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length);
};
Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite;
Buffer.prototype.base64Write = function (string, offset, length) {
var bytes, pos;
return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length);
};
Buffer.prototype.base64Slice = function (start, end) {
var bytes = Array.prototype.slice.apply(this, arguments);
return require('22', module).fromByteArray(bytes);
};
Buffer.prototype.utf8Slice = function () {
var bytes = Array.prototype.slice.apply(this, arguments);
var res = '';
var tmp = '';
var i = 0;
while (i < bytes.length) {
if (bytes[i] <= 127) {
res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]);
tmp = '';
} else
tmp += '%' + bytes[i].toString(16);
i++;
}
return res + decodeUtf8Char(tmp);
};
Buffer.prototype.asciiSlice = function () {
var bytes = Array.prototype.slice.apply(this, arguments);
var ret = '';
for (var i = 0; i < bytes.length; i++)
ret += String.fromCharCode(bytes[i]);
return ret;
};
Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice;
Buffer.prototype.inspect = function () {
var out = [], len = this.length;
for (var i = 0; i < len; i++) {
out[i] = toHex(this[i]);
if (i == exports.INSPECT_MAX_BYTES) {
out[i + 1] = '...';
break;
}
}
return '<Buffer ' + out.join(' ') + '>';
};
Buffer.prototype.hexSlice = function (start, end) {
var len = this.length;
if (!start || start < 0)
start = 0;
if (!end || end < 0 || end > len)
end = len;
var out = '';
for (var i = start; i < end; i++) {
out += toHex(this[i]);
}
return out;
};
Buffer.prototype.toString = function (encoding, start, end) {
encoding = String(encoding || 'utf8').toLowerCase();
start = +start || 0;
if (typeof end == 'undefined')
end = this.length;
if (+end == start) {
return '';
}
switch (encoding) {
case 'hex':
return this.hexSlice(start, end);
case 'utf8':
case 'utf-8':
return this.utf8Slice(start, end);
case 'ascii':
return this.asciiSlice(start, end);
case 'binary':
return this.binarySlice(start, end);
case 'base64':
return this.base64Slice(start, end);
case 'ucs2':
case 'ucs-2':
return this.ucs2Slice(start, end);
default:
throw new Error('Unknown encoding');
}
};
Buffer.prototype.hexWrite = function (string, offset, length) {
offset = +offset || 0;
var remaining = this.length - offset;
if (!length) {
length = remaining;
} else {
length = +length;
if (length > remaining) {
length = remaining;
}
}
var strLen = string.length;
if (strLen % 2) {
throw new Error('Invalid hex string');
}
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16);
if (isNaN(byte))
throw new Error('Invalid hex string');
this[offset + i] = byte;
}
Buffer._charsWritten = i * 2;
return i;
};
Buffer.prototype.write = function (string, offset, length, encoding) {
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length;
length