From 9176ef520f3ce2018aee2d37a09bab1dbdf43dcb Mon Sep 17 00:00:00 2001 From: pemrouz Date: Fri, 16 Dec 2016 15:48:17 +0000 Subject: [PATCH] chore: build dist --- dist/index.js | 38 +- dist/ripple.js | 64162 +++++++++++++++++++++++++++-------- dist/ripple.min.js | 30 +- dist/ripple.min.js.gz | Bin 55827 -> 208980 bytes dist/ripple.pure.js | 19334 ++++++++++- dist/ripple.pure.min.js | 9 +- dist/ripple.pure.min.js.gz | Bin 5722 -> 64230 bytes npm-shrinkwrap.json | 1119 - 8 files changed, 70127 insertions(+), 14565 deletions(-) delete mode 100644 npm-shrinkwrap.json diff --git a/dist/index.js b/dist/index.js index 3a5da56..5f712d3 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,10 +1,5 @@ 'use strict'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = create; - var _rijs = require('rijs.backpressure'); var _rijs2 = _interopRequireDefault(_rijs); @@ -49,30 +44,34 @@ var _rijs21 = require('rijs.serve'); var _rijs22 = _interopRequireDefault(_rijs21); -var _rijs23 = require('rijs.needs'); +var _rijs23 = require('rijs.pages'); var _rijs24 = _interopRequireDefault(_rijs23); -var _rijs25 = require('rijs.sync'); +var _rijs25 = require('rijs.needs'); var _rijs26 = _interopRequireDefault(_rijs25); -var _rijs27 = require('rijs.core'); +var _rijs27 = require('rijs.sync'); var _rijs28 = _interopRequireDefault(_rijs27); -var _rijs29 = require('rijs.data'); +var _rijs29 = require('rijs.core'); var _rijs30 = _interopRequireDefault(_rijs29); -var _rijs31 = require('rijs.css'); +var _rijs31 = require('rijs.data'); var _rijs32 = _interopRequireDefault(_rijs31); -var _rijs33 = require('rijs.fn'); +var _rijs33 = require('rijs.css'); var _rijs34 = _interopRequireDefault(_rijs33); +var _rijs35 = require('rijs.fn'); + +var _rijs36 = _interopRequireDefault(_rijs35); + var _client = require('utilise/client'); var _client2 = _interopRequireDefault(_client); @@ -82,22 +81,25 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de _client2.default && !window.ripple && create(); +module.exports = create; + function create(opts) { - var ripple = (0, _rijs28.default)(); // empty base collection of resources + var ripple = (0, _rijs30.default)(); // empty base collection of resources // enrich.. (0, _rijs8.default)(ripple); // exposes a single instance - (0, _rijs30.default)(ripple); // register data types - (0, _rijs32.default)(ripple); // register css types - (0, _rijs34.default)(ripple); // register fn types + (0, _rijs32.default)(ripple); // register data types + (0, _rijs34.default)(ripple); // register css types + (0, _rijs36.default)(ripple); // register fn types (0, _rijs16.default)(ripple); // expose helper functions and constants (0, _rijs4.default)(ripple); // invoke web components, fn.call(, data) - (0, _rijs24.default)(ripple); // define default attrs for components + (0, _rijs26.default)(ripple); // define default attrs for components (0, _rijs18.default)(ripple); // preapplies scoped css - (0, _rijs22.default)(ripple, opts); // serve client libraries (0, _rijs14.default)(ripple); // loads/saves from/to localstorage - (0, _rijs26.default)(ripple, opts); // syncs resources between server/client + (0, _rijs28.default)(ripple, opts); // syncs resources between server/client (0, _rijs2.default)(ripple); // restricts broadcast to clients based on need + (0, _rijs22.default)(ripple, opts); // serve client libraries + (0, _rijs24.default)(ripple, opts); // serve pages directory (0, _rijs12.default)(ripple); // extend components with features (0, _rijs6.default)(ripple); // versioning info and time travel (0, _rijs10.default)(ripple, opts); // populates sessionid on each connection diff --git a/dist/ripple.js b/dist/ripple.js index 14de209..01029ee 100644 --- a/dist/ripple.js +++ b/dist/ripple.js @@ -1,15211 +1,52795 @@ (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, data) - (0, _rijs24.default)(ripple); // define default attrs for components - (0, _rijs18.default)(ripple); // preapplies scoped css - (0, _rijs22.default)(ripple, opts); // serve client libraries - (0, _rijs14.default)(ripple); // loads/saves from/to localstorage - (0, _rijs26.default)(ripple, opts); // syncs resources between server/client - (0, _rijs2.default)(ripple); // restricts broadcast to clients based on need - (0, _rijs12.default)(ripple); // extend components with features - (0, _rijs6.default)(ripple); // versioning info and time travel - (0, _rijs10.default)(ripple, opts); // populates sessionid on each connection - (0, _rijs20.default)(ripple, opts); // loads from resources folder +// ------------------------------------------- +// Applies backpressure on the flow of streams +// ------------------------------------------- +function backpressure(ripple) { + log('creating'); + if (!ripple.io) return ripple; + if (true) { + ripple.render = render(ripple)(ripple.render); + ripple.pull = pull(ripple); + ripple.deps = deps; + ripple.requested = {}; + ripple.io.on('connect', refresh(ripple)); + ripple.io.on('reconnect', reconnect(ripple)); + (0, _ready2.default)(start(ripple)); + return ripple; + } + ripple.to = limit(ripple.to); + ripple.from = track(ripple)(ripple.from); + ripple.io.use(function (socket, next) { + socket.deps = {}, next(); + }); return ripple; } -},{"rijs.backpressure":75,"rijs.components":76,"rijs.core":79,"rijs.css":81,"rijs.data":82,"rijs.features":83,"rijs.fn":84,"rijs.helpers":85,"rijs.needs":86,"rijs.offline":87,"rijs.precss":88,"rijs.resdir":194,"rijs.serve":195,"rijs.sessions":196,"rijs.singleton":89,"rijs.sync":90,"rijs.versioned":91,"utilise":146}],2:[function(require,module,exports){ -module.exports = after - -function after(count, callback, err_cb) { - var bail = false - err_cb = err_cb || noop - proxy.count = count +var start = function start(ripple) { + return function (d) { + return scan(ripple)(document.body); + }; +}; - return (count === 0) ? callback() : proxy +var scan = function scan(ripple) { + return function (el) { + return !el ? undefined : ((0, _all2.default)('*', el).filter((0, _by2.default)('nodeName', (0, _includes2.default)('-'))).filter((0, _by2.default)('nodeName', function (d) { + return !_is2.default.in(ripple.requested)((0, _lo2.default)(d)); + })).map(ripple.draw), el); + }; +}; - function proxy(err, result) { - if (proxy.count <= 0) { - throw new Error('after called too many times') - } - --proxy.count +var track = function track(ripple) { + return function (next) { + return function (req, res) { + var name = req.name, + type = req.type, + socket = req.socket, + send = ripple.send, + exists = name in socket.deps; - // after first error, rest are passed to err_cb - if (err) { - bail = true - callback(err) - // future error callbacks will go to error handler - callback = err_cb - } else if (proxy.count === 0 && !bail) { - callback(null, result) - } - } -} -function noop() {} + if (!(name in ripple.resources)) return; + if (type === 'pull') { + socket.deps[name] = 1; + send(socket)(name); + } + return (next || _identity2.default)(req, res); + }; + }; +}; -},{}],3:[function(require,module,exports){ -/** - * An abstraction for slicing an arraybuffer even when - * ArrayBuffer.prototype.slice is not supported - * - * @api public - */ +var reconnect = function reconnect(_ref) { + var io = _ref.io; + return function (d) { + return io.io.disconnect(), io.io.connect(); + }; +}; -module.exports = function(arraybuffer, start, end) { - var bytes = arraybuffer.byteLength; - start = start || 0; - end = end || bytes; +var refresh = function refresh(ripple) { + return function (d) { + return (0, _group2.default)('refreshing', function (d) { + return (0, _values2.default)(ripple.resources).map(function (d) { + return d.name; + }).map(ripple.pull); + }); + }; +}; - if (arraybuffer.slice) { return arraybuffer.slice(start, end); } +var pull = function pull(ripple) { + return function (name, node) { + if (node instanceof Element) { + var original = (0, _attr2.default)('data')(node) || ''; + if (!original.split(' ').some((0, _is2.default)(name))) (0, _attr2.default)('data', (original + ' ' + name).trim())(node); + } - if (start < 0) { start += bytes; } - if (end < 0) { end += bytes; } - if (end > bytes) { end = bytes; } + if (!(name in ripple.requested)) { + log('pulling', name); + ripple.requested[name] = ripple.send({ name: name, type: 'pull' }); + } - if (start >= bytes || start >= end || bytes === 0) { - return new ArrayBuffer(0); - } + return name in ripple.resources ? promise(ripple(name)) : ripple.requested[name]; + }; +}; - var abv = new Uint8Array(arraybuffer); - var result = new Uint8Array(end - start); - for (var i = start, ii = 0; i < end; i++, ii++) { - result[ii] = abv[i]; - } - return result.buffer; +var limit = function limit(next) { + return function (req) { + return req.name in req.socket.deps ? (next || _identity2.default)(req) : false; + }; }; -},{}],4:[function(require,module,exports){ +var deps = function deps(el) { + return format([(0, _key2.default)('nodeName'), (0, _attr2.default)('data'), (0, _attr2.default)('css'), (0, _attr2.default)('is')])(el); +}; -/** - * Expose `Backoff`. - */ +var format = function format(arr) { + return function (el) { + return arr.map(function (extract) { + return extract(el); + }).filter(Boolean).map(_lo2.default).map((0, _split2.default)(' ')).reduce(_flatten2.default, []).filter(_unique2.default); + }; +}; -module.exports = Backoff; +var render = function render(ripple) { + return function (next) { + return function (el) { + return ripple.deps(el).filter((0, _not2.default)(_is2.default.in(ripple.requested))).map(ripple.pull).length ? false : scan(ripple)(next(el)); + }; + }; +}; -/** - * Initialize backoff timer with `opts`. - * - * - `min` initial timeout in milliseconds [100] - * - `max` max timeout [10000] - * - `jitter` [0] - * - `factor` [2] - * - * @param {Object} opts - * @api public - */ +var log = require('utilise/log')('[ri/back]'), + err = require('utilise/err')('[ri/back]'); +},{"utilise/all":2,"utilise/attr":3,"utilise/by":4,"utilise/err":7,"utilise/flatten":8,"utilise/from":9,"utilise/group":10,"utilise/identity":11,"utilise/includes":12,"utilise/is":13,"utilise/key":14,"utilise/lo":16,"utilise/log":17,"utilise/noop":18,"utilise/not":19,"utilise/ready":21,"utilise/split":22,"utilise/unique":25,"utilise/values":26}],2:[function(require,module,exports){ +var to = require('./to') -function Backoff(opts) { - opts = opts || {}; - this.ms = opts.min || 100; - this.max = opts.max || 10000; - this.factor = opts.factor || 2; - this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; - this.attempts = 0; +module.exports = function all(selector, doc){ + var prefix = !doc && document.head.createShadowRoot ? 'html /deep/ ' : '' + return to.arr((doc || document).querySelectorAll(prefix+selector)) } +},{"./to":24}],3:[function(require,module,exports){ +var is = require('./is') -/** - * Return the backoff duration. - * - * @return {Number} - * @api public - */ +module.exports = function attr(name, value) { + var args = arguments.length + + return !is.str(name) && args == 2 ? attr(arguments[1]).call(this, arguments[0]) + : !is.str(name) && args == 3 ? attr(arguments[1], arguments[2]).call(this, arguments[0]) + : function(el){ + var ctx = this || {} + el = ctx.nodeName || is.fn(ctx.node) ? ctx : el + el = el.node ? el.node() : el + el = el.host || el -Backoff.prototype.duration = function(){ - var ms = this.ms * Math.pow(this.factor, this.attempts++); - if (this.jitter) { - var rand = Math.random(); - var deviation = Math.floor(rand * this.jitter * ms); - ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; - } - return Math.min(ms, this.max) | 0; -}; + return args > 1 && value === false ? el.removeAttribute(name) + : args > 1 ? (el.setAttribute(name, value), value) + : el.attributes.getNamedItem(name) + && el.attributes.getNamedItem(name).value + } +} -/** - * Reset the number of attempts. - * - * @api public - */ - -Backoff.prototype.reset = function(){ - this.attempts = 0; -}; - -/** - * Set the minimum duration - * - * @api public - */ - -Backoff.prototype.setMin = function(min){ - this.ms = min; -}; - -/** - * Set the maximum duration - * - * @api public - */ +},{"./is":13}],4:[function(require,module,exports){ +var key = require('./key') + , is = require('./is') -Backoff.prototype.setMax = function(max){ - this.max = max; -}; +module.exports = function by(k, v){ + var exists = arguments.length == 1 + return function(o){ + var d = is.fn(k) ? k(o) : key(k)(o) + + return d && v && d.toLowerCase && v.toLowerCase ? d.toLowerCase() === v.toLowerCase() + : exists ? Boolean(d) + : is.fn(v) ? v(d) + : d == v + } +} +},{"./is":13,"./key":14}],5:[function(require,module,exports){ +module.exports = typeof window != 'undefined' +},{}],6:[function(require,module,exports){ +module.exports = function datum(node){ + return node.__data__ +} +},{}],7:[function(require,module,exports){ +var is = require('./is') + , to = require('./to') + , owner = require('./owner') -/** - * Set the jitter - * - * @api public - */ +module.exports = function err(ns){ + return function(d){ + if (!owner.console || !console.error.apply) return d; + is.arr(arguments[2]) && (arguments[2] = arguments[2].length) + var args = to.arr(arguments) + , prefix = '[err][' + (new Date()).toISOString() + ']' + ns -Backoff.prototype.setJitter = function(jitter){ - this.jitter = jitter; -}; + args.unshift(prefix.red ? prefix.red : prefix) + return console.error.apply(console, args), d + } +} +},{"./is":13,"./owner":20,"./to":24}],8:[function(require,module,exports){ +var is = require('./is') +module.exports = function flatten(p,v){ + is.arr(v) && (v = v.reduce(flatten, [])) + return (p = p || []), p.concat(v) +} -},{}],5:[function(require,module,exports){ -/* - * base64-arraybuffer - * https://github.com/niklasvh/base64-arraybuffer - * - * Copyright (c) 2012 Niklas von Hertzen - * Licensed under the MIT license. - */ -(function(){ - "use strict"; +},{"./is":13}],9:[function(require,module,exports){ +var datum = require('./datum') + , key = require('./key') - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +module.exports = from +from.parent = fromParent - // Use a lookup table to find the index. - var lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; +function from(o){ + return function(k){ + return key(k)(o) } +} - exports.encode = function(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), - i, len = bytes.length, base64 = ""; - - for (i = 0; i < len; i+=3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += chars[bytes[i + 2] & 63]; - } - - if ((len % 3) === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; - } +function fromParent(k){ + return datum(this.parentNode)[k] +} +},{"./datum":6,"./key":14}],10:[function(require,module,exports){ +var client = require('./client') + , owner = require('./owner') + , noop = require('./noop') - return base64; - }; +module.exports = function group(prefix, fn){ + if (!owner.console) return fn() + if (!console.groupCollapsed) polyfill() + console.groupCollapsed(prefix) + var ret = fn() + console.groupEnd(prefix) + return ret +} - exports.decode = function(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, i, p = 0, - encoded1, encoded2, encoded3, encoded4; +function polyfill() { + console.groupCollapsed = console.groupEnd = function(d){ + (console.log || noop)('*****', d, '*****') + } +} +},{"./client":5,"./noop":18,"./owner":20}],11:[function(require,module,exports){ +module.exports = function identity(d) { + return d +} +},{}],12:[function(require,module,exports){ +module.exports = function includes(pattern){ + return function(d){ + return d && d.indexOf && ~d.indexOf(pattern) + } +} +},{}],13:[function(require,module,exports){ +module.exports = is +is.fn = isFunction +is.str = isString +is.num = isNumber +is.obj = isObject +is.lit = isLiteral +is.bol = isBoolean +is.truthy = isTruthy +is.falsy = isFalsy +is.arr = isArray +is.null = isNull +is.def = isDef +is.in = isIn +is.promise = isPromise - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; - } - } +function is(v){ + return function(d){ + return d == v + } +} - var arraybuffer = new ArrayBuffer(bufferLength), - bytes = new Uint8Array(arraybuffer); +function isFunction(d) { + return typeof d == 'function' +} - for (i = 0; i < len; i+=4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i+1)]; - encoded3 = lookup[base64.charCodeAt(i+2)]; - encoded4 = lookup[base64.charCodeAt(i+3)]; +function isBoolean(d) { + return typeof d == 'boolean' +} - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } +function isString(d) { + return typeof d == 'string' +} - return arraybuffer; - }; -})(); +function isNumber(d) { + return typeof d == 'number' +} -},{}],6:[function(require,module,exports){ -'use strict' +function isObject(d) { + return typeof d == 'object' +} -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray +function isLiteral(d) { + return typeof d == 'object' + && !(d instanceof Array) +} -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +function isTruthy(d) { + return !!d == true +} -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i +function isFalsy(d) { + return !!d == false } -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 +function isArray(d) { + return d instanceof Array +} -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +function isNull(d) { + return d === null +} - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +function isDef(d) { + return typeof d !== 'undefined' } -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) +function isPromise(d) { + return d instanceof Promise } -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) +function isIn(set) { + return function(d){ + return !set ? false + : set.indexOf ? ~set.indexOf(d) + : d in set + } +} +},{}],14:[function(require,module,exports){ +var str = require('./str') + , is = require('./is') - arr = new Arr(len * 3 / 4 - placeHolders) +module.exports = function key(k, v){ + var set = arguments.length > 1 + , keys = is.fn(k) ? [] : str(k).split('.') + , root = keys.shift() - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len + return function deep(o, i){ + var masked = {} + + return !o ? undefined + : !is.num(k) && !k ? o + : is.arr(k) ? (k.map(copy), masked) + : o[k] || !keys.length ? (set ? ((o[k] = is.fn(v) ? v(o[k], i) : v), o) + : (is.fn(k) ? k(o) : o[k])) + : (set ? (key(keys.join('.'), v)(o[root] ? o[root] : (o[root] = {})), o) + : key(keys.join('.'))(o[root])) - var L = 0 + function copy(k){ + var val = key(k)(o) + ;(val != undefined) && key(k, val)(masked) + } + } +} +},{"./is":13,"./str":23}],15:[function(require,module,exports){ +var is = require('./is') - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF +module.exports = function keys(o) { + return Object.keys(is.obj(o) || is.fn(o) ? o : {}) +} +},{"./is":13}],16:[function(require,module,exports){ +module.exports = function lo(d){ + return (d || '').toLowerCase() +} + +},{}],17:[function(require,module,exports){ +var is = require('./is') + , to = require('./to') + , owner = require('./owner') + +module.exports = function log(ns){ + return function(d){ + if (!owner.console || !console.log.apply) return d; + is.arr(arguments[2]) && (arguments[2] = arguments[2].length) + var args = to.arr(arguments) + , prefix = '[log][' + (new Date()).toISOString() + ']' + ns + + args.unshift(prefix.grey ? prefix.grey : prefix) + return console.log.apply(console, args), d + } +} +},{"./is":13,"./owner":20,"./to":24}],18:[function(require,module,exports){ +module.exports = function noop(){} +},{}],19:[function(require,module,exports){ +module.exports = function not(fn){ + return function(){ + return !fn.apply(this, arguments) } +} +},{}],20:[function(require,module,exports){ +(function (global){ +var client = require('./client') +module.exports = client ? /* istanbul ignore next */ window : global +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./client":5}],21:[function(require,module,exports){ +module.exports = function ready(fn){ + return document.body ? fn() : document.addEventListener('DOMContentLoaded', fn.bind(this)) +} - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF +},{}],22:[function(require,module,exports){ +module.exports = function split(delimiter){ + return function(d){ + return d.split(delimiter) } +} - return arr +},{}],23:[function(require,module,exports){ +var is = require('./is') + +module.exports = function str(d){ + return d === 0 ? '0' + : !d ? '' + : is.fn(d) ? '' + d + : is.obj(d) ? JSON.stringify(d) + : String(d) } +},{"./is":13}],24:[function(require,module,exports){ +const is = require('./is') -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +module.exports = { + arr: toArray +, obj: toObject } -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') +function toArray(d){ + return Array.prototype.slice.call(d, 0) } -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 +function toObject(d) { + var by = 'id' + , o = {} - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } + return arguments.length == 1 + ? (by = d, reduce) + : reduce.apply(this, arguments) - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' + function reduce(p,v,i){ + if (i === 0) p = {} + p[is.fn(by) ? by(v, i) : v[by]] = v + return p } +} +},{"./is":13}],25:[function(require,module,exports){ +var is = require('./is') - parts.push(output) +module.exports = function unique(d, i){ + if (!i) unique.matched = [] + return !is.in(unique.matched)(d) + ? unique.matched.push(d) + : false +} - return parts.join('') +},{"./is":13}],26:[function(require,module,exports){ +var keys = require('./keys') + , from = require('./from') + +module.exports = function values(o) { + return !o ? [] : keys(o).map(from(o)) } +},{"./from":9,"./keys":15}],27:[function(require,module,exports){ +'use strict'; -},{}],7:[function(require,module,exports){ -(function (global){ -/** - * Create a blob builder even when vendor prefixes exist - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = components; -var BlobBuilder = global.BlobBuilder - || global.WebKitBlobBuilder - || global.MSBlobBuilder - || global.MozBlobBuilder; +var _overwrite = require('utilise/overwrite'); -/** - * Check if Blob constructor is supported - */ +var _overwrite2 = _interopRequireDefault(_overwrite); -var blobSupported = (function() { - try { - var a = new Blob(['hi']); - return a.size === 2; - } catch(e) { - return false; - } -})(); +var _includes = require('utilise/includes'); -/** - * Check if Blob constructor supports ArrayBufferViews - * Fails in Safari 6, so we need to map to ArrayBuffers there. - */ +var _includes2 = _interopRequireDefault(_includes); -var blobSupportsArrayBufferView = blobSupported && (function() { - try { - var b = new Blob([new Uint8Array([1,2])]); - return b.size === 2; - } catch(e) { - return false; - } -})(); +var _header = require('utilise/header'); -/** - * Check if BlobBuilder is supported - */ +var _header2 = _interopRequireDefault(_header); -var blobBuilderSupported = BlobBuilder - && BlobBuilder.prototype.append - && BlobBuilder.prototype.getBlob; -/** - * Helper function that maps ArrayBufferViews to ArrayBuffers - * Used by BlobBuilder constructor and old browsers that didn't - * support it in the Blob constructor. - */ -function mapArrayBufferViews(ary) { - for (var i = 0; i < ary.length; i++) { - var chunk = ary[i]; - if (chunk.buffer instanceof ArrayBuffer) { - var buf = chunk.buffer; +var _values = require('utilise/values'); - // if this is a subarray, make a copy so we only - // include the subarray region from the underlying buffer - if (chunk.byteLength !== buf.byteLength) { - var copy = new Uint8Array(chunk.byteLength); - copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); - buf = copy.buffer; - } +var _values2 = _interopRequireDefault(_values); - ary[i] = buf; - } - } -} +var _proxy = require('utilise/proxy'); -function BlobBuilderConstructor(ary, options) { - options = options || {}; +var _proxy2 = _interopRequireDefault(_proxy); - var bb = new BlobBuilder(); - mapArrayBufferViews(ary); +var _attr = require('utilise/attr'); - for (var i = 0; i < ary.length; i++) { - bb.append(ary[i]); - } +var _attr2 = _interopRequireDefault(_attr); - return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); -}; +var _noop = require('utilise/noop'); -function BlobConstructor(ary, options) { - mapArrayBufferViews(ary); - return new Blob(ary, options || {}); -}; +var _noop2 = _interopRequireDefault(_noop); -module.exports = (function() { - if (blobSupported) { - return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; - } else if (blobBuilderSupported) { - return BlobBuilderConstructor; - } else { - return undefined; - } -})(); +var _time = require('utilise/time'); -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],8:[function(require,module,exports){ +var _time2 = _interopRequireDefault(_time); -},{}],9:[function(require,module,exports){ -arguments[4][8][0].apply(exports,arguments) -},{"dup":8}],10:[function(require,module,exports){ -(function (global){ -'use strict'; +var _key = require('utilise/key'); -var buffer = require('buffer'); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; -} -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - return new Buffer(size); -} -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); - } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); - } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); - } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); - } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); - } - } - - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); -} -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); - } - return new SlowBuffer(size); -} +var _key2 = _interopRequireDefault(_key); -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"buffer":11}],11:[function(require,module,exports){ -(function (global){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ +var _all = require('utilise/all'); -'use strict' +var _all2 = _interopRequireDefault(_all); -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var isArray = require('isarray') +var _is = require('utilise/is'); -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 +var _is2 = _interopRequireDefault(_is); -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. +var _lo = require('utilise/lo'); - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() +var _lo2 = _interopRequireDefault(_lo); -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() +var _data = require('./types/data'); -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} +var _data2 = _interopRequireDefault(_data); -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} +var _fn = require('./types/fn'); -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } +var _fn2 = _interopRequireDefault(_fn); - return that -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ +// ------------------------------------------- +// API: Renders specific nodes, resources or everything +// ------------------------------------------- +// ripple.draw() - redraw all components on page +// ripple.draw(element) - redraw specific element +// ripple.draw.call(element) - redraw specific element +// ripple.draw.call(selection) - redraw D3 selection +// ripple.draw('name') - redraw elements that depend on resource +// ripple.draw({ ... }) - redraw elements that depend on resource +// MutationObserver(ripple.draw) - redraws element being observed -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } +function components(ripple) { + if (!true) return ripple; + log('creating'); - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) + (0, _values2.default)(ripple.types).map(function (type) { + return type.parse = (0, _proxy2.default)(type.parse, clean(ripple)); + }); + (0, _key2.default)('types.application/javascript.render', function (d) { + return (0, _fn2.default)(ripple); + })(ripple); + (0, _key2.default)('types.application/data.render', function (d) { + return (0, _data2.default)(ripple); + })(ripple); + ripple.draw = Node.prototype.draw = draw(ripple); + ripple.render = render(ripple); + ripple.on('change.draw', ripple.draw); + (0, _time2.default)(0, ripple.draw); + return ripple; } -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr +// public draw api +function draw(ripple) { + return function (thing) { + return this && this.nodeName ? invoke(ripple)(this) : this && this.node ? invoke(ripple)(this.node()) : !thing ? everything(ripple) : thing instanceof mutation ? invoke(ripple)(thing.target) : thing[0] instanceof mutation ? invoke(ripple)(thing[0].target) : thing.nodeName ? invoke(ripple)(thing) : thing.node ? invoke(ripple)(thing.node()) : thing.name ? resource(ripple)(thing.name) : _is2.default.str(thing) ? resource(ripple)(thing) : err('could not update', thing); + }; } -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } +// render all components +var everything = function everything(ripple) { + var selector = (0, _values2.default)(ripple.resources).filter((0, _header2.default)('content-type', 'application/javascript')).map((0, _key2.default)('name')).join(','); - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } + return !selector ? [] : (0, _all2.default)(selector).map(invoke(ripple)); +}; - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } +// render all elements that depend on the resource +var resource = function resource(ripple) { + return function (name) { + var res = ripple.resources[name], + type = (0, _header2.default)('content-type')(res); - return fromObject(that, value) -} + return (ripple.types[type].render || _noop2.default)(res); + }; +}; -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} +// batch renders on render frames +var batch = function batch(ripple) { + return function (el) { + if (!el.pending) { + el.pending = []; + requestAnimationFrame(function (d) { + el.changes = el.pending; + delete el.pending; + ripple.render(el); + }); + } -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} + if (ripple.change) el.pending.push(ripple.change[1]); + }; +}; -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} +// main function to render a particular custom element with any data it needs +var invoke = function invoke(ripple) { + return function (el) { + if (!(0, _includes2.default)('-')(el.nodeName)) return; + if (el.nodeName == '#document-fragment') return invoke(ripple)(el.host); + if (el.nodeName == '#text') return invoke(ripple)(el.parentNode); + if (!el.matches(isAttached)) return; + if ((0, _attr2.default)(el, 'inert') != null) return; + return batch(ripple)(el), el; + }; +}; -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} +var render = function render(ripple) { + return function (el) { + var name = (0, _lo2.default)(el.tagName), + deps = (0, _attr2.default)(el, 'data'), + fn = body(ripple)(name), + data = bodies(ripple)(deps), + root = el.shadowRoot || el; -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} + if (!fn) return el; + if (deps && !data) return el; -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 + try { + fn.call(root, root, defaults(el, data)); + } catch (e) { + err(e, e.stack); } - } - return that -} -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} + return el; + }; +}; -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } +// clean local headers for transport +var clean = function clean(ripple) { + return function (res) { + return delete res.headers.pending, res; + }; +}; - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } +// helpers +var defaults = function defaults(el, data) { + el.state = el.state || {}; + (0, _overwrite2.default)(el.state)(data); + (0, _overwrite2.default)(el.state)(el.__data__); + el.__data__ = el.state; + return el.state; +}; - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) +var bodies = function bodies(ripple) { + return function (deps) { + var o = {}, + names = deps ? deps.split(' ') : []; - var actual = that.write(string, encoding) + names.map(function (d) { + return o[d] = body(ripple)(d); + }); - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } + return !names.length ? undefined : (0, _values2.default)(o).some(_is2.default.falsy) ? undefined : o; + }; +}; - return that -} +var body = function body(ripple) { + return function (name) { + return ripple.resources[name] && ripple.resources[name].body; + }; +}; -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} +var index = function index(el) { + return Array.prototype.indexOf.call((0, _key2.default)('parentNode.children')(el) || [], el); +}; -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer +var log = require('utilise/log')('[ri/components]'), + err = require('utilise/err')('[ri/components]'), + mutation = true && window.MutationRecord || _noop2.default, + customs = true && !!document.registerElement, + isAttached = customs ? 'html *, :host-context(html) *' : 'html *'; +true && (Element.prototype.matches = Element.prototype.matches || Element.prototype.msMatchesSelector); +},{"./types/data":28,"./types/fn":29,"utilise/all":30,"utilise/attr":31,"utilise/err":35,"utilise/header":37,"utilise/includes":39,"utilise/is":40,"utilise/key":41,"utilise/lo":43,"utilise/log":44,"utilise/noop":45,"utilise/overwrite":46,"utilise/proxy":48,"utilise/time":50,"utilise/values":52}],28:[function(require,module,exports){ +'use strict'; - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = data; - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } +var _all = require('utilise/all'); - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } +var _all2 = _interopRequireDefault(_all); - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// render all elements that require the specified data +function data(ripple) { + return function (res) { + return (0, _all2.default)('[data~="' + res.name + '"]:not([inert])').map(ripple.draw); + }; } +},{"utilise/all":30}],29:[function(require,module,exports){ +'use strict'; -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = fn; - if (that.length === 0) { - return that - } +var _includes = require('utilise/includes'); - obj.copy(that, 0, 0, len) - return that - } +var _includes2 = _interopRequireDefault(_includes); - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} +var _all = require('utilise/all'); -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} +var _all2 = _interopRequireDefault(_all); -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} +// register custom element prototype (render is automatic) +function fn(ripple) { + return function (res) { + if (!customs || !customEl(res) || registered(res)) return (0, _all2.default)(res.name + ':not([inert])\n ,[is="' + res.name + '"]:not([inert])').map(ripple.draw); -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + var proto = Object.create(HTMLElement.prototype), + opts = { prototype: proto }; - if (a === b) return 0 + proto.attachedCallback = ripple.draw; + document.registerElement(res.name, opts); + }; +} - var x = a.length - var y = b.length +var registered = function registered(res) { + return document.createElement(res.name).attachedCallback; +}; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } +var customs = true && !!document.registerElement, + customEl = function customEl(d) { + return (0, _includes2.default)('-')(d.name); +}; +},{"utilise/all":30,"utilise/includes":39}],30:[function(require,module,exports){ +arguments[4][2][0].apply(exports,arguments) +},{"./to":51,"dup":2}],31:[function(require,module,exports){ +arguments[4][3][0].apply(exports,arguments) +},{"./is":40,"dup":3}],32:[function(require,module,exports){ +arguments[4][5][0].apply(exports,arguments) +},{"dup":5}],33:[function(require,module,exports){ +module.exports = function copy(from, to){ + return function(d){ + return to[d] = from[d], d } - - if (x < y) return -1 - if (y < x) return 1 - return 0 } +},{}],34:[function(require,module,exports){ +arguments[4][6][0].apply(exports,arguments) +},{"dup":6}],35:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"./is":40,"./owner":47,"./to":51,"dup":7}],36:[function(require,module,exports){ +arguments[4][9][0].apply(exports,arguments) +},{"./datum":34,"./key":41,"dup":9}],37:[function(require,module,exports){ +var key = require('./key') -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false +module.exports = function header(header, value) { + var getter = arguments.length == 1 + return function(d){ + return !d || !d.headers ? null + : getter ? key(header)(d.headers) + : key(header)(d.headers) == value } } +},{"./key":41}],38:[function(require,module,exports){ +arguments[4][11][0].apply(exports,arguments) +},{"dup":11}],39:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"dup":12}],40:[function(require,module,exports){ +arguments[4][13][0].apply(exports,arguments) +},{"dup":13}],41:[function(require,module,exports){ +arguments[4][14][0].apply(exports,arguments) +},{"./is":40,"./str":49,"dup":14}],42:[function(require,module,exports){ +arguments[4][15][0].apply(exports,arguments) +},{"./is":40,"dup":15}],43:[function(require,module,exports){ +arguments[4][16][0].apply(exports,arguments) +},{"dup":16}],44:[function(require,module,exports){ +arguments[4][17][0].apply(exports,arguments) +},{"./is":40,"./owner":47,"./to":51,"dup":17}],45:[function(require,module,exports){ +arguments[4][18][0].apply(exports,arguments) +},{"dup":18}],46:[function(require,module,exports){ +var is = require('./is') + , keys = require('./keys') + , copy = require('./copy') -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') +module.exports = function overwrite(to){ + return function(from){ + keys(from) + .map(copy(from, to)) + + return to } +} +},{"./copy":33,"./is":40,"./keys":42}],47:[function(require,module,exports){ +arguments[4][20][0].apply(exports,arguments) +},{"./client":32,"dup":20}],48:[function(require,module,exports){ +var is = require('./is') + , identity = require('./identity') - if (list.length === 0) { - return Buffer.alloc(0) +module.exports = function proxy(fn, ret, ctx){ + return function(){ + var result = (fn || identity).apply(ctx || this, arguments) + return is.fn(ret) ? ret.call(ctx || this, result) : ret || result } +} +},{"./identity":38,"./is":40}],49:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"./is":40,"dup":23}],50:[function(require,module,exports){ +module.exports = function time(ms, fn) { + return arguments.length === 1 + ? setTimeout(ms) + : setTimeout(fn, ms) +} +},{}],51:[function(require,module,exports){ +var is = require('./is') - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } +module.exports = { + arr: toArray +, obj: toObject +} - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer +function toArray(d){ + return Array.prototype.slice.call(d, 0) } -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } +function toObject(d) { + var by = 'id' + , o = {} - var len = string.length - if (len === 0) return 0 + return arguments.length == 1 + ? (by = d, reduce) + : reduce.apply(this, arguments) - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } + function reduce(p,v,i){ + if (i === 0) p = {} + p[is.fn(by) ? by(v, i) : v[by]] = v + return p } } -Buffer.byteLength = byteLength +},{"./is":40}],52:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"./from":36,"./keys":42,"dup":26}],53:[function(require,module,exports){ +'use strict'; -function slowToString (encoding, start, end) { - var loweredCase = false +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = core; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. +var _emitterify = require('utilise/emitterify'); - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } +var _emitterify2 = _interopRequireDefault(_emitterify); - if (end === undefined || end > this.length) { - end = this.length - } +var _colorfill = require('utilise/colorfill'); - if (end <= 0) { - return '' - } +var _colorfill2 = _interopRequireDefault(_colorfill); - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 +var _identity = require('utilise/identity'); - if (end <= start) { - return '' - } +var _identity2 = _interopRequireDefault(_identity); - if (!encoding) encoding = 'utf8' +var _header = require('utilise/header'); - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) +var _header2 = _interopRequireDefault(_header); - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) +var _values = require('utilise/values'); - case 'ascii': - return asciiSlice(this, start, end) +var _values2 = _interopRequireDefault(_values); - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) +var _key = require('utilise/key'); - case 'base64': - return base64Slice(this, start, end) +var _key2 = _interopRequireDefault(_key); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) +var _is = require('utilise/is'); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} +var _is2 = _interopRequireDefault(_is); -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true +var _to = require('utilise/to'); -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} +var _to2 = _interopRequireDefault(_to); -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} +var _za = require('utilise/za'); -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} +var _za2 = _interopRequireDefault(_za); -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} +var _text = require('./types/text'); -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} +var _text2 = _interopRequireDefault(_text); -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' +// ------------------------------------------- +// API: Gets or sets a resource +// ------------------------------------------- +// ripple('name') - returns the resource body if it exists +// ripple('name') - creates & returns resource if it doesn't exist +// ripple('name', {}) - creates & returns resource, with specified name and body +// ripple({ ... }) - creates & returns resource, with specified name, body and headers +// ripple.resources - returns raw resources +// ripple.resource - alias for ripple, returns ripple instead of resource for method chaining +// ripple.register - alias for ripple +// ripple.on - event listener for changes - all resources +// ripple('name').on - event listener for changes - resource-specific + +function core() { + log('creating'); + + var resources = {}; + ripple.resources = resources; + ripple.resource = chainable(ripple); + ripple.register = ripple; + ripple.types = types(); + return (0, _emitterify2.default)(ripple); + + function ripple(name, body, headers) { + return !name ? ripple : _is2.default.arr(name) ? name.map(ripple) : _is2.default.obj(name) && !name.name ? ripple((0, _values2.default)(name)) : _is2.default.fn(name) && name.resources ? ripple((0, _values2.default)(name.resources)) : _is2.default.str(name) && !body && resources[name] ? resources[name].body : _is2.default.str(name) && !body && !resources[name] ? register(ripple)({ name: name }) : _is2.default.str(name) && body ? register(ripple)({ name: name, body: body, headers: headers }) : _is2.default.obj(name) && !_is2.default.arr(name) ? register(ripple)(name) : (err('could not find or create resource', name), false); } - return '' } -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } +var register = function register(ripple) { + return function (_ref) { + var name = _ref.name; + var body = _ref.body; + var _ref$headers = _ref.headers; + var headers = _ref$headers === undefined ? {} : _ref$headers; - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } + log('registering', name); + var res = normalise(ripple)({ name: name, body: body, headers: headers }); - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + if (!res) return err('failed to register', name), false; + ripple.resources[name] = res; + ripple.emit('change', [name, { + type: 'update', + value: res.body, + time: now(res) + }]); + return ripple.resources[name].body; + }; +}; - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } +var normalise = function normalise(ripple) { + return function (res) { + if (!(0, _header2.default)('content-type')(res)) (0, _values2.default)(ripple.types).sort((0, _za2.default)('priority')).some(contentType(res)); + if (!(0, _header2.default)('content-type')(res)) return err('could not understand resource', res), false; + return parse(ripple)(res); + }; +}; - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 +var parse = function parse(ripple) { + return function (res) { + var type = (0, _header2.default)('content-type')(res); + if (!ripple.types[type]) return err('could not understand type', type), false; + return (ripple.types[type].parse || _identity2.default)(res); + }; +}; - if (this === target) return 0 +var contentType = function contentType(res) { + return function (type) { + return type.check(res) && (res.headers['content-type'] = type.header); + }; +}; - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) +var types = function types() { + return [_text2.default].reduce(_to2.default.obj('header'), 1); +}; - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +var chainable = function chainable(fn) { + return function () { + return fn.apply(this, arguments), fn; + }; +}; - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } +var err = require('utilise/err')('[ri/core]'), + log = require('utilise/log')('[ri/core]'), + now = function now(d, t) { + return t = (0, _key2.default)('body.log.length')(d), _is2.default.num(t) ? t - 1 : t; +}; +},{"./types/text":54,"utilise/colorfill":467,"utilise/emitterify":476,"utilise/err":477,"utilise/header":491,"utilise/identity":492,"utilise/is":496,"utilise/key":498,"utilise/log":502,"utilise/to":545,"utilise/values":548,"utilise/za":552}],54:[function(require,module,exports){ +'use strict'; - if (x < y) return -1 - if (y < x) return 1 - return 0 -} +Object.defineProperty(exports, "__esModule", { + value: true +}); -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 +var _includes = require('utilise/includes'); - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } +var _includes2 = _interopRequireDefault(_includes); - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } +var _is = require('utilise/is'); - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) +var _is2 = _interopRequireDefault(_is); + +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + header: 'text/plain', + check: function check(res) { + return !(0, _includes2.default)('.html')(res.name) && !(0, _includes2.default)('.css')(res.name) && _is2.default.str(res.body); } +}; +},{"utilise/includes":494,"utilise/is":496}],55:[function(require,module,exports){ +'use strict'; - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = css; - throw new TypeError('val must be string, number or Buffer') -} +var _includes = require('utilise/includes'); -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length +var _includes2 = _interopRequireDefault(_includes); - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) +// ------------------------------------------- +// Exposes a convenient global instance +// ------------------------------------------- +function css(ripple) { + log('creating'); + ripple.types['text/css'] = { + header: 'text/css', + check: function check(res) { + return (0, _includes2.default)('.css')(res.name); } - } + }; - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } + return ripple; +} + +var log = require('utilise/log')('[ri/types/css]'); +},{"utilise/includes":56,"utilise/log":58}],56:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"dup":12}],57:[function(require,module,exports){ +module.exports = is +is.fn = isFunction +is.str = isString +is.num = isNumber +is.obj = isObject +is.lit = isLiteral +is.bol = isBoolean +is.truthy = isTruthy +is.falsy = isFalsy +is.arr = isArray +is.null = isNull +is.def = isDef +is.in = isIn + +function is(v){ + return function(d){ + return d == v } +} - return -1 +function isFunction(d) { + return typeof d == 'function' } -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 +function isBoolean(d) { + return typeof d == 'boolean' } -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +function isString(d) { + return typeof d == 'string' } -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +function isNumber(d) { + return typeof d == 'number' } -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } +function isObject(d) { + return typeof d == 'object' +} - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') +function isLiteral(d) { + return typeof d == 'object' + && !(d instanceof Array) +} - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i +function isTruthy(d) { + return !!d == true } -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +function isFalsy(d) { + return !!d == false } -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) +function isArray(d) { + return d instanceof Array } -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) +function isNull(d) { + return d === null } -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) +function isDef(d) { + return typeof d !== 'undefined' } -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +function isIn(set) { + return function(d){ + return !set ? false + : set.indexOf ? ~set.indexOf(d) + : d in set + } } +},{}],58:[function(require,module,exports){ +var is = require('utilise/is') + , to = require('utilise/to') + , owner = require('utilise/owner') -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) +module.exports = function log(prefix){ + return function(d){ + if (!owner.console || !console.log.apply) return d; + is.arr(arguments[2]) && (arguments[2] = arguments[2].length) + var args = to.arr(arguments) + args.unshift(prefix.grey ? prefix.grey : prefix) + return console.log.apply(console, args), d } +} +},{"utilise/is":57,"utilise/owner":59,"utilise/to":60}],59:[function(require,module,exports){ +(function (global){ +module.exports = true ? /* istanbul ignore next */ window : global +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],60:[function(require,module,exports){ +module.exports = { + arr: toArray +, obj: toObject +} - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining +function toArray(d){ + return Array.prototype.slice.call(d, 0) +} - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') +function toObject(d) { + var by = 'id' + , o = {} + + return arguments.length == 1 + ? (by = d, reduce) + : reduce.apply(this, arguments) + + function reduce(p,v,i){ + if (i === 0) p = {} + p[v[by]] = v + return p } +} +},{}],61:[function(require,module,exports){ +'use strict'; - if (!encoding) encoding = 'utf8' +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = data; - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) +var _overwrite = require('utilise/overwrite'); - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) +var _overwrite2 = _interopRequireDefault(_overwrite); - case 'ascii': - return asciiWrite(this, string, offset, length) +var _header = require('utilise/header'); - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) +var _header2 = _interopRequireDefault(_header); - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +var _extend = require('utilise/extend'); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) +var _extend2 = _interopRequireDefault(_extend); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true +var _not = require('utilise/not'); + +var _not2 = _interopRequireDefault(_not); + +var _key = require('utilise/key'); + +var _key2 = _interopRequireDefault(_key); + +var _set = require('utilise/set'); + +var _set2 = _interopRequireDefault(_set); + +var _is = require('utilise/is'); + +var _is2 = _interopRequireDefault(_is); + +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// ------------------------------------------- +// Adds support for data resources +// ------------------------------------------- +function data(ripple) { + log('creating'); + ripple.on('change.data', trickle(ripple)); + ripple.types['application/data'] = { + header: 'application/data', + check: function check(res) { + return _is2.default.obj(res.body) || !res.body ? true : false; + }, + parse: function parse(res) { + var existing = ripple.resources[res.name] || {}; + + (0, _extend2.default)(res.headers)(existing.headers); + res.body = (0, _set2.default)()(res.body || [], existing.body && existing.body.log, _is2.default.num(res.headers.log) ? res.headers.log : -1); + (0, _overwrite2.default)(res.body.on)(listeners(existing)); + res.body.on('change.bubble', function (change) { + ripple.emit('change', ripple.change = [res.name, change], (0, _not2.default)(_is2.default.in(['data']))); + delete ripple.change; + }); + + return res; } - } -} + }; -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } + return ripple; } -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } +var trickle = function trickle(ripple) { + return function (name, change) { + return (0, _header2.default)('content-type', 'application/data')(ripple.resources[name]) && ripple.resources[name].body.emit('change', [change || null], (0, _not2.default)(_is2.default.in(['bubble']))); + }; +}; + +var log = require('utilise/log')('[ri/types/data]'), + listeners = (0, _key2.default)('body.on'); +},{"utilise/extend":66,"utilise/header":68,"utilise/is":69,"utilise/key":70,"utilise/log":72,"utilise/not":73,"utilise/overwrite":74,"utilise/set":76}],62:[function(require,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"dup":33}],63:[function(require,module,exports){ +var has = require('utilise/has') + +module.exports = function def(o, p, v, w){ + if (o.host && o.host.nodeName) o = o.host + if (p.name) v = p, p = p.name + !has(o, p) && Object.defineProperty(o, p, { value: v, writable: w }) + return o[p] } -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] +},{"utilise/has":67}],64:[function(require,module,exports){ +var err = require('utilise/err')('[emitterify]') + , keys = require('utilise/keys') + , def = require('utilise/def') + , not = require('utilise/not') + , is = require('utilise/is') + +module.exports = function emitterify(body, dparam) { + return def(body, 'emit', emit, 1) + , def(body, 'once', once, 1) + , def(body, 'on', on, 1) + , body - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 + function emit(type, param, filter) { + var ns = type.split('.')[1] + , id = type.split('.')[0] + , li = body.on[id] || [] + , tt = li.length - 1 + , tp = is.def(param) ? param + : is.def(dparam) ? dparam + : [body] + , pm = is.arr(tp) ? tp : [tp] - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint + if (ns) return invoke(li, ns, pm), body - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } + for (var i = li.length; i >=0; i--) + invoke(li, i, pm) - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } + keys(li) + .filter(not(isFinite)) + .filter(filter || Boolean) + .map(function(n){ return invoke(li, n, pm) }) - res.push(codePoint) - i += bytesPerSequence + return body } - return decodeCodePointsArray(res) -} + function invoke(o, k, p){ + if (!o[k]) return + var fn = o[k] + o[k].once && (isFinite(k) ? o.splice(k, 1) : delete o[k]) + try { fn.apply(body, p) } catch(e) { err(e, e.stack) } + } -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 + function on(type, callback) { + var ns = type.split('.')[1] + , id = type.split('.')[0] -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + body.on[id] = body.on[id] || [] + return !callback && !ns ? (body.on[id]) + : !callback && ns ? (body.on[id][ns]) + : ns ? (body.on[id][ns] = callback, body) + : (body.on[id].push(callback), body) } - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) + function once(type, callback){ + return callback.once = true, body.on(type, callback), body } - return res } +},{"utilise/def":63,"utilise/err":65,"utilise/is":69,"utilise/keys":71,"utilise/not":73}],65:[function(require,module,exports){ +var owner = require('utilise/owner') + , to = require('utilise/to') -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) +module.exports = function err(prefix){ + return function(d){ + if (!owner.console || !console.error.apply) return d; + var args = to.arr(arguments) + args.unshift(prefix.red ? prefix.red : prefix) + return console.error.apply(console, args), d } - return ret } +},{"utilise/owner":75,"utilise/to":78}],66:[function(require,module,exports){ +var is = require('utilise/is') + , not = require('utilise/not') + , keys = require('utilise/keys') + , copy = require('utilise/copy') -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) +module.exports = function extend(to){ + return function(from){ + keys(from) + .filter(not(is.in(to))) + .map(copy(from, to)) - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) + return to } - return ret } - -function hexSlice (buf, start, end) { - var len = buf.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(buf[i]) - } - return out +},{"utilise/copy":62,"utilise/is":69,"utilise/keys":71,"utilise/not":73}],67:[function(require,module,exports){ +module.exports = function has(o, k) { + return k in o } +},{}],68:[function(require,module,exports){ +var key = require('utilise/key') -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) +module.exports = function header(header, value) { + var getter = arguments.length == 1 + return function(d){ + return !d || !d.headers ? null + : getter ? key(header)(d.headers) + : key(header)(d.headers) == value } - return res } +},{"utilise/key":70}],69:[function(require,module,exports){ +arguments[4][57][0].apply(exports,arguments) +},{"dup":57}],70:[function(require,module,exports){ +var str = require('utilise/str') + , is = require('utilise/is') -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end +module.exports = function key(k, v){ + var set = arguments.length > 1 + , keys = is.fn(k) ? [] : str(k).split('.') + , root = keys.shift() - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len + return function deep(o, i){ + var masked = {} + + return !o ? undefined + : !is.num(k) && !k ? o + : is.arr(k) ? (k.map(copy), masked) + : o[k] || !keys.length ? (set ? ((o[k] = is.fn(v) ? v(o[k], i) : v), o) + : (is.fn(k) ? k(o) : o[k])) + : (set ? (key(keys.join('.'), v)(o[root] ? o[root] : (o[root] = {})), o) + : key(keys.join('.'))(o[root])) + + function copy(k){ + var val = key(k)(o) + ;(val != undefined) && key(k, val)(masked) + } } +} +},{"utilise/is":69,"utilise/str":77}],71:[function(require,module,exports){ +var is = require('utilise/is') - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len +module.exports = function keys(o) { + return Object.keys(is.obj(o) || is.fn(o) ? o : {}) +} +},{"utilise/is":69}],72:[function(require,module,exports){ +arguments[4][58][0].apply(exports,arguments) +},{"dup":58,"utilise/is":69,"utilise/owner":75,"utilise/to":78}],73:[function(require,module,exports){ +arguments[4][19][0].apply(exports,arguments) +},{"dup":19}],74:[function(require,module,exports){ +var is = require('utilise/is') + , keys = require('utilise/keys') + , copy = require('utilise/copy') + +module.exports = function overwrite(to){ + return function(from){ + keys(from) + .map(copy(from, to)) + + return to } +} +},{"utilise/copy":62,"utilise/is":69,"utilise/keys":71}],75:[function(require,module,exports){ +arguments[4][59][0].apply(exports,arguments) +},{"dup":59}],76:[function(require,module,exports){ +var act = { add: add, update: update, remove: remove } + , emitterify = require('utilise/emitterify') + , def = require('utilise/def') + , is = require('utilise/is') + , str = JSON.stringify + , parse = JSON.parse - if (end < start) end = start +module.exports = function set(d) { + return function(o, existing, max) { + if (!is.obj(o)) + return o - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] + if (!is.obj(d)) { + var log = existing || o.log || [] + , root = o + + if (!is.def(max)) max = log.max || 0 + if (!max) log = [] + if (max < 0) log = log.concat(null) + if (max > 0) { + var s = str(o) + root = parse(s) + log = log.concat({ type: 'update', value: parse(s), time: log.length }) + } + + def(log, 'max', max) + + root.log + ? (root.log = log) + : def(emitterify(root, null), 'log', log, 1) + + return root } - } - return newBuf -} + if (is.def(d.key)) + apply(o, d.type, (d.key = '' + d.key).split('.'), d.value) -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} + if (o.log && o.log.max) + o.log.push((d.time = o.log.length, o.log.max > 0 ? d : null)) -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + if (o.emit) + o.emit('change', d) - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul + return o } - - return val } -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } +function apply(body, type, path, value) { + var next = path.shift() - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul + if (path.length) { + if (!(next in body)) + if (type == 'remove') return + else body[next] = {} + apply(body[next], type, path, value) } - - return val + else + act[type](body, next, value) } -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] +function add(o, k, v) { + is.arr(o) + ? o.splice(k, 0, v) + : (o[k] = v) } -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) +function update(o, k, v) { + o[k] = v } -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] +function remove(o, k, v) { + is.arr(o) + ? o.splice(k, 1) + : delete o[k] } +},{"utilise/def":63,"utilise/emitterify":64,"utilise/is":69}],77:[function(require,module,exports){ +var is = require('utilise/is') -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) +module.exports = function str(d){ + return d === 0 ? '0' + : !d ? '' + : is.fn(d) ? '' + d + : is.obj(d) ? JSON.stringify(d) + : String(d) } +},{"utilise/is":69}],78:[function(require,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"dup":60}],79:[function(require,module,exports){ +'use strict'; -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = features; - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} +var _includes = require('utilise/includes'); -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) +var _includes2 = _interopRequireDefault(_includes); - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - return val -} +var _header = require('utilise/header'); -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) +var _header2 = _interopRequireDefault(_header); - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 +var _append = require('utilise/append'); - if (val >= mul) val -= Math.pow(2, 8 * byteLength) +var _append2 = _interopRequireDefault(_append); - return val -} +var _attr = require('utilise/attr'); -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} +var _attr2 = _interopRequireDefault(_attr); -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} +var _from = require('utilise/from'); -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} +var _from2 = _interopRequireDefault(_from); -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) +var _not = require('utilise/not'); - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} +var _not2 = _interopRequireDefault(_not); -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) +var _str = require('utilise/str'); - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} +var _str2 = _interopRequireDefault(_str); -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} +var _key = require('utilise/key'); -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} +var _key2 = _interopRequireDefault(_key); -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} +var _by = require('utilise/by'); -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} +var _by2 = _interopRequireDefault(_by); -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} +var _is = require('utilise/is'); -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } +var _is2 = _interopRequireDefault(_is); - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return offset + byteLength +// ------------------------------------------- +// Extend Components with Features +// ------------------------------------------- +function features(ripple) { + if (!true) return; + log('creating'); + ripple.render = render(ripple)(ripple.render); + return ripple; } -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } +var render = function render(ripple) { + return function (next) { + return function (el) { + var features = (0, _str2.default)((0, _attr2.default)(el, 'is')).split(' ').map((0, _from2.default)(ripple.resources)).filter((0, _header2.default)('content-type', 'application/javascript')), + css = (0, _str2.default)((0, _attr2.default)('css')(el)).split(' '); - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } + features.filter((0, _by2.default)('headers.needs', (0, _includes2.default)('[css]'))).map((0, _key2.default)('name')).map((0, _append2.default)('.css')).filter((0, _not2.default)(_is2.default.in(css))).map(function (d) { + return (0, _attr2.default)('css', ((0, _str2.default)((0, _attr2.default)('css')(el)) + ' ' + d).trim())(el); + }); - return offset + byteLength -} + var node = next(el); -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} + return !node || !node.state ? undefined : (features.map((0, _key2.default)('body')).map(function (d) { + return d.call(node.shadowRoot || node, node.shadowRoot || node, node.state); + }), node); + }; + }; +}; -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 +var log = require('utilise/log')('[ri/features]'); +},{"utilise/append":80,"utilise/attr":81,"utilise/by":82,"utilise/from":85,"utilise/header":86,"utilise/includes":87,"utilise/is":88,"utilise/key":89,"utilise/log":90,"utilise/not":91,"utilise/str":93}],80:[function(require,module,exports){ +module.exports = function append(v) { + return function(d){ + return d+v } } +},{}],81:[function(require,module,exports){ +arguments[4][3][0].apply(exports,arguments) +},{"./is":88,"dup":3}],82:[function(require,module,exports){ +arguments[4][4][0].apply(exports,arguments) +},{"./is":88,"./key":89,"dup":4}],83:[function(require,module,exports){ +arguments[4][5][0].apply(exports,arguments) +},{"dup":5}],84:[function(require,module,exports){ +arguments[4][6][0].apply(exports,arguments) +},{"dup":6}],85:[function(require,module,exports){ +arguments[4][9][0].apply(exports,arguments) +},{"./datum":84,"./key":89,"dup":9}],86:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"./key":89,"dup":37}],87:[function(require,module,exports){ +arguments[4][12][0].apply(exports,arguments) +},{"dup":12}],88:[function(require,module,exports){ +arguments[4][13][0].apply(exports,arguments) +},{"dup":13}],89:[function(require,module,exports){ +arguments[4][14][0].apply(exports,arguments) +},{"./is":88,"./str":93,"dup":14}],90:[function(require,module,exports){ +arguments[4][17][0].apply(exports,arguments) +},{"./is":88,"./owner":92,"./to":94,"dup":17}],91:[function(require,module,exports){ +arguments[4][19][0].apply(exports,arguments) +},{"dup":19}],92:[function(require,module,exports){ +arguments[4][20][0].apply(exports,arguments) +},{"./client":83,"dup":20}],93:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"./is":88,"dup":23}],94:[function(require,module,exports){ +arguments[4][60][0].apply(exports,arguments) +},{"dup":60}],95:[function(require,module,exports){ +'use strict'; -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = fnc; -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} +var _str = require('utilise/str'); -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} +var _str2 = _interopRequireDefault(_str); -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} +var _is = require('utilise/is'); -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} +var _is2 = _interopRequireDefault(_is); -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) +var _fn = require('utilise/fn'); - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } +var _fn2 = _interopRequireDefault(_fn); - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return offset + byteLength +// ------------------------------------------- +// Adds support for function resources +// ------------------------------------------- +function fnc(ripple) { + log('creating'); + ripple.types['application/javascript'] = { header: header, check: check, parse: parse, to: to }; + return ripple; } -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) +var header = 'application/javascript'; +var check = function check(res) { + return _is2.default.fn(res.body); +}; +var parse = function parse(res) { + return res.body = (0, _fn2.default)(res.body), res; +}; +var log = require('utilise/log')('[ri/types/fn]'); +var to = function to(res) { + return res.value = (0, _str2.default)(res.value), res; +}; +},{"utilise/fn":484,"utilise/is":496,"utilise/log":502,"utilise/str":540}],96:[function(require,module,exports){ +require('utilise');'use strict'; - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } +var _rijs = require('rijs.backpressure'); - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } +var _rijs2 = _interopRequireDefault(_rijs); - return offset + byteLength -} +var _rijs3 = require('rijs.components'); -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} +var _rijs4 = _interopRequireDefault(_rijs3); -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} +var _rijs5 = require('rijs.versioned'); -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} +var _rijs6 = _interopRequireDefault(_rijs5); -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} +var _rijs7 = require('rijs.singleton'); -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} +var _rijs8 = _interopRequireDefault(_rijs7); -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} +var _rijs9 = require('rijs.sessions'); -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} +var _rijs10 = _interopRequireDefault(_rijs9); -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} +var _rijs11 = require('rijs.features'); -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} +var _rijs12 = _interopRequireDefault(_rijs11); -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} +var _rijs13 = require('rijs.offline'); -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} +var _rijs14 = _interopRequireDefault(_rijs13); -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} +var _rijs15 = require('rijs.helpers'); -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start +var _rijs16 = _interopRequireDefault(_rijs15); - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 +var _rijs17 = require('rijs.precss'); - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') +var _rijs18 = _interopRequireDefault(_rijs17); - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } +var _rijs19 = require('rijs.resdir'); - var len = end - start - var i +var _rijs20 = _interopRequireDefault(_rijs19); - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } +var _rijs21 = require('rijs.serve'); - return len -} +var _rijs22 = _interopRequireDefault(_rijs21); -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } +var _rijs23 = require('rijs.pages'); - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } +var _rijs24 = _interopRequireDefault(_rijs23); - if (end <= start) { - return this - } +var _rijs25 = require('rijs.needs'); - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 +var _rijs26 = _interopRequireDefault(_rijs25); - if (!val) val = 0 +var _rijs27 = require('rijs.sync'); - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } +var _rijs28 = _interopRequireDefault(_rijs27); - return this -} +var _rijs29 = require('rijs.core'); -// HELPER FUNCTIONS -// ================ +var _rijs30 = _interopRequireDefault(_rijs29); -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g +var _rijs31 = require('rijs.data'); -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} +var _rijs32 = _interopRequireDefault(_rijs31); -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} +var _rijs33 = require('rijs.css'); -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} +var _rijs34 = _interopRequireDefault(_rijs33); -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] +var _rijs35 = require('rijs.fn'); - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) +var _rijs36 = _interopRequireDefault(_rijs35); - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - // valid lead - leadSurrogate = codePoint - continue - } +/* istanbul ignore next */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } +true && !window.ripple && create(); - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } +module.exports = create; - leadSurrogate = null +function create(opts) { + var ripple = (0, _rijs30.default)(); // empty base collection of resources - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } + // enrich.. + (0, _rijs8.default)(ripple); // exposes a single instance + (0, _rijs32.default)(ripple); // register data types + (0, _rijs34.default)(ripple); // register css types + (0, _rijs36.default)(ripple); // register fn types + (0, _rijs16.default)(ripple); // expose helper functions and constants + (0, _rijs4.default)(ripple); // invoke web components, fn.call(, data) + (0, _rijs26.default)(ripple); // define default attrs for components + (0, _rijs18.default)(ripple); // preapplies scoped css + (0, _rijs14.default)(ripple); // loads/saves from/to localstorage + (0, _rijs28.default)(ripple, opts); // syncs resources between server/client + (0, _rijs2.default)(ripple); // restricts broadcast to clients based on need + (0, _rijs22.default)(ripple, opts); // serve client libraries + (0, _rijs24.default)(ripple, opts); // serve pages directory + (0, _rijs12.default)(ripple); // extend components with features + (0, _rijs6.default)(ripple); // versioning info and time travel + (0, _rijs10.default)(ripple, opts); // populates sessionid on each connection + (0, _rijs20.default)(ripple, opts); // loads from resources folder - return bytes + return ripple; } -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} +},{"rijs.backpressure":1,"rijs.components":27,"rijs.core":53,"rijs.css":55,"rijs.data":61,"rijs.features":79,"rijs.fn":95,"rijs.helpers":248,"rijs.needs":264,"rijs.offline":277,"rijs.pages":296,"rijs.precss":297,"rijs.resdir":321,"rijs.serve":322,"rijs.sessions":323,"rijs.singleton":324,"rijs.sync":329,"rijs.versioned":438,"utilise":495}],97:[function(require,module,exports){ +var asn1 = exports; -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break +asn1.bignum = require('bn.js'); - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } +asn1.define = require('./asn1/api').define; +asn1.base = require('./asn1/base'); +asn1.constants = require('./asn1/constants'); +asn1.decoders = require('./asn1/decoders'); +asn1.encoders = require('./asn1/encoders'); - return byteArray -} +},{"./asn1/api":98,"./asn1/base":100,"./asn1/constants":104,"./asn1/decoders":106,"./asn1/encoders":109,"bn.js":112}],98:[function(require,module,exports){ +var asn1 = require('../asn1'); +var inherits = require('inherits'); -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} +var api = exports; -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] +api.define = function define(name, body) { + return new Entity(name, body); +}; + +function Entity(name, body) { + this.name = name; + this.body = body; + + this.decoders = {}; + this.encoders = {}; +}; + +Entity.prototype._createNamed = function createNamed(base) { + var named; + try { + named = require('vm').runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; } - return i -} + inherits(named, base); + named.prototype._initNamed = function initnamed(entity) { + base.call(this, entity); + }; -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} + return new named(this); +}; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":6,"ieee754":52,"isarray":56}],12:[function(require,module,exports){ -/* +Entity.prototype._getDecoder = function _getDecoder(enc) { + enc = enc || 'der'; + // Lazily create decoder + if (!this.decoders.hasOwnProperty(enc)) + this.decoders[enc] = this._createNamed(asn1.decoders[enc]); + return this.decoders[enc]; +}; -The MIT License (MIT) +Entity.prototype.decode = function decode(data, enc, options) { + return this._getDecoder(enc).decode(data, options); +}; -Original Library - - Copyright (c) Marak Squires +Entity.prototype._getEncoder = function _getEncoder(enc) { + enc = enc || 'der'; + // Lazily create encoder + if (!this.encoders.hasOwnProperty(enc)) + this.encoders[enc] = this._createNamed(asn1.encoders[enc]); + return this.encoders[enc]; +}; -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) +Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { + return this._getEncoder(enc).encode(data, reporter); +}; -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +},{"../asn1":97,"inherits":189,"vm":246}],99:[function(require,module,exports){ +var inherits = require('inherits'); +var Reporter = require('../base').Reporter; +var Buffer = require('buffer').Buffer; -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +function DecoderBuffer(base, options) { + Reporter.call(this, options); + if (!Buffer.isBuffer(base)) { + this.error('Input not Buffer'); + return; + } -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + this.base = base; + this.offset = 0; + this.length = base.length; +} +inherits(DecoderBuffer, Reporter); +exports.DecoderBuffer = DecoderBuffer; -*/ +DecoderBuffer.prototype.save = function save() { + return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; +}; -var colors = {}; -module['exports'] = colors; +DecoderBuffer.prototype.restore = function restore(save) { + // Return skipped data + var res = new DecoderBuffer(this.base); + res.offset = save.offset; + res.length = this.offset; -colors.themes = {}; + this.offset = save.offset; + Reporter.prototype.restore.call(this, save.reporter); -var ansiStyles = colors.styles = require('./styles'); -var defineProps = Object.defineProperties; + return res; +}; -colors.supportsColor = require('./system/supports-colors'); +DecoderBuffer.prototype.isEmpty = function isEmpty() { + return this.offset === this.length; +}; -if (typeof colors.enabled === "undefined") { - colors.enabled = colors.supportsColor; +DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { + if (this.offset + 1 <= this.length) + return this.base.readUInt8(this.offset++, true); + else + return this.error(fail || 'DecoderBuffer overrun'); } -colors.stripColors = colors.strip = function(str){ - return ("" + str).replace(/\x1B\[\d+m/g, ''); -}; +DecoderBuffer.prototype.skip = function skip(bytes, fail) { + if (!(this.offset + bytes <= this.length)) + return this.error(fail || 'DecoderBuffer overrun'); + var res = new DecoderBuffer(this.base); -var stylize = colors.stylize = function stylize (str, style) { - if (!colors.enabled) { - return str+''; - } + // Share reporter state + res._reporterState = this._reporterState; - return ansiStyles[style].open + str + ansiStyles[style].close; + res.offset = this.offset; + res.length = this.offset + bytes; + this.offset += bytes; + return res; } -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); +DecoderBuffer.prototype.raw = function raw(save) { + return this.base.slice(save ? save.offset : this.offset, this.length); +} + +function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) { + this.length = 0; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); } - return str.replace(matchOperatorsRe, '\\$&'); -} - -function build(_styles) { - var builder = function builder() { - return applyStyle.apply(builder, arguments); - }; - builder._styles = _styles; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - builder.__proto__ = proto; - return builder; } +exports.EncoderBuffer = EncoderBuffer; -var styles = (function () { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function (key) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - ret[key] = { - get: function () { - return build(this._styles.concat(key)); - } - }; - }); - return ret; -})(); +EncoderBuffer.prototype.join = function join(out, offset) { + if (!out) + out = new Buffer(this.length); + if (!offset) + offset = 0; -var proto = defineProps(function colors() {}, styles); + if (this.length === 0) + return out; -function applyStyle() { - var args = arguments; - var argsLen = args.length; - var str = argsLen !== 0 && String(arguments[0]); - if (argsLen > 1) { - for (var a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } + if (Array.isArray(this.value)) { + this.value.forEach(function(item) { + item.join(out, offset); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + this.value.copy(out, offset); + offset += this.length; } - if (!colors.enabled || !str) { - return str; - } + return out; +}; - var nestedStyles = this._styles; +},{"../base":100,"buffer":142,"inherits":189}],100:[function(require,module,exports){ +var base = exports; - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - } +base.Reporter = require('./reporter').Reporter; +base.DecoderBuffer = require('./buffer').DecoderBuffer; +base.EncoderBuffer = require('./buffer').EncoderBuffer; +base.Node = require('./node'); - return str; -} +},{"./buffer":99,"./node":101,"./reporter":102}],101:[function(require,module,exports){ +var Reporter = require('../base').Reporter; +var EncoderBuffer = require('../base').EncoderBuffer; +var DecoderBuffer = require('../base').DecoderBuffer; +var assert = require('minimalistic-assert'); -function applyTheme (theme) { - for (var style in theme) { - (function(style){ - colors[style] = function(str){ - if (typeof theme[style] === 'object'){ - var out = str; - for (var i in theme[style]){ - out = colors[theme[style][i]](out); - } - return out; - } - return colors[theme[style]](str); - }; - })(style) - } -} +// Supported tags +var tags = [ + 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', + 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' +]; -colors.setTheme = function (theme) { - if (typeof theme === 'string') { - try { - colors.themes[theme] = require(theme); - applyTheme(colors.themes[theme]); - return colors.themes[theme]; - } catch (err) { - console.log(err); - return err; - } - } else { - applyTheme(theme); - } -}; +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); -function init() { - var ret = {}; - Object.keys(styles).forEach(function (name) { - ret[name] = { - get: function () { - return build([name]); - } - }; +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; }); - return ret; -} + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; -var sequencer = function sequencer (map, str) { - var exploded = str.split(""), i = 0; - exploded = exploded.map(map); - return exploded.join(""); +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } }; -// custom formatter methods -colors.trap = require('./custom/trap'); -colors.zalgo = require('./custom/zalgo'); +// +// Overrided methods +// -// maps -colors.maps = {}; -colors.maps.america = require('./maps/america'); -colors.maps.zebra = require('./maps/zebra'); -colors.maps.rainbow = require('./maps/rainbow'); -colors.maps.random = require('./maps/random') +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); -for (var map in colors.maps) { - (function(map){ - colors[map] = function (str) { - return sequencer(colors.maps[map], str); - } - })(map) -} +// +// Public methods +// -defineProps(colors, init()); -},{"./custom/trap":13,"./custom/zalgo":14,"./maps/america":17,"./maps/rainbow":18,"./maps/random":19,"./maps/zebra":20,"./styles":21,"./system/supports-colors":22}],13:[function(require,module,exports){ -module['exports'] = function runTheTrap (text, options) { - var result = ""; - text = text || "Run the trap, drop the bass"; - text = text.split(''); - var trap = { - a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"], - b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"], - c: ["\u00a9", "\u023b", "\u03fe"], - d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"], - e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"], - f: ["\u04fa"], - g: ["\u0262"], - h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"], - i: ["\u0f0f"], - j: ["\u0134"], - k: ["\u0138", "\u04a0", "\u04c3", "\u051e"], - l: ["\u0139"], - m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"], - n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"], - o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"], - p: ["\u01f7", "\u048e"], - q: ["\u09cd"], - r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"], - s: ["\u00a7", "\u03de", "\u03df", "\u03e8"], - t: ["\u0141", "\u0166", "\u0373"], - u: ["\u01b1", "\u054d"], - v: ["\u05d8"], - w: ["\u0428", "\u0460", "\u047c", "\u0d70"], - x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"], - y: ["\u00a5", "\u04b0", "\u04cb"], - z: ["\u01b5", "\u0240"] - } - text.forEach(function(c){ - c = c.toLowerCase(); - var chars = trap[c] || [" "]; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== "undefined") { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; - -} +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); -},{}],14:[function(require,module,exports){ -// please no -module['exports'] = function zalgo(text, options) { - text = text || " he is here "; - var soul = { - "up" : [ - '̍', '̎', '̄', '̅', - '̿', '̑', '̆', '̐', - '͒', '͗', '͑', '̇', - '̈', '̊', '͂', '̓', - '̈', '͊', '͋', '͌', - '̃', '̂', '̌', '͐', - '̀', '́', '̋', '̏', - '̒', '̓', '̔', '̽', - '̉', 'ͣ', 'ͤ', 'ͥ', - 'ͦ', 'ͧ', 'ͨ', 'ͩ', - 'ͪ', 'ͫ', 'ͬ', 'ͭ', - 'ͮ', 'ͯ', '̾', '͛', - '͆', '̚' - ], - "down" : [ - '̖', '̗', '̘', '̙', - '̜', '̝', '̞', '̟', - '̠', '̤', '̥', '̦', - '̩', '̪', '̫', '̬', - '̭', '̮', '̯', '̰', - '̱', '̲', '̳', '̹', - '̺', '̻', '̼', 'ͅ', - '͇', '͈', '͉', '͍', - '͎', '͓', '͔', '͕', - '͖', '͙', '͚', '̣' - ], - "mid" : [ - '̕', '̛', '̀', '́', - '͘', '̡', '̢', '̧', - '̨', '̴', '̵', '̶', - '͜', '͝', '͞', - '͟', '͠', '͢', '̸', - '̷', '͡', ' ҉' - ] - }, - all = [].concat(soul.up, soul.down, soul.mid), - zalgo = {}; + assert(state.tag === null); + state.tag = tag; - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; - } + this._useArgs(args); - function is_char(character) { - var bool = false; - all.filter(function (i) { - bool = (i === character); - }); - return bool; - } - + return this; + }; +}); - function heComes(text, options) { - var result = '', counts, l; - options = options || {}; - options["up"] = typeof options["up"] !== 'undefined' ? options["up"] : true; - options["mid"] = typeof options["mid"] !== 'undefined' ? options["mid"] : true; - options["down"] = typeof options["down"] !== 'undefined' ? options["down"] : true; - options["size"] = typeof options["size"] !== 'undefined' ? options["size"] : "maxi"; - text = text.split(''); - for (l in text) { - if (is_char(l)) { - continue; - } - result = result + text[l]; - counts = {"up" : 0, "down" : 0, "mid" : 0}; - switch (options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.mid = randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.mid = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; - var arr = ["up", "mid", "down"]; - for (var d in arr) { - var index = arr[d]; - for (var i = 0 ; i <= counts[index]; i++) { - if (options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - } - // don't summon him - return heComes(text, options); -} + assert(state.use === null); + state.use = item; -},{}],15:[function(require,module,exports){ -var colors = require('./colors'); + return this; +}; -module['exports'] = function () { +Node.prototype.optional = function optional() { + var state = this._baseState; - // - // Extends prototype of native string object to allow for "foo".red syntax - // - var addProperty = function (color, func) { - String.prototype.__defineGetter__(color, func); - }; + state.optional = true; - var sequencer = function sequencer (map, str) { - return function () { - var exploded = this.split(""), i = 0; - exploded = exploded.map(map); - return exploded.join(""); - } - }; + return this; +}; - addProperty('strip', function () { - return colors.strip(this); - }); +Node.prototype.def = function def(val) { + var state = this._baseState; - addProperty('stripColors', function () { - return colors.strip(this); - }); + assert(state['default'] === null); + state['default'] = val; + state.optional = true; - addProperty("trap", function(){ - return colors.trap(this); - }); + return this; +}; - addProperty("zalgo", function(){ - return colors.zalgo(this); - }); +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; - addProperty("zebra", function(){ - return colors.zebra(this); - }); + assert(state.explicit === null && state.implicit === null); + state.explicit = num; - addProperty("rainbow", function(){ - return colors.rainbow(this); - }); + return this; +}; - addProperty("random", function(){ - return colors.random(this); - }); +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; - addProperty("america", function(){ - return colors.america(this); - }); + assert(state.explicit === null && state.implicit === null); + state.implicit = num; - // - // Iterate through all default styles and colors - // - var x = Object.keys(colors.styles); - x.forEach(function (style) { - addProperty(style, function () { - return colors.stylize(this, style); - }); - }); + return this; +}; - function applyTheme(theme) { - // - // Remark: This is a list of methods that exist - // on String that you should not overwrite. - // - var stringPrototypeBlacklist = [ - '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor', - 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt', - 'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring', - 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight' - ]; +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); - Object.keys(theme).forEach(function (prop) { - if (stringPrototypeBlacklist.indexOf(prop) !== -1) { - console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name'); - } - else { - if (typeof(theme[prop]) === 'string') { - colors[prop] = colors[theme[prop]]; - addProperty(prop, function () { - return colors[theme[prop]](this); - }); - } - else { - addProperty(prop, function () { - var ret = this; - for (var t = 0; t < theme[prop].length; t++) { - ret = colors[theme[prop][t]](ret); - } - return ret; - }); - } - } - }); - } + state.obj = true; - colors.setTheme = function (theme) { - if (typeof theme === 'string') { - try { - colors.themes[theme] = require(theme); - applyTheme(colors.themes[theme]); - return colors.themes[theme]; - } catch (err) { - console.log(err); - return err; - } - } else { - applyTheme(theme); - } - }; + if (args.length !== 0) + this._useArgs(args); + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; }; -},{"./colors":12}],16:[function(require,module,exports){ -var colors = require('./colors'); -module['exports'] = colors; -// Remark: By default, colors will add style properties to String.prototype -// -// If you don't wish to extend String.prototype you can do this instead and native String will not be touched -// -// var colors = require('colors/safe); -// colors.red("foo") // +// Decoding // -require('./extendStringPrototype')(); -},{"./colors":12,"./extendStringPrototype":15}],17:[function(require,module,exports){ -var colors = require('../colors'); -module['exports'] = (function() { - return function (letter, i, exploded) { - if(letter === " ") return letter; - switch(i%3) { - case 0: return colors.red(letter); - case 1: return colors.white(letter) - case 2: return colors.blue(letter) +Node.prototype._decode = function decode(input, options) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); + + var result = state['default']; + var present = true; + + var prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; } } -})(); -},{"../colors":12}],18:[function(require,module,exports){ -var colors = require('../colors'); -module['exports'] = (function () { - var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV - return function (letter, i, exploded) { - if (letter === " ") { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; } - }; -})(); + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } -},{"../colors":12}],19:[function(require,module,exports){ -var colors = require('../colors'); + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); -module['exports'] = (function () { - var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; - return function(letter, i, exploded) { - return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter); - }; -})(); -},{"../colors":12}],20:[function(require,module,exports){ -var colors = require('../colors'); + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); -module['exports'] = function (letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); -}; -},{"../colors":12}],21:[function(require,module,exports){ -/* -The MIT License (MIT) + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input, options); + else + result = this._decodeChoice(input, options); -Copyright (c) Sindre Sorhus (sindresorhus.com) + if (input.isError(result)) + return result; -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); -*/ + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); -var styles = {}; -module['exports'] = styles; + return result; +}; -var codes = { - reset: [0, 0], +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); + + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], +Node.prototype._getUse = function _getUse(entity, obj) { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; - // legacy styles for colors pre v1.0.0 - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49] +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + if (!match) + return input.error('Choice not matched'); + + return result; }; -Object.keys(codes).forEach(function (key) { - var val = codes[key]; - var style = styles[key] = []; - style.open = '\u001b[' + val[0] + 'm'; - style.close = '\u001b[' + val[1] + 'm'; -}); -},{}],22:[function(require,module,exports){ -(function (process){ -/* -The MIT License (MIT) +// +// Encoding +// -Copyright (c) Sindre Sorhus (sindresorhus.com) +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + if (this._skipDefault(result, reporter, parent)) + return; -*/ + return result; +}; -var argv = process.argv; +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; -module.exports = (function () { - if (argv.indexOf('--no-color') !== -1 || - argv.indexOf('--color=false') !== -1) { - return false; - } + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); - if (argv.indexOf('--color') !== -1 || - argv.indexOf('--color=true') !== -1 || - argv.indexOf('--color=always') !== -1) { - return true; - } + var result = null; - if (process.stdout && !process.stdout.isTTY) { - return false; - } + // Set reporter to share it with a child class + this.reporter = reporter; - if (process.platform === 'win32') { - return true; + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; } - if ('COLORTERM' in process.env) { - return true; - } + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); - if (process.env.TERM === 'dumb') { - return false; + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } } - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be ommited only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } } - return false; -})(); -}).call(this,require('_process')) -},{"_process":63}],23:[function(require,module,exports){ -/** - * Slice reference. - */ + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); -var slice = [].slice; + return result; +}; -/** - * Bind `obj` to `fn`. - * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public - */ +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; -module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); - } +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); }; -},{}],24:[function(require,module,exports){ +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; -/** - * Expose `Emitter`. - */ +},{"../base":100,"minimalistic-assert":193}],102:[function(require,module,exports){ +var inherits = require('inherits'); -module.exports = Emitter; +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.Reporter = Reporter; -/** - * Initialize a new `Emitter`. - * - * @api public - */ +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; -function Emitter(obj) { - if (obj) return mixin(obj); +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; }; -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks[event] = this._callbacks[event] || []) - .push(fn); - return this; +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); }; -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; -Emitter.prototype.once = function(event, fn){ - var self = this; - this._callbacks = this._callbacks || {}; + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; - function on() { - self.off(event, on); - fn.apply(this, arguments); - } +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; - on.fn = fn; - this.on(event, on); - return this; +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; }; -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; + var now = state.obj; + state.obj = prev; + return now; +}; - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); } - // specific event - var callbacks = this._callbacks[event]; - if (!callbacks) return this; + if (!state.options.partial) + throw err; - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks[event]; - return this; - } + if (!inherited) + state.errors.push(err); - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; + return err; }; -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks[event]; + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; } } - return this; }; -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ +},{"inherits":189}],103:[function(require,module,exports){ +var constants = require('../constants'); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); + +},{"../constants":104}],104:[function(require,module,exports){ +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks[event] || []; + return res; }; -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ +constants.der = require('./der'); -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; +},{"./der":103}],105:[function(require,module,exports){ +var inherits = require('inherits'); -},{}],25:[function(require,module,exports){ +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; -module.exports = function(a, b){ - var fn = function(){}; - fn.prototype = b.prototype; - a.prototype = new fn; - a.prototype.constructor = a; +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); }; -},{}],26:[function(require,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +module.exports = DERDecoder; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; + return this.tree._decode(data, options); +}; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +// Tree methods -function isNull(arg) { - return arg === null; +function DERNode(parent) { + base.Node.call(this, 'der', parent); } -exports.isNull = isNull; +inherits(DERNode, base.Node); -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + buffer.restore(state); -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + // Failure + if (buffer.isError(len)) + return len; -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; -exports.isBuffer = Buffer.isBuffer; +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); -function objectToString(o) { - return Object.prototype.toString.call(o); -} + // Failure + if (buffer.isError(res)) + return res; -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":55}],27:[function(require,module,exports){ -module.exports = function scope(styles, prefix) { - return styles - .replace(/^(?!.*:host)([^@%\n]*){/gim, function($1){ return prefix+' '+$1 }) // ... { -> tag ... { - .replace(/^(?!.*:host)(.*?),\s*$/gim, function($1){ return prefix+' '+$1 }) // ... , -> tag ... , - .replace(/:host\((.*?)\)/gi, function($1, $2){ return prefix+$2 }) // :host(...) -> tag... - .replace(/:host /gi, prefix + ' ') // :host ... -> tag ... - .replace(/^.*:host-context\((.*)\)/gim, function($1, $2){ return $2+' ' +prefix }) // ... :host-context(..) -> ... tag.. -} -},{}],28:[function(require,module,exports){ + if (tag.tagStr === 'end') + break; + } +}; -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; -/** - * Colors. - */ +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; -function useColors() { - // is webkit? http://stackoverflow.com/a/16459606/376773 - return ('WebkitAppearance' in document.documentElement.style) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (window.console && (console.firebug || (console.exception && console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); -} + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } -exports.formatters.j = function(v) { - return JSON.stringify(v); + return result; }; +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; -function formatArgs() { - var args = arguments; - var useColors = this.useColors; +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; - if (!useColors) return args; +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); - var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); + if (values) + res = values[res.toString(10)] || res; - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + return res; +}; - args.splice(lastC, 0, c); - return args; -} +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ +// Utility methods -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; } - } catch(e) {} + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - return r; -} + // Indefinite form + if (!primitive && len === 0x80) + return null; -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } -exports.enable(load()); + // Long form + var num = len & 0x7f; + if (num >= 4) + return buf.error('length octect is too long'); -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } -function localstorage(){ - try { - return window.localStorage; - } catch (e) {} + return len; } -},{"./debug":29}],29:[function(require,module,exports){ +},{"../../asn1":97,"inherits":189}],106:[function(require,module,exports){ +var decoders = exports; -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ +decoders.der = require('./der'); +decoders.pem = require('./pem'); -exports = module.exports = debug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); +},{"./der":105,"./pem":107}],107:[function(require,module,exports){ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; -/** - * The currently active debug mode names, and names to skip. - */ +var DERDecoder = require('./der'); -exports.names = []; -exports.skips = []; +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lowercased letter, i.e. "n". - */ +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); -exports.formatters = {}; + var label = options.label.toUpperCase(); -/** - * Previously assigned color. - */ + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; -var prevColor = 0; + if (match[2] !== label) + continue; -/** - * Previous log timestamp. - */ + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); -var prevTime; + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); -/** - * Select a color. - * - * @return {Number} - * @api private - */ + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; -function selectColor() { - return exports.colors[prevColor++ % exports.colors.length]; -} +},{"./der":105,"buffer":142,"inherits":189}],108:[function(require,module,exports){ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ +var asn1 = require('../../asn1'); +var base = asn1.base; -function debug(namespace) { +// Import DER constants +var der = asn1.constants.der; - // define the `disabled` version - function disabled() { - } - disabled.enabled = false; +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; - // define the `enabled` version - function enabled() { + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; - var self = enabled; +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +// Tree methods - // add the `color` if not set - if (null == self.useColors) self.useColors = exports.useColors(); - if (null == self.color && self.useColors) self.color = selectColor(); +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); - var args = Array.prototype.slice.call(arguments); +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); - args[0] = exports.coerce(args[0]); + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } - if ('string' !== typeof args[0]) { - // anything else let's inspect with %o - args = ['%o'].concat(args); - } + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; - if ('function' === typeof exports.formatArgs) { - args = exports.formatArgs.apply(self, args); + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); } - var logFn = enabled.log || exports.log || console.log.bind(console); - logFn.apply(self, args); + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); } - enabled.enabled = true; +}; - var fn = exports.enabled(namespace) ? enabled : disabled; +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } - fn.namespace = namespace; + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } - return fn; -} + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } -function enable(namespaces) { - exports.save(namespaces); + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } - var split = (namespaces || '').split(/[\s,]+/); - var len = split.length; + return this._createEncoderBuffer(objid); +}; - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } -} - -/** - * Disable debug output. - * - * @api public - */ -function disable() { - exports.enable(''); -} + return this._encodeStr(str, 'octstr'); +}; -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); } + num = values[num]; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); } + num = new Buffer(numArray); } - return false; -} -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; -},{"ms":58}],30:[function(require,module,exports){ + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } -module.exports = require('./lib/index'); + if (num < 0x80) + return this._createEncoderBuffer(num); -},{"./lib/index":31}],31:[function(require,module,exports){ + if (num < 0x100) + return this._createEncoderBuffer([0, num]); -module.exports = require('./socket'); + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; -/** - * Exports parser - * - * @api public - * - */ -module.exports.parser = require('engine.io-parser'); + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } -},{"./socket":32,"engine.io-parser":44}],32:[function(require,module,exports){ -(function (global){ -/** - * Module dependencies. - */ + return this._createEncoderBuffer(new Buffer(out)); +}; -var transports = require('./transports/index'); -var Emitter = require('component-emitter'); -var debug = require('debug')('engine.io-client:socket'); -var index = require('indexof'); -var parser = require('engine.io-parser'); -var parseuri = require('parseuri'); -var parsejson = require('parsejson'); -var parseqs = require('parseqs'); +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; -/** - * Module exports. - */ +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; -module.exports = Socket; +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; -/** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); -function Socket (uri, opts) { - if (!(this instanceof Socket)) return new Socket(uri, opts); + if (data.length !== state.defaultBuffer.length) + return false; - opts = opts || {}; + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; - if (uri && 'object' === typeof uri) { - opts = uri; - uri = null; - } + return true; +}; - if (uri) { - uri = parseuri(uri); - opts.hostname = uri.host; - opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parseuri(opts.host).host; - } +// Utility methods - this.secure = null != opts.secure ? opts.secure - : (global.location && 'https:' === location.protocol); +function encodeTag(tag, primitive, cls, reporter) { + var res; - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = this.secure ? '443' : '80'; - } + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; - this.agent = opts.agent || false; - this.hostname = opts.hostname || - (global.location ? location.hostname : 'localhost'); - this.port = opts.port || (global.location && location.port - ? location.port - : (this.secure ? 443 : 80)); - this.query = opts.query || {}; - if ('string' === typeof this.query) this.query = parseqs.decode(this.query); - this.upgrade = false !== opts.upgrade; - this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; - this.forceJSONP = !!opts.forceJSONP; - this.jsonp = false !== opts.jsonp; - this.forceBase64 = !!opts.forceBase64; - this.enablesXDR = !!opts.enablesXDR; - this.timestampParam = opts.timestampParam || 't'; - this.timestampRequests = opts.timestampRequests; - this.transports = opts.transports || ['polling', 'websocket']; - this.readyState = ''; - this.writeBuffer = []; - this.prevBufferLen = 0; - this.policyPort = opts.policyPort || 843; - this.rememberUpgrade = opts.rememberUpgrade || false; - this.binaryType = null; - this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; - this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); - if (true === this.perMessageDeflate) this.perMessageDeflate = {}; - if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { - this.perMessageDeflate.threshold = 1024; - } + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); - // SSL options for Node.js client - this.pfx = opts.pfx || null; - this.key = opts.key || null; - this.passphrase = opts.passphrase || null; - this.cert = opts.cert || null; - this.ca = opts.ca || null; - this.ciphers = opts.ciphers || null; - this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; - this.forceNode = !!opts.forceNode; + if (!primitive) + res |= 0x20; - // other options for Node.js client - var freeGlobal = typeof global === 'object' && global; - if (freeGlobal.global === freeGlobal) { - if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { - this.extraHeaders = opts.extraHeaders; - } + res |= (der.tagClassByName[cls || 'universal'] << 6); - if (opts.localAddress) { - this.localAddress = opts.localAddress; - } - } + return res; +} - // set on handshake - this.id = null; - this.upgrades = null; - this.pingInterval = null; - this.pingTimeout = null; +},{"../../asn1":97,"buffer":142,"inherits":189}],109:[function(require,module,exports){ +var encoders = exports; - // set on heartbeat - this.pingIntervalTimer = null; - this.pingTimeoutTimer = null; +encoders.der = require('./der'); +encoders.pem = require('./pem'); - this.open(); -} +},{"./der":108,"./pem":110}],110:[function(require,module,exports){ +var inherits = require('inherits'); -Socket.priorWebsocketSuccess = false; +var DEREncoder = require('./der'); -/** - * Mix in `Emitter`. - */ +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; -Emitter(Socket.prototype); +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); -/** - * Protocol version. - * - * @api public - */ + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; -Socket.protocol = parser.protocol; // this is an int +},{"./der":108,"inherits":189}],111:[function(require,module,exports){ +'use strict' -/** - * Expose deps for legacy compatibility - * and standalone browser access. - */ +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray -Socket.Socket = Socket; -Socket.Transport = require('./transport'); -Socket.transports = require('./transports/index'); -Socket.parser = require('engine.io-parser'); +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array -/** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} -Socket.prototype.createTransport = function (name) { - debug('creating transport "%s"', name); - var query = clone(this.query); +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 - // append engine.io protocol identifier - query.EIO = parser.protocol; +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - // transport name - query.transport = name; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} - // session id if we already have one - if (this.id) query.sid = this.id; +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} - var transport = new transports[name]({ - agent: this.agent, - hostname: this.hostname, - port: this.port, - secure: this.secure, - path: this.path, - query: query, - forceJSONP: this.forceJSONP, - jsonp: this.jsonp, - forceBase64: this.forceBase64, - enablesXDR: this.enablesXDR, - timestampRequests: this.timestampRequests, - timestampParam: this.timestampParam, - policyPort: this.policyPort, - socket: this, - pfx: this.pfx, - key: this.key, - passphrase: this.passphrase, - cert: this.cert, - ca: this.ca, - ciphers: this.ciphers, - rejectUnauthorized: this.rejectUnauthorized, - perMessageDeflate: this.perMessageDeflate, - extraHeaders: this.extraHeaders, - forceNode: this.forceNode, - localAddress: this.localAddress - }); +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) - return transport; -}; + arr = new Arr(len * 3 / 4 - placeHolders) -function clone (obj) { - var o = {}; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; - } - } - return o; -} + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len -/** - * Initializes transport to use and starts probe. - * - * @api private - */ -Socket.prototype.open = function () { - var transport; - if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { - transport = 'websocket'; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function () { - self.emit('error', 'No transports available'); - }, 0); - return; - } else { - transport = this.transports[0]; + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF } - this.readyState = 'opening'; - // Retry with the next transport if the transport is disabled (jsonp: false) - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF } - transport.open(); - this.setTransport(transport); -}; + return arr +} -/** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} -Socket.prototype.setTransport = function (transport) { - debug('setting transport %s', transport.name); - var self = this; +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} - if (this.transport) { - debug('clearing existing transport %s', this.transport.name); - this.transport.removeAllListeners(); +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } - // set up transport - this.transport = transport; + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } - // set up transport listeners - transport - .on('drain', function () { - self.onDrain(); - }) - .on('packet', function (packet) { - self.onPacket(packet); - }) - .on('error', function (e) { - self.onError(e); - }) - .on('close', function () { - self.onClose('transport close'); - }); -}; + parts.push(output) -/** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ + return parts.join('') +} -Socket.prototype.probe = function (name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { probe: 1 }); - var failed = false; - var self = this; +},{}],112:[function(require,module,exports){ +(function (module, exports) { + 'use strict'; - Socket.priorWebsocketSuccess = false; + // Utils + function assert (val, msg) { + if (!val) throw new Error(msg || 'Assertion failed'); + } - function onTransportOpen () { - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; - } - if (failed) return; + // Could use `inherits` module, but don't want to move from single file + // architecture yet. + function inherits (ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } - debug('probe transport "%s" opened', name); - transport.send([{ type: 'ping', data: 'probe' }]); - transport.once('packet', function (msg) { - if (failed) return; - if ('pong' === msg.type && 'probe' === msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit('upgrading', transport); - if (!transport) return; - Socket.priorWebsocketSuccess = 'websocket' === transport.name; + // BN - debug('pausing current transport "%s"', self.transport.name); - self.transport.pause(function () { - if (failed) return; - if ('closed' === self.readyState) return; - debug('changing transport and sending upgrade packet'); + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } - cleanup(); + this.negative = 0; + this.words = null; + this.length = 0; - self.setTransport(transport); - transport.send([{ type: 'upgrade' }]); - self.emit('upgrade', transport); - transport = null; - self.upgrading = false; - self.flush(); - }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error('probe error'); - err.transport = transport.name; - self.emit('upgradeError', err); - } - }); - } + // Reduction context + this.red = null; - function freezeTransport () { - if (failed) return; + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } - // Any callback called by transport should be ignored since now - failed = true; + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } - cleanup(); + BN.BN = BN; + BN.wordSize = 26; - transport.close(); - transport = null; + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { } - // Handle any error that happens while probing - function onerror (err) { - var error = new Error('probe error: ' + err); - error.transport = transport.name; + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } - freezeTransport(); + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; - debug('probe transport "%s" failed because of error: %s', name, err); + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; - self.emit('upgradeError', error); - } + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; - function onTransportClose () { - onerror('transport closed'); - } + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } - // When the socket is closed while we're probing - function onclose () { - onerror('socket closed'); - } + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } - // When the socket is upgraded while we're probing - function onupgrade (to) { - if (transport && to.name !== transport.name) { - debug('"%s" works - aborting "%s"', to.name, transport.name); - freezeTransport(); + if (base === 'hex') { + base = 16; } - } + assert(base === (base | 0) && base >= 2 && base <= 36); - // Remove all listeners on the transport and on self - function cleanup () { - transport.removeListener('open', onTransportOpen); - transport.removeListener('error', onerror); - transport.removeListener('close', onTransportClose); - self.removeListener('close', onclose); - self.removeListener('upgrading', onupgrade); - } + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } - transport.once('open', onTransportOpen); - transport.once('error', onerror); - transport.once('close', onTransportClose); + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } - this.once('close', onclose); - this.once('upgrading', onupgrade); + if (number[0] === '-') { + this.negative = 1; + } - transport.open(); -}; + this.strip(); -/** - * Called when connection is deemed open. - * - * @api public - */ + if (endian !== 'le') return; -Socket.prototype.onOpen = function () { - debug('socket open'); - this.readyState = 'open'; - Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; - this.emit('open'); - this.flush(); + this._initArray(this.toArray(), base, endian); + }; - // we check for `readyState` in case an `open` - // listener already closed the socket - if ('open' === this.readyState && this.upgrade && this.transport.pause) { - debug('starting upgrade probes'); - for (var i = 0, l = this.upgrades.length; i < l; i++) { - this.probe(this.upgrades[i]); + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; } - } -}; -/** - * Handles a packet. - * - * @api private - */ + if (endian !== 'le') return; -Socket.prototype.onPacket = function (packet) { - if ('opening' === this.readyState || 'open' === this.readyState || - 'closing' === this.readyState) { - debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; - this.emit('packet', packet); + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } - // Socket is live - any packet counts - this.emit('heartbeat'); + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } - switch (packet.type) { - case 'open': - this.onHandshake(parsejson(packet.data)); - break; + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; - case 'pong': - this.setPing(); - this.emit('pong'); - break; + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; - case 'error': - var err = new Error('server error'); - err.code = packet.data; - this.onError(err); - break; + r <<= 4; - case 'message': - this.emit('data', packet.data); - this.emit('message', packet.data); - break; - } - } else { - debug('packet received with socket readyState "%s"', this.readyState); - } -}; + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; -/** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; -Socket.prototype.onHandshake = function (data) { - this.emit('handshake', data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); - // In case open handler closes socket - if ('closed' === this.readyState) return; - this.setPing(); + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } - // Prolong liveness of socket on heartbeat - this.removeListener('heartbeat', this.onHeartbeat); - this.on('heartbeat', this.onHeartbeat); -}; + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } -/** - * Resets ping timeout. - * - * @api private - */ + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; -Socket.prototype.onHeartbeat = function (timeout) { - clearTimeout(this.pingTimeoutTimer); - var self = this; - self.pingTimeoutTimer = setTimeout(function () { - if ('closed' === self.readyState) return; - self.onClose('ping timeout'); - }, timeout || (self.pingInterval + self.pingTimeout)); -}; + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; -/** - * Pings server every `this.pingInterval` and expects response - * within `this.pingTimeout` or closes connection. - * - * @api private - */ + r *= mul; -Socket.prototype.setPing = function () { - var self = this; - clearTimeout(self.pingIntervalTimer); - self.pingIntervalTimer = setTimeout(function () { - debug('writing ping packet - expecting pong within %sms', self.pingTimeout); - self.ping(); - self.onHeartbeat(self.pingTimeout); - }, self.pingInterval); -}; + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; -/** -* Sends a ping packet. -* -* @api private -*/ + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; -Socket.prototype.ping = function () { - var self = this; - this.sendPacket('ping', function () { - self.emit('ping'); - }); -}; + // '0' - '9' + } else { + r += c; + } + } + return r; + } -/** - * Called on `drain` event - * - * @api private - */ + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; -Socket.prototype.onDrain = function () { - this.writeBuffer.splice(0, this.prevBufferLen); + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - if (0 === this.writeBuffer.length) { - this.emit('drain'); - } else { - this.flush(); - } -}; + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); -/** - * Flush write buffers. - * - * @api private - */ + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } -Socket.prototype.flush = function () { - if ('closed' !== this.readyState && this.transport.writable && - !this.upgrading && this.writeBuffer.length) { - debug('flushing %d packets in socket', this.writeBuffer.length); - this.transport.send(this.writeBuffer); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = this.writeBuffer.length; - this.emit('flush'); - } -}; + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); -/** - * Sends a message. - * - * @param {String} message. - * @param {Function} callback function. - * @param {Object} options. - * @return {Socket} for chaining. - * @api public - */ + for (i = 0; i < mod; i++) { + pow *= base; + } -Socket.prototype.write = -Socket.prototype.send = function (msg, options, fn) { - this.sendPacket('message', msg, options, fn); - return this; -}; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; -/** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} callback function. - * @api private - */ + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; -Socket.prototype.sendPacket = function (type, data, options, fn) { - if ('function' === typeof data) { - fn = data; - data = undefined; - } + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; - if ('function' === typeof options) { - fn = options; - options = null; - } + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; - if ('closing' === this.readyState || 'closed' === this.readyState) { - return; - } + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; - options = options || {}; - options.compress = false !== options.compress; + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; - var packet = { - type: type, - data: data, - options: options + BN.prototype.inspect = function inspect () { + return (this.red ? ''; }; - this.emit('packetCreate', packet); - this.writeBuffer.push(packet); - if (fn) this.once('flush', fn); - this.flush(); -}; -/** - * Closes the connection. - * - * @api private - */ + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; -Socket.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.readyState = 'closing'; + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; - var self = this; + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; - if (this.writeBuffer.length) { - this.once('drain', function () { - if (this.upgrading) { - waitForUpgrade(); + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; } else { - close(); + out = word + out; } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; } - } - function close () { - self.onClose('forced close'); - debug('socket closing - telling transport to close'); - self.transport.close(); - } + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } - function cleanupAndClose () { - self.removeListener('upgrade', cleanupAndClose); - self.removeListener('upgradeError', cleanupAndClose); - close(); - } + assert(false, 'Base should be between 2 and 36'); + }; - function waitForUpgrade () { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once('upgrade', cleanupAndClose); - self.once('upgradeError', cleanupAndClose); - } + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; - return this; -}; + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; -/** - * Called upon transport error - * - * @api private - */ + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; -Socket.prototype.onError = function (err) { - debug('socket error %j', err); - Socket.priorWebsocketSuccess = false; - this.emit('error', err); - this.onClose('transport error', err); -}; + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; -/** - * Called upon transport close. - * - * @api private - */ + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } -Socket.prototype.onClose = function (reason, desc) { - if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { - debug('socket close with reason: "%s"', reason); - var self = this; + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - // clear timers - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); - // stop event from firing again for transport - this.transport.removeAllListeners('close'); + res[i] = b; + } - // ensure transport won't stay open - this.transport.close(); + for (; i < reqLength; i++) { + res[i] = 0; + } + } - // ignore further transport communication - this.transport.removeAllListeners(); + return res; + }; - // set ready state - this.readyState = 'closed'; + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } - // clear session id - this.id = null; + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; - // emit close event - this.emit('close', reason, desc); + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; - // clean buffers after, so users can still - // grab the buffers on `close` event - self.writeBuffer = []; - self.prevBufferLen = 0; - } -}; + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; -/** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ + function toBitArray (num) { + var w = new Array(num.bitLength()); -Socket.prototype.filterUpgrades = function (upgrades) { - var filteredUpgrades = []; - for (var i = 0, j = upgrades.length; i < j; i++) { - if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); - } - return filteredUpgrades; -}; + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./transport":33,"./transports/index":34,"component-emitter":40,"debug":41,"engine.io-parser":44,"indexof":53,"parsejson":59,"parseqs":60,"parseuri":61}],33:[function(require,module,exports){ -/** - * Module dependencies. - */ + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } -var parser = require('engine.io-parser'); -var Emitter = require('component-emitter'); + return w; + } -/** - * Module exports. - */ + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; -module.exports = Transport; + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; -/** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private - */ + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; -function Transport (opts) { - this.path = opts.path; - this.hostname = opts.hostname; - this.port = opts.port; - this.secure = opts.secure; - this.query = opts.query; - this.timestampParam = opts.timestampParam; - this.timestampRequests = opts.timestampRequests; - this.readyState = ''; - this.agent = opts.agent || false; - this.socket = opts.socket; - this.enablesXDR = opts.enablesXDR; + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - this.forceNode = opts.forceNode; + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - this.localAddress = opts.localAddress; -} + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; -/** - * Mix in `Emitter`. - */ + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; -Emitter(Transport.prototype); + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } -/** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ + return this; + }; -Transport.prototype.onError = function (msg, desc) { - var err = new Error(msg); - err.type = 'TransportError'; - err.description = desc; - this.emit('error', err); - return this; -}; + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } -/** - * Opens the transport. - * - * @api public - */ + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } -Transport.prototype.open = function () { - if ('closed' === this.readyState || '' === this.readyState) { - this.readyState = 'opening'; - this.doOpen(); - } + return this.strip(); + }; - return this; -}; + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; -/** - * Closes the transport. - * - * @api private - */ + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; -Transport.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.doClose(); - this.onClose(); - } + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; - return this; -}; + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } -/** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } -Transport.prototype.send = function (packets) { - if ('open' === this.readyState) { - this.write(packets); - } else { - throw new Error('Transport not open'); - } -}; + this.length = b.length; -/** - * Called upon open - * - * @api private - */ + return this.strip(); + }; -Transport.prototype.onOpen = function () { - this.readyState = 'open'; - this.writable = true; - this.emit('open'); -}; + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; -/** - * Called with data. - * - * @param {String} data - * @api private - */ + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; -Transport.prototype.onData = function (data) { - var packet = parser.decodePacket(data, this.socket.binaryType); - this.onPacket(packet); -}; + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; -/** - * Called with a decoded packet. - */ + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } -Transport.prototype.onPacket = function (packet) { - this.emit('packet', packet); -}; + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } -/** - * Called upon close. - * - * @api private - */ + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } -Transport.prototype.onClose = function () { - this.readyState = 'closed'; - this.emit('close'); -}; + this.length = a.length; -},{"component-emitter":40,"engine.io-parser":44}],34:[function(require,module,exports){ -(function (global){ -/** - * Module dependencies - */ + return this.strip(); + }; -var XMLHttpRequest = require('xmlhttprequest-ssl'); -var XHR = require('./polling-xhr'); -var JSONP = require('./polling-jsonp'); -var websocket = require('./websocket'); + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; -/** - * Export transports. - */ + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; -exports.polling = polling; -exports.websocket = websocket; + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; -/** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); -function polling (opts) { - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; - if (global.location) { - var isSSL = 'https:' === location.protocol; - var port = location.port; + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; + if (bitsLeft > 0) { + bytesNeeded--; } - xd = opts.hostname !== location.hostname || port !== opts.port; - xs = opts.secure !== isSSL; - } + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } - opts.xdomain = xd; - opts.xscheme = xs; - xhr = new XMLHttpRequest(opts); + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } - if ('open' in xhr && !opts.forceJSONP) { - return new XHR(opts); - } else { - if (!jsonp) throw new Error('JSONP disabled'); - return new JSONP(opts); - } -} + // And remove leading zeroes + return this.strip(); + }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./polling-jsonp":35,"./polling-xhr":36,"./websocket":38,"xmlhttprequest-ssl":39}],35:[function(require,module,exports){ -(function (global){ + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; -/** - * Module requirements. - */ + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); -var Polling = require('./polling'); -var inherit = require('component-inherit'); + var off = (bit / 26) | 0; + var wbit = bit % 26; -/** - * Module exports. - */ + this._expand(off + 1); -module.exports = JSONPPolling; + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } -/** - * Cached regular expressions. - */ + return this.strip(); + }; -var rNewline = /\n/g; -var rEscapedNewline = /\\n/g; + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } -/** - * Global JSONP callbacks. - */ + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } -var callbacks; + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } -/** - * Noop. - */ + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } -function empty () { } + return this; + }; -/** - * JSONP Polling constructor. - * - * @param {Object} opts. - * @api public - */ + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } -function JSONPPolling (opts) { - Polling.call(this, opts); + if (this.length > num.length) return this.clone().iadd(num); - this.query = this.query || {}; + return num.clone().iadd(this); + }; - // define global callbacks array if not present - // we do this here (lazily) to avoid unneeded global pollution - if (!callbacks) { - // we need to consider multiple engines in the same page - if (!global.___eio) global.___eio = []; - callbacks = global.___eio; - } + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } - // callback identifier - this.index = callbacks.length; + // At this point both numbers are positive + var cmp = this.cmp(num); - // add callback to jsonp global - var self = this; - callbacks.push(function (msg) { - self.onData(msg); - }); + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } - // append to query string - this.query.j = this.index; + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - // prevent spurious errors from being emitted when the window is unloaded - if (global.document && global.addEventListener) { - global.addEventListener('beforeunload', function () { - if (self.script) self.script.onerror = empty; - }, false); - } -} + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } -/** - * Inherits from Polling. - */ + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } -inherit(JSONPPolling, Polling); + this.length = Math.max(this.length, i); -/* - * JSONP only supports binary as base64 encoded strings - */ + if (a !== this) { + this.negative = 1; + } -JSONPPolling.prototype.supportsBinary = false; + return this.strip(); + }; -/** - * Closes the socket. - * - * @api private - */ + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; -JSONPPolling.prototype.doClose = function () { - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); } - if (this.form) { - this.form.parentNode.removeChild(this.form); - this.form = null; - this.iframe = null; + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); } - Polling.prototype.doClose.call(this); -}; + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } -/** - * Starts a poll cycle. - * - * @api private - */ + return res; + }; -JSONPPolling.prototype.doPoll = function () { - var self = this; - var script = document.createElement('script'); + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; + function FFTM (x, y) { + this.x = x; + this.y = y; } - script.async = true; - script.src = this.uri(); - script.onerror = function (e) { - self.onError('jsonp poll error', e); + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; }; - var insertAt = document.getElementsByTagName('script')[0]; - if (insertAt) { - insertAt.parentNode.insertBefore(script, insertAt); - } else { - (document.head || document.body).appendChild(script); - } - this.script = script; + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; - var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } - if (isUAgecko) { - setTimeout(function () { - var iframe = document.createElement('iframe'); - document.body.appendChild(iframe); - document.body.removeChild(iframe); - }, 100); - } -}; + return rb; + }; -/** - * Writes with a hidden iframe. - * - * @param {String} data to send - * @param {Function} called upon flush. - * @api private - */ + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; -JSONPPolling.prototype.doWrite = function (data, fn) { - var self = this; + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); - if (!this.form) { - var form = document.createElement('form'); - var area = document.createElement('textarea'); - var id = this.iframeId = 'eio_iframe_' + this.index; - var iframe; + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; - form.className = 'socketio'; - form.style.position = 'absolute'; - form.style.top = '-1000px'; - form.style.left = '-1000px'; - form.target = id; - form.method = 'POST'; - form.setAttribute('accept-charset', 'utf-8'); - area.name = 'd'; - form.appendChild(area); - document.body.appendChild(form); + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); - this.form = form; - this.area = area; - } + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; - this.form.action = this.uri(); + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; - function complete () { - initIframe(); - fn(); - } + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; - function initIframe () { - if (self.iframe) { - try { - self.form.removeChild(self.iframe); - } catch (e) { - self.onError('jsonp polling iframe removal error', e); + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } } } + }; - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - var html = '