├── .gitignore ├── LICENSE ├── README.md ├── algorithm_application.js ├── algorithm_interface.js ├── algorithms ├── follow_bitstamp.algo ├── follow_mercadobitcoin.algo ├── market_maker.algo └── smart_order.algo ├── main.js └── node_modules └── websocket ├── .jshintrc ├── CHANGELOG.md ├── LICENSE ├── Makefile ├── README.md ├── binding.gyp ├── build ├── Makefile ├── Release │ ├── .deps │ │ └── Release │ │ │ ├── bufferutil.node.d │ │ │ ├── obj.target │ │ │ ├── bufferutil │ │ │ │ └── src │ │ │ │ │ └── bufferutil.o.d │ │ │ └── validation │ │ │ │ └── src │ │ │ │ └── validation.o.d │ │ │ └── validation.node.d │ ├── bufferutil.node │ ├── linker.lock │ ├── obj.target │ │ ├── bufferutil │ │ │ └── src │ │ │ │ └── bufferutil.o │ │ └── validation │ │ │ └── src │ │ │ └── validation.o │ └── validation.node ├── binding.Makefile ├── bufferutil.target.mk ├── config.gypi ├── gyp-mac-tool └── validation.target.mk ├── builderror.log ├── docs ├── W3CWebSocket.md ├── WebSocketClient.md ├── WebSocketConnection.md ├── WebSocketFrame.md ├── WebSocketRequest.md ├── WebSocketServer.md └── index.md ├── gulpfile.js ├── index.js ├── lib ├── BufferUtil.fallback.js ├── BufferUtil.js ├── Deprecation.js ├── Validation.fallback.js ├── Validation.js ├── W3CWebSocket.js ├── WebSocketClient.js ├── WebSocketConnection.js ├── WebSocketFrame.js ├── WebSocketRequest.js ├── WebSocketRouter.js ├── WebSocketRouterRequest.js ├── WebSocketServer.js ├── browser.js ├── utils.js ├── version.js └── websocket.js ├── node_modules ├── debug │ ├── .jshintrc │ ├── .npmignore │ ├── History.md │ ├── Makefile │ ├── Readme.md │ ├── bower.json │ ├── browser.js │ ├── component.json │ ├── debug.js │ ├── node.js │ ├── node_modules │ │ └── ms │ │ │ ├── .npmignore │ │ │ ├── README.md │ │ │ ├── index.js │ │ │ └── package.json │ └── package.json ├── nan │ ├── .dntrc │ ├── LICENSE │ ├── README.md │ ├── build │ │ └── config.gypi │ ├── include_dirs.js │ ├── nan.h │ └── package.json └── typedarray-to-buffer │ ├── .travis.yml │ ├── .zuul.yml │ ├── LICENSE │ ├── README.md │ ├── index.js │ ├── node_modules │ └── is-typedarray │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── index.js │ │ ├── package.json │ │ └── test.js │ ├── package.json │ └── test │ └── basic.js ├── package.json ├── src ├── bufferutil.cc └── validation.cc └── vendor └── FastBufferList.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea/ 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### algorithm-trading ( DOCUMENTATION IS INCOMPLETE, TAKE A LOOK AT THE [EXAMPLES](https://github.com/blinktrade/algorithm-trading/tree/master/algorithms) ) 2 | 3 | 4 | This repository contains algorithm trading programs ( AKA trading strategies, trading bot ) which are compatible with all exchanges running the blinktrade platform. Those algorithms are executed in the users browser context and not in the servers. 5 | 6 | ### Pre-requisites to create your own algorithm trading 7 | - Basic knowledge of JavaScript 8 | - Curiosity 9 | 10 | ### Is there a test environment to test my algorithms? 11 | - Yes, [blinktrade tesnet exchange](https://testnet.blinktrade.com/) 12 | 13 | 14 | ### List of blinktrade approved algorithm trading strategies 15 | - [market_maker.algo ** incomplete **](https://github.com/blinktrade/algorithm-trading/blob/master/algorithms/market_maker.algo) 16 | 17 | 18 | ### Basic structure of an algorithm 19 | ```JavaScript 20 | -----BEGIN ALGO DEFINITION----- 21 | { 22 | "id": "any_id_here", 23 | "description": "Description of what your algorithm does", 24 | "params": [ 25 | {"name":"your_parameter_1", "label":"Your Parammeter #1", "type":"text", "value":"0", "validator":"required; validateNumber; validateMin 10; validateMax 1000;" }, 26 | {"name":"your_parameter_2", "label":"Your Parammeter #2", "type":"text", "value":"5", "validator":"required; validateInteger; validateMin 1; validateMax 5;" } 27 | ], 28 | "creator": "name_of_the_function_which_the_exchange_will_invoke_to_create_an_instance_of_your_algo", 29 | "destructor": "name_of_the_functions_which_the_exchange_will_invoke_when_destroying_the_instance_of_your_algo", 30 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 31 | } 32 | -----END ALGO DEFINITION----- 33 | -----BEGIN ALGO----- 34 | // define a class that implements the following interface [interface](https://github.com/blinktrade/algorithm-trading/blob/master/algorithm_interface.js) here 35 | 36 | function name_of_the_function_which_the_exchange_will_invoke_to_create_an_instance_of_your_algo() { 37 | return new MyAlgo(); 38 | } 39 | 40 | function name_of_the_functions_which_the_exchange_will_invoke_when_destroying_the_instance_of_your_algo(instance_of_my_algo) { 41 | delete instance_of_my_algo; 42 | } 43 | -----END ALGO----- 44 | ``` 45 | 46 | ### How does it work 47 | The exchange expects you to create a javascript class that implements the following [interface](https://github.com/blinktrade/algorithm-trading/blob/master/algorithm_interface.js) 48 | 49 | 50 | 51 | ### List of exchanges running blinktrade platform 52 | - [chilebit](https://chilebit.net) 53 | - [foxbit](https://foxbit.com.br) 54 | - [VBTC](https://vbtc.vn) 55 | - [surbitcoin](https://surbitcoin.com) 56 | - [urdubit](https://urdubit.com) 57 | -------------------------------------------------------------------------------- /algorithm_interface.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @param {Application} application 4 | * @param {string} symbol 5 | * @constructor 6 | */ 7 | var AlgorithmTradingInterface = function(application, symbol){}; 8 | 9 | /** 10 | * @enum {string} Balance Types 11 | */ 12 | AlgorithmTradingInterface.BalanceType = { 13 | DEPOSIT : 'deposit', 14 | LOCKED: 'locked', 15 | AVAILABLE: 'available' 16 | }; 17 | 18 | /** 19 | * Invoked when your algorithm is ready to run. 20 | * Don't try to send orders before the start method. 21 | * @param {Object.} params 22 | */ 23 | AlgorithmTradingInterface.prototype.start = function(params) { }; 24 | 25 | /** 26 | * Invoked before the system stops your algo. Do your cleanup here 27 | */ 28 | AlgorithmTradingInterface.prototype.stop = function() { }; 29 | 30 | 31 | /** 32 | * Invoked whenever your balance change 33 | * @param {string} currency 34 | * @param {number} balance 35 | * @param {AlgorithmTradingInterface.BalanceType} balance_type 36 | */ 37 | AlgorithmTradingInterface.prototype.onBalanceUpdate = function(currency, balance, balance_type) { }; 38 | 39 | 40 | /** 41 | * Invoked when you update your parameters. 42 | * @param {Object.} params 43 | */ 44 | AlgorithmTradingInterface.prototype.onUpdateParams = function(params) { }; 45 | 46 | 47 | /** 48 | * Invoked to report the arrival of a new order, and executions on it. 49 | * @param {Object.} msg 50 | * @see {http://btobits.com/fixopaedia/fixdic44/message_Execution_Report_8_.html} 51 | */ 52 | AlgorithmTradingInterface.prototype.onExecutionReport = function(msg) { }; 53 | 54 | 55 | /** 56 | * Invoked when there was a change in the order book 57 | * @param {Array.>} order_book 58 | */ 59 | AlgorithmTradingInterface.prototype.onOrderBookChange = function(order_book) { }; 60 | 61 | 62 | /** 63 | * Invoked when there is a change in the ticker 64 | * @param {Object.} msg 65 | */ 66 | AlgorithmTradingInterface.prototype.onTicker = function(msg) { }; 67 | 68 | 69 | /** 70 | * Invoked when a new order arrives in the order book 71 | * @param {Object.} msg 72 | */ 73 | AlgorithmTradingInterface.prototype.onOrderBookNewOrder = function(msg) { }; 74 | 75 | 76 | /** 77 | * Invoked when an order gets updated in the order book 78 | * @param {Object.} msg 79 | */ 80 | AlgorithmTradingInterface.prototype.onOrderBookUpdateOrder = function(msg) { }; 81 | 82 | 83 | /** 84 | * Invoked when an order gets deleted from the order book 85 | * @param {Object.} msg 86 | */ 87 | AlgorithmTradingInterface.prototype.onOrderBookDeleteOrder = function(msg) { }; 88 | 89 | 90 | /** 91 | * Invoked when one or more orders gets deleted from the order book 92 | * @param {Object.} msg 93 | */ 94 | AlgorithmTradingInterface.prototype.onOrderBookDeleteOrdersThru = function(msg) { }; 95 | 96 | 97 | /** 98 | * Invoked when there is a new trade in the exchange 99 | * @param {Object.} msg 100 | */ 101 | AlgorithmTradingInterface.prototype.onTrade = function(msg) { }; -------------------------------------------------------------------------------- /algorithms/follow_bitstamp.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "bitstamp", 5 | "description": "Notifies the user when there is a new best bid/ask and trade at BitStamp", 6 | "params": [ 7 | {"name":"exchange_rate", "label":"Dollar exchange rate", "type":"text", "value":"1", "validator":"required; validateNumber; validateMin 0;" } 8 | ], 9 | "creator": "blinktrade.FollowBitStampAlgo.create", 10 | "destructor": "blinktrade.FollowBitStampAlgo.destroy", 11 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 12 | } 13 | -----END ALGO DEFINITION----- 14 | -----BEGIN ALGO----- 15 | /**/ 16 | 17 | 18 | /** 19 | * Namespace. 20 | */ 21 | var blinktrade = {}; 22 | 23 | 24 | /** 25 | * @param {Object} application 26 | * @param {string} symbol 27 | * @constructor 28 | */ 29 | blinktrade.FollowBitStampAlgo = function(application, symbol){ 30 | this.application_ = application; 31 | this.symbol_ = symbol; 32 | this.bitstamp_order_book_channel_subscription_ = false; 33 | }; 34 | 35 | /** 36 | * @type {boolean} 37 | */ 38 | blinktrade.FollowBitStampAlgo.prototype.bitstamp_order_book_channel_subscription_; 39 | 40 | /** 41 | * @type {number} 42 | */ 43 | blinktrade.FollowBitStampAlgo.prototype.last_best_bid_; 44 | 45 | /** 46 | * @type {number} 47 | */ 48 | blinktrade.FollowBitStampAlgo.prototype.last_best_ask_; 49 | 50 | 51 | /** 52 | * @param {Application} application 53 | * @param {string} symbol 54 | * @return {blinktrade.FollowBitStampAlgo} 55 | */ 56 | blinktrade.FollowBitStampAlgo.create = function(application,symbol) { 57 | return new blinktrade.FollowBitStampAlgo(application,symbol); 58 | }; 59 | 60 | /** 61 | * @param {Object} params 62 | */ 63 | blinktrade.FollowBitStampAlgo.prototype.start = function(params) { 64 | this.ws_pusher_ = new WebSocket('wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?protocol=7&client=js&version=2.1.6&flash=false'); 65 | this.ws_pusher_.onopen = goog.bind(this.onPusherOpen_, this); 66 | this.ws_pusher_.onmessage = goog.bind(this.onPusherMessage_, this); 67 | this.ws_pusher_.onclose = goog.bind(this.onPusherClose_, this); 68 | }; 69 | 70 | blinktrade.FollowBitStampAlgo.prototype.onPusherOpen_ = function() { 71 | this.ws_pusher_.send( JSON.stringify({"event":"pusher:subscribe","data":{"channel":"order_book"}})); 72 | this.ws_pusher_.send( JSON.stringify({"event":"pusher:subscribe","data":{"channel":"live_trades"}})); 73 | }; 74 | 75 | blinktrade.FollowBitStampAlgo.prototype.onPusherClose_ = function() { 76 | this.application_.stop('Problems with pusher'); 77 | }; 78 | 79 | blinktrade.FollowBitStampAlgo.prototype.onPusherMessage_ = function (e) { 80 | var msg = JSON.parse(e.data); 81 | switch(msg["event"]) { 82 | case 'pusher:error': 83 | this.stop( msg["data"]["message"] ); 84 | break; 85 | case 'pusher_internal:subscription_succeeded': 86 | if (msg["channel"] == "order_book") { 87 | this.bitstamp_order_book_channel_subscription_ = true; 88 | } 89 | break; 90 | case 'data': 91 | switch(msg["channel"]){ 92 | case "order_book": 93 | this.onBitStampOrderBookData(JSON.parse(msg["data"])); 94 | return; 95 | case "live_trades": 96 | this.onBitStampTrade(JSON.parse(msg["data"])); 97 | return; 98 | } 99 | } 100 | }; 101 | 102 | /** 103 | * @param {Object} trade 104 | */ 105 | blinktrade.FollowBitStampAlgo.prototype.onBitStampTrade = function(trade) { 106 | var exchange_rate = parseFloat(this.application_.getParameters()['exchange_rate']); 107 | this.application_.showNotification('BitStamp trade', 108 | 'price:' + parseFloat(trade['price']) * exchange_rate + ', amount:' + trade['amount'], 'error' ); 109 | }; 110 | 111 | /** 112 | * @param {Object.>> } order_book 113 | */ 114 | blinktrade.FollowBitStampAlgo.prototype.onBitStampOrderBookData = function(order_book) { 115 | var exchange_rate = parseFloat(this.application_.getParameters()['exchange_rate']); 116 | 117 | var best_bid = parseFloat(order_book['bids'][0][0]) * exchange_rate; 118 | var best_ask = parseFloat(order_book['asks'][0][0]) * exchange_rate; 119 | 120 | if (this.last_best_bid_ != best_bid) { 121 | this.last_best_bid_ = best_bid; 122 | this.application_.showNotification('BitStamp', 'The new best bid is ' + best_bid, 'success' ); 123 | } 124 | 125 | 126 | if ( this.last_best_ask_ != best_ask ) { 127 | this.last_best_ask_ = best_ask; 128 | this.application_.showNotification('BitStamp', 'The new best ask is ' + best_ask, 'info' ); 129 | } 130 | }; 131 | 132 | blinktrade.FollowBitStampAlgo.prototype.stop = function() { 133 | this.ws_pusher_.close(); 134 | }; 135 | 136 | //-----END ALGO----- 137 | -------------------------------------------------------------------------------- /algorithms/follow_mercadobitcoin.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "bitstamp", 5 | "description": "Notifies the user when there is a new best bid/ask at MercadoBitcoin", 6 | "params": [], 7 | "creator": "blinktrade.FollowMercadoBitcoin.create", 8 | "destructor": "blinktrade.FollowMercadoBitcoin.destroy", 9 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"] 10 | } 11 | -----END ALGO DEFINITION----- 12 | -----BEGIN ALGO----- 13 | /**/ 14 | 15 | 16 | /** 17 | * Namespace. 18 | */ 19 | var blinktrade = {}; 20 | 21 | /** 22 | * Workaround using yahoo yql api to make cross domain requests 23 | * @param {string} url 24 | * @param {function(*)} fn 25 | * @param {Object} selfObj 26 | */ 27 | function crossDomainRequest( url, fn, selfObj) { 28 | var callback_function_name = 'yqlCallback' + parseInt(Math.random() * 1000000, 10); 29 | self[callback_function_name] = function( yqlResult ) { 30 | goog.bind(fn,selfObj, yqlResult.query.results)(); 31 | }; 32 | 33 | var yql = 'select * from json where url="' + url + '"'; 34 | var uri = 'https://query.yahooapis.com/v1/public/yql?q=' + 35 | encodeURIComponent(yql) + '&format=json&callback=' + callback_function_name ; 36 | importScripts(uri); 37 | } 38 | 39 | /** 40 | * @param {Object} application 41 | * @param {string} symbol 42 | * @constructor 43 | */ 44 | blinktrade.FollowMercadoBitcoin = function(application, symbol){ 45 | this.application_ = application; 46 | this.symbol_ = symbol; 47 | global_instance = this; 48 | 49 | }; 50 | 51 | /** 52 | * @type {number} 53 | */ 54 | blinktrade.FollowMercadoBitcoin.prototype.last_best_bid_; 55 | 56 | /** 57 | * @type {number} 58 | */ 59 | blinktrade.FollowMercadoBitcoin.prototype.last_best_ask_; 60 | 61 | /** 62 | * @param {Application} application 63 | * @param {string} symbol 64 | * @return {blinktrade.FollowMercadoBitcoin} 65 | */ 66 | blinktrade.FollowMercadoBitcoin.create = function(application,symbol) { 67 | return new blinktrade.FollowMercadoBitcoin(application,symbol); 68 | }; 69 | 70 | /** 71 | * @param {Object} params 72 | */ 73 | blinktrade.FollowMercadoBitcoin.prototype.start = function(params) { 74 | console.log('blinktrade.FollowMercadoBitcoin.prototype.start'); 75 | this.timer_ = setInterval(goog.bind(crossDomainRequest, 76 | this, 77 | 'https://www.mercadobitcoin.net/api/v2/ticker/', 78 | this.onMBCallBack_, 79 | this ), 6000 ); // every 60 seconds 80 | }; 81 | 82 | 83 | blinktrade.FollowMercadoBitcoin.prototype.stop = function() { 84 | clearInterval(this.timer_); 85 | }; 86 | 87 | /** 88 | * @param {Object.} params 89 | */ 90 | blinktrade.FollowMercadoBitcoin.prototype.onUpdateParams = function(params) {}; 91 | 92 | 93 | 94 | blinktrade.FollowMercadoBitcoin.prototype.onMBCallBack_ = function(ticker){ 95 | var best_bid = parseFloat(ticker['ticker']['buy']); 96 | var best_ask = parseFloat(ticker['ticker']['sell']); 97 | 98 | if (this.last_best_bid_ != best_bid) { 99 | this.last_best_bid_ = best_bid; 100 | this.application_.showNotification('MercadoBitcoin', 'The new best bid is ' + best_bid, 'success' ); 101 | } 102 | 103 | if ( this.last_best_ask_ != best_ask ) { 104 | this.last_best_ask_ = best_ask; 105 | this.application_.showNotification('MercadoBitcoin', 'The new best ask is ' + best_ask, 'info' ); 106 | } 107 | }; 108 | 109 | //-----END ALGO----- 110 | -------------------------------------------------------------------------------- /algorithms/smart_order.algo: -------------------------------------------------------------------------------- 1 | /* 2 | -----BEGIN ALGO DEFINITION----- 3 | { 4 | "id": "blinktrade", 5 | "description": "Make sure your order is always on top", 6 | "params": [ 7 | {"name":"side", "label":"Buy(1) / Sell(2)", "type":"number", "value":"1", "filter":"positive_number", "validator":"required; validateMin 1; validateMax 2; validateNumber;" }, 8 | {"name":"qty", "label":"Qty", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" }, 9 | {"name":"min_price", "label":"Minimum Price", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" }, 10 | {"name":"max_price", "label":"Maximum Price", "type":"number", "value":"" , "filter":"positive_number", "validator":"required; validateMin 0; validateNumber;" } 11 | ], 12 | "creator": "blinktrade.SmartOrderAlgo.create", 13 | "destructor": "blinktrade.SmartOrderAlgo.destroy", 14 | "permissions": ["notification", "balance", "execution_report", "new_order_limited", "cancel_order"], 15 | "tickers" : ["UOL:USDBRT","BITFINEX:BTCUSD", "OKCOIN:BTCCNY"] 16 | } 17 | -----END ALGO DEFINITION----- 18 | -----BEGIN ALGO----- 19 | /**/ 20 | 21 | /** 22 | * Namespace. 23 | */ 24 | var blinktrade = {}; 25 | 26 | /** 27 | * @param {Object} application 28 | * @param {string} symbol 29 | * @constructor 30 | */ 31 | blinktrade.SmartOrderAlgo = function(application, symbol){ 32 | this.application_ = application; 33 | this.symbol_ = symbol; 34 | 35 | this.my_orders_prefix_ = 'p' + parseInt( 1e4 * Math.random() , 10 ) + '_'; 36 | this.price_increment_ = 0.01; 37 | }; 38 | 39 | /** 40 | * @type {Object} 41 | */ 42 | blinktrade.SmartOrderAlgo.prototype.current_order_; 43 | 44 | 45 | /** 46 | * @type {number} 47 | */ 48 | blinktrade.SmartOrderAlgo.prototype.target_price_; 49 | 50 | 51 | /** 52 | * @param {Application} application 53 | * @param {string} symbol 54 | * @return {blinktrade.SmartOrderAlgo} 55 | */ 56 | blinktrade.SmartOrderAlgo.create = function(application,symbol) { 57 | return new blinktrade.SmartOrderAlgo(application,symbol); 58 | }; 59 | 60 | /** 61 | * @param {Object} params 62 | */ 63 | blinktrade.SmartOrderAlgo.prototype.start = function(params) { 64 | this.target_qty_ = params['qty'] * 1e8; 65 | 66 | this.cancellAlgoOrders(); 67 | this.sendOrders(); 68 | 69 | this.timer_ = setInterval(goog.bind(this.sendOrders, this), 1000 ); // every 1 second 70 | }; 71 | 72 | blinktrade.SmartOrderAlgo.prototype.stop = function() { 73 | clearInterval(this.timer_); 74 | this.cancellAlgoOrders(); 75 | }; 76 | 77 | /** 78 | * @param {Object} msg 79 | */ 80 | blinktrade.SmartOrderAlgo.prototype.onTicker = function(msg) { 81 | console.log(msg); 82 | }; 83 | 84 | /** 85 | * @param {Object.} params 86 | */ 87 | blinktrade.SmartOrderAlgo.prototype.onUpdateParams = function(params) { 88 | if (params['qty'] * 1e8 !== this.target_qty_) { 89 | this.target_qty_ = params['qty'] * 1e8; 90 | this.cancellAlgoOrders(); 91 | } 92 | this.sendOrders(); 93 | }; 94 | 95 | /** 96 | * 97 | * @param {Object.} msg 98 | */ 99 | blinktrade.SmartOrderAlgo.prototype.onExecutionReport = function(msg) { 100 | this.target_qty_ = msg['LeavesQty']; 101 | }; 102 | 103 | 104 | blinktrade.SmartOrderAlgo.prototype.cancellAlgoOrders = function() { 105 | if (goog.isDefAndNotNull(this.current_order_)) { 106 | this.application_.cancelOrder(this.current_order_['ClOrdID']); 107 | } 108 | this.current_order_ = null; 109 | }; 110 | 111 | 112 | blinktrade.SmartOrderAlgo.prototype.sendOrders = function() { 113 | var params = this.application_.getParameters(); 114 | var max_price = params["max_price"] * 1e8; 115 | var min_price = params["min_price"] * 1e8; 116 | 117 | if (this.target_qty_ < 10000) { // minimum qty 118 | return; 119 | } 120 | 121 | var order_book = this.application_.getOrderBook(); 122 | 123 | var best_market_price; 124 | var order_at_top_of_the_book; 125 | var counter_order_at_top_of_the_book; 126 | 127 | 128 | if (params["side"] == 1) { 129 | order_at_top_of_the_book = order_book["bids"][0]; 130 | counter_order_at_top_of_the_book = order_book["asks"][0]; 131 | } else { 132 | order_at_top_of_the_book = order_book["asks"][0]; 133 | counter_order_at_top_of_the_book = order_book["bids"][0]; 134 | } 135 | 136 | var do_i_have_the_best_order = false; 137 | if (goog.isDefAndNotNull(this.current_order_)) { 138 | do_i_have_the_best_order = (this.current_order_['Price'] == order_at_top_of_the_book[0] && 139 | this.current_order_['Qty'] == order_at_top_of_the_book[1]); 140 | } 141 | 142 | var price_better_than_the_current_order_price = order_at_top_of_the_book[0]; 143 | if (do_i_have_the_best_order) { 144 | var book_side = "bids"; 145 | if (params["side"] == 2) { 146 | book_side = "asks"; 147 | } 148 | 149 | for (var i =1; i < order_book[book_side].length; ++i ) { 150 | if ( (book_side == "bids" && order_book[book_side][i][0] < price_better_than_the_current_order_price) 151 | || (book_side == "asks" && order_book[book_side][i][0] > price_better_than_the_current_order_price) ) { 152 | price_better_than_the_current_order_price = order_book[book_side][i][0]; 153 | break; 154 | } 155 | } 156 | } 157 | 158 | 159 | if (params["side"] == 1 ) { // BUY 160 | price_better_than_the_current_order_price = 161 | price_better_than_the_current_order_price + (this.price_increment_ * 1e8); 162 | } else if (params["side"] == 2 ) { // SELL 163 | price_better_than_the_current_order_price = 164 | price_better_than_the_current_order_price - (this.price_increment_ * 1e8); 165 | } 166 | 167 | // find the target price now 168 | if (params["side"] == 1 ) { // BUY 169 | if (price_better_than_the_current_order_price <= max_price && price_better_than_the_current_order_price >= min_price ){ 170 | this.target_price_ = price_better_than_the_current_order_price; 171 | } else if (price_better_than_the_current_order_price >= max_price ) { 172 | this.target_price_ = max_price; 173 | } else { 174 | this.target_price_ = min_price; 175 | } 176 | } else { 177 | if (price_better_than_the_current_order_price <= max_price && price_better_than_the_current_order_price >= min_price ){ 178 | this.target_price_ = price_better_than_the_current_order_price; 179 | } else if (price_better_than_the_current_order_price <= min_price ) { 180 | this.target_price_ = min_price; 181 | } else { 182 | this.target_price_ = max_price; 183 | } 184 | } 185 | 186 | if (params["side"] == 1 && this.target_price_ >= counter_order_at_top_of_the_book[0] || 187 | params["side"] == 2 && this.target_price_ <= counter_order_at_top_of_the_book[0]) { 188 | return; // we don't want to cause an execution. 189 | } 190 | 191 | 192 | var should_send_new_order = false; 193 | if (goog.isDefAndNotNull(this.current_order_)) { 194 | if ((this.current_order_["Side"] != params["side"] )) { 195 | this.application_.cancelOrder(this.current_order_['ClOrdID']); 196 | should_send_new_order = true; 197 | } 198 | if (this.current_order_["Price"] !== this.target_price_ ) { 199 | this.application_.cancelOrder(this.current_order_['ClOrdID']); 200 | should_send_new_order = true; 201 | } 202 | } else { 203 | should_send_new_order = true; 204 | } 205 | 206 | if (should_send_new_order) { 207 | this.current_order_ = { 208 | 'Side' : params["side"], 209 | 'ClOrdID' : this.my_orders_prefix_ + parseInt( 1e7 * Math.random() , 10 ), 210 | 'Qty' : this.target_qty_, 211 | 'Price' : this.target_price_ 212 | }; 213 | 214 | if (this.current_order_['Side'] == 1 ) { 215 | this.application_.sendBuyLimitedOrder(this.current_order_['Qty'], 216 | this.current_order_['Price'], 217 | this.current_order_['ClOrdID']); 218 | 219 | } else { 220 | this.application_.sendSellLimitedOrder(this.current_order_['Qty'], 221 | this.current_order_['Price'], 222 | this.current_order_['ClOrdID']); 223 | } 224 | } 225 | }; 226 | 227 | 228 | 229 | //-----END ALGO----- 230 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | var sys = require('sys'); 2 | var WebSocketClient = require('websocket').client; 3 | 4 | var wsClient = new WebSocketClient(); 5 | wsClient.connect('wss://api.testnet.blinktrade.com/trade/'); 6 | 7 | wsClient.addListener('connect', function(ws) { 8 | ws.addListener('message', function(buf) { 9 | sys.debug('Got data: ' + sys.inspect(buf)); 10 | }); 11 | ws.onmessage = function(m) { 12 | sys.debug('Got message: ' + m); 13 | } 14 | ws.send('{"MsgType":"1", "TestReqID":0}'); 15 | }); 16 | 17 | 18 | -------------------------------------------------------------------------------- /node_modules/websocket/.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | // JSHint Default Configuration File (as on JSHint website) 3 | // See http://jshint.com/docs/ for more details 4 | 5 | "maxerr" : 50, // {int} Maximum error before stopping 6 | 7 | // Enforcing 8 | "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.) 9 | "camelcase" : false, // true: Identifiers must be in camelCase 10 | "curly" : true, // true: Require {} for every new block or scope 11 | "eqeqeq" : true, // true: Require triple equals (===) for comparison 12 | "freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc. 13 | "forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty() 14 | "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` 15 | "latedef" : "nofunc", // true: Require variables/functions to be defined before being used 16 | "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` 17 | "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` 18 | "noempty" : true, // true: Prohibit use of empty blocks 19 | "nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters. 20 | "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment) 21 | "plusplus" : false, // true: Prohibit use of `++` & `--` 22 | "quotmark" : "single", // Quotation mark consistency: 23 | // false : do nothing (default) 24 | // true : ensure whatever is used is consistent 25 | // "single" : require single quotes 26 | // "double" : require double quotes 27 | "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) 28 | "unused" : "vars", // vars: Require all defined variables be used, ignore function params 29 | "strict" : false, // true: Requires all functions run in ES5 Strict Mode 30 | "maxparams" : false, // {int} Max number of formal params allowed per function 31 | "maxdepth" : false, // {int} Max depth of nested blocks (within functions) 32 | "maxstatements" : false, // {int} Max number statements per function 33 | "maxcomplexity" : false, // {int} Max cyclomatic complexity per function 34 | "maxlen" : false, // {int} Max number of characters per line 35 | 36 | // Relaxing 37 | "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) 38 | "boss" : false, // true: Tolerate assignments where comparisons would be expected 39 | "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. 40 | "eqnull" : false, // true: Tolerate use of `== null` 41 | "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) 42 | "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`) 43 | "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) 44 | // (ex: `for each`, multiple try/catch, function expression…) 45 | "evil" : false, // true: Tolerate use of `eval` and `new Function()` 46 | "expr" : false, // true: Tolerate `ExpressionStatement` as Programs 47 | "funcscope" : false, // true: Tolerate defining variables inside control statements 48 | "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') 49 | "iterator" : false, // true: Tolerate using the `__iterator__` property 50 | "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block 51 | "laxbreak" : false, // true: Tolerate possibly unsafe line breakings 52 | "laxcomma" : false, // true: Tolerate comma-first style coding 53 | "loopfunc" : false, // true: Tolerate functions being defined in loops 54 | "multistr" : false, // true: Tolerate multi-line strings 55 | "noyield" : false, // true: Tolerate generator functions with no yield statement in them. 56 | "notypeof" : false, // true: Tolerate invalid typeof operator values 57 | "proto" : false, // true: Tolerate using the `__proto__` property 58 | "scripturl" : false, // true: Tolerate script-targeted URLs 59 | "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` 60 | "sub" : true, // true: Tolerate using `[]` notation when it can still be expressed in dot notation 61 | "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` 62 | "validthis" : false, // true: Tolerate using this in a non-constructor function 63 | 64 | // Environments 65 | "browser" : true, // Web Browser (window, document, etc) 66 | "browserify" : true, // Browserify (node.js code in the browser) 67 | "couch" : false, // CouchDB 68 | "devel" : true, // Development/debugging (alert, confirm, etc) 69 | "dojo" : false, // Dojo Toolkit 70 | "jasmine" : false, // Jasmine 71 | "jquery" : false, // jQuery 72 | "mocha" : false, // Mocha 73 | "mootools" : false, // MooTools 74 | "node" : true, // Node.js 75 | "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) 76 | "prototypejs" : false, // Prototype and Scriptaculous 77 | "qunit" : false, // QUnit 78 | "rhino" : false, // Rhino 79 | "shelljs" : false, // ShellJS 80 | "worker" : false, // Web Workers 81 | "wsh" : false, // Windows Scripting Host 82 | "yui" : false, // Yahoo User Interface 83 | 84 | // Custom Globals 85 | "globals" : { // additional predefined global variables 86 | "WebSocket": true 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /node_modules/websocket/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /node_modules/websocket/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | node-gyp configure build 3 | 4 | clean: 5 | node-gyp clean 6 | 7 | autobahn: 8 | @NODE_PATH=lib node test/autobahn-test-client.js --host=127.0.0.1 --port=9000 9 | 10 | autobahn-server: 11 | @NODE_PATH=lib node test/echo-server.js 12 | -------------------------------------------------------------------------------- /node_modules/websocket/binding.gyp: -------------------------------------------------------------------------------- 1 | { 2 | 'targets': [ 3 | { 4 | 'target_name': 'validation', 5 | 'include_dirs': [">sys.stderr, line 171 | return libtoolout.returncode 172 | 173 | def ExecPackageFramework(self, framework, version): 174 | """Takes a path to Something.framework and the Current version of that and 175 | sets up all the symlinks.""" 176 | # Find the name of the binary based on the part before the ".framework". 177 | binary = os.path.basename(framework).split('.')[0] 178 | 179 | CURRENT = 'Current' 180 | RESOURCES = 'Resources' 181 | VERSIONS = 'Versions' 182 | 183 | if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): 184 | # Binary-less frameworks don't seem to contain symlinks (see e.g. 185 | # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). 186 | return 187 | 188 | # Move into the framework directory to set the symlinks correctly. 189 | pwd = os.getcwd() 190 | os.chdir(framework) 191 | 192 | # Set up the Current version. 193 | self._Relink(version, os.path.join(VERSIONS, CURRENT)) 194 | 195 | # Set up the root symlinks. 196 | self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) 197 | self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) 198 | 199 | # Back to where we were before! 200 | os.chdir(pwd) 201 | 202 | def _Relink(self, dest, link): 203 | """Creates a symlink to |dest| named |link|. If |link| already exists, 204 | it is overwritten.""" 205 | if os.path.lexists(link): 206 | os.remove(link) 207 | os.symlink(dest, link) 208 | 209 | 210 | if __name__ == '__main__': 211 | sys.exit(main(sys.argv[1:])) 212 | -------------------------------------------------------------------------------- /node_modules/websocket/build/validation.target.mk: -------------------------------------------------------------------------------- 1 | # This file is generated by gyp; do not edit. 2 | 3 | TOOLSET := target 4 | TARGET := validation 5 | DEFS_Debug := \ 6 | '-D_DARWIN_USE_64_BIT_INODE=1' \ 7 | '-D_LARGEFILE_SOURCE' \ 8 | '-D_FILE_OFFSET_BITS=64' \ 9 | '-DBUILDING_NODE_EXTENSION' \ 10 | '-DDEBUG' \ 11 | '-D_DEBUG' 12 | 13 | # Flags passed to all source files. 14 | CFLAGS_Debug := \ 15 | -O0 \ 16 | -gdwarf-2 \ 17 | -mmacosx-version-min=10.5 \ 18 | -arch x86_64 \ 19 | -Wall \ 20 | -Wendif-labels \ 21 | -W \ 22 | -Wno-unused-parameter 23 | 24 | # Flags passed to only C files. 25 | CFLAGS_C_Debug := \ 26 | -fno-strict-aliasing 27 | 28 | # Flags passed to only C++ files. 29 | CFLAGS_CC_Debug := \ 30 | -fno-rtti \ 31 | -fno-exceptions \ 32 | -fno-threadsafe-statics \ 33 | -fno-strict-aliasing 34 | 35 | # Flags passed to only ObjC files. 36 | CFLAGS_OBJC_Debug := 37 | 38 | # Flags passed to only ObjC++ files. 39 | CFLAGS_OBJCC_Debug := 40 | 41 | INCS_Debug := \ 42 | -I/Users/pinhopro/.node-gyp/0.10.13/src \ 43 | -I/Users/pinhopro/.node-gyp/0.10.13/deps/uv/include \ 44 | -I/Users/pinhopro/.node-gyp/0.10.13/deps/v8/include \ 45 | -I$(srcdir)/node_modules/nan 46 | 47 | DEFS_Release := \ 48 | '-D_DARWIN_USE_64_BIT_INODE=1' \ 49 | '-D_LARGEFILE_SOURCE' \ 50 | '-D_FILE_OFFSET_BITS=64' \ 51 | '-DBUILDING_NODE_EXTENSION' 52 | 53 | # Flags passed to all source files. 54 | CFLAGS_Release := \ 55 | -Os \ 56 | -gdwarf-2 \ 57 | -mmacosx-version-min=10.5 \ 58 | -arch x86_64 \ 59 | -Wall \ 60 | -Wendif-labels \ 61 | -W \ 62 | -Wno-unused-parameter 63 | 64 | # Flags passed to only C files. 65 | CFLAGS_C_Release := \ 66 | -fno-strict-aliasing 67 | 68 | # Flags passed to only C++ files. 69 | CFLAGS_CC_Release := \ 70 | -fno-rtti \ 71 | -fno-exceptions \ 72 | -fno-threadsafe-statics \ 73 | -fno-strict-aliasing 74 | 75 | # Flags passed to only ObjC files. 76 | CFLAGS_OBJC_Release := 77 | 78 | # Flags passed to only ObjC++ files. 79 | CFLAGS_OBJCC_Release := 80 | 81 | INCS_Release := \ 82 | -I/Users/pinhopro/.node-gyp/0.10.13/src \ 83 | -I/Users/pinhopro/.node-gyp/0.10.13/deps/uv/include \ 84 | -I/Users/pinhopro/.node-gyp/0.10.13/deps/v8/include \ 85 | -I$(srcdir)/node_modules/nan 86 | 87 | OBJS := \ 88 | $(obj).target/$(TARGET)/src/validation.o 89 | 90 | # Add to the list of files we specially track dependencies for. 91 | all_deps += $(OBJS) 92 | 93 | # CFLAGS et al overrides must be target-local. 94 | # See "Target-specific Variable Values" in the GNU Make manual. 95 | $(OBJS): TOOLSET := $(TOOLSET) 96 | $(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) 97 | $(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) 98 | $(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) 99 | $(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) 100 | 101 | # Suffix rules, putting all outputs into $(obj). 102 | 103 | $(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD 104 | @$(call do_cmd,cxx,1) 105 | 106 | # Try building from generated source, too. 107 | 108 | $(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD 109 | @$(call do_cmd,cxx,1) 110 | 111 | $(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD 112 | @$(call do_cmd,cxx,1) 113 | 114 | # End of this set of suffix rules 115 | ### Rules for final target. 116 | LDFLAGS_Debug := \ 117 | -Wl,-search_paths_first \ 118 | -mmacosx-version-min=10.5 \ 119 | -arch x86_64 \ 120 | -L$(builddir) \ 121 | -install_name @rpath/validation.node 122 | 123 | LIBTOOLFLAGS_Debug := \ 124 | -Wl,-search_paths_first 125 | 126 | LDFLAGS_Release := \ 127 | -Wl,-search_paths_first \ 128 | -mmacosx-version-min=10.5 \ 129 | -arch x86_64 \ 130 | -L$(builddir) \ 131 | -install_name @rpath/validation.node 132 | 133 | LIBTOOLFLAGS_Release := \ 134 | -Wl,-search_paths_first 135 | 136 | LIBS := \ 137 | -undefined dynamic_lookup 138 | 139 | $(builddir)/validation.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) 140 | $(builddir)/validation.node: LIBS := $(LIBS) 141 | $(builddir)/validation.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) 142 | $(builddir)/validation.node: TOOLSET := $(TOOLSET) 143 | $(builddir)/validation.node: $(OBJS) FORCE_DO_CMD 144 | $(call do_cmd,solink_module) 145 | 146 | all_deps += $(builddir)/validation.node 147 | # Add target alias 148 | .PHONY: validation 149 | validation: $(builddir)/validation.node 150 | 151 | # Short alias for building this executable. 152 | .PHONY: validation.node 153 | validation.node: $(builddir)/validation.node 154 | 155 | # Add executable to "all" target. 156 | .PHONY: all 157 | all: $(builddir)/validation.node 158 | 159 | -------------------------------------------------------------------------------- /node_modules/websocket/builderror.log: -------------------------------------------------------------------------------- 1 | gyp http GET http://nodejs.org/dist/v0.10.13/node-v0.10.13.tar.gz 2 | gyp http 200 http://nodejs.org/dist/v0.10.13/node-v0.10.13.tar.gz 3 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/W3CWebSocket.md: -------------------------------------------------------------------------------- 1 | W3CWebSocket 2 | ============ 3 | 4 | * [Constructor](#constructor) 5 | * [Limitations](#limitations) 6 | 7 | `var W3CWebSocket = require('websocket').w3cwebsocket` 8 | 9 | Implementation of the [W3C WebSocket API](http://www.w3.org/TR/websockets/) for browsers. 10 | 11 | The exposed class lets the developer use the browser *W3C WebSocket API* in Node: 12 | 13 | ```javascript 14 | var WS = require('websocket').w3cwebsocket; 15 | 16 | WS === window.WebSocket 17 | // => true when in the browser 18 | 19 | var ws = new WS('ws://example.com/resource', 'foo', 'http://example.com'); 20 | // - In Node it creates an instance of websocket.W3CWebSocket. 21 | // - In the browser it creates an instance of window.WebSocket (third parameter 22 | // is ignored by the native WebSocket constructor). 23 | 24 | ws.onopen = function() { console.log('ws open'); }; 25 | // etc. 26 | ``` 27 | 28 | 29 | Constructor 30 | ----------- 31 | 32 | ```javascript 33 | new W3CWebSocket(requestUrl, requestedProtocols, [[[[origin], headers], requestOptions], clientConfig]) 34 | ``` 35 | 36 | **clientConfig** is the parameter of the [WebSocketClient](./WebSocketClient.md) constructor. 37 | 38 | **requestUrl**, **requestedProtocols**, **origin**, **headers** and **requestOptions** are parameters to be used in the `connect()` method of [WebSocketClient](./WebSocketClient.md). 39 | 40 | This constructor API makes it possible to use the W3C API and "browserify" the Node application into a valid browser library. 41 | 42 | When running in a browser (for example by using [browserify](http://browserify.org/)) the browser's native `WebSocket` implementation is used, and thus just the first and second arguments (`requestUrl` and `requestedProtocols`) are used (those allowed by the *W3C WebSocket API*). 43 | 44 | 45 | Limitations 46 | ----------- 47 | 48 | * `bufferedAmount` attribute is always 0. 49 | * `binaryType` is "arraybuffer" by default given that "blob" is not supported (Node does not implement the `Blob` class). 50 | * `send()` method allows arguments of type `DOMString`, `ArrayBuffer`, `ArrayBufferView` (`Int8Array`, etc) or Node `Buffer`, but does not allow `Blob`. 51 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/WebSocketClient.md: -------------------------------------------------------------------------------- 1 | WebSocketClient 2 | =============== 3 | 4 | * [Constructor](#constructor) 5 | * [Config Options](#client-config-options) 6 | * [Methods](#methods) 7 | * [Events](#events) 8 | * **Examples** 9 | * [Connect using a Proxy Server](#connect-using-a-proxy-server) 10 | 11 | `var WebSocketClient = require('websocket').client` 12 | 13 | This object allows you to make client connections to a WebSocket server. 14 | 15 | Constructor 16 | ----------- 17 | ```javascript 18 | new WebSocketClient([clientConfig]); 19 | ``` 20 | 21 | Client Config Options 22 | --------------------- 23 | **webSocketVersion** - uint - *Default: 13* 24 | Which version of the WebSocket protocol to use when making the connection. Currently supported values are 8 and 13. 25 | This option will be removed once the protocol is finalized by the IETF It is only available to ease the transition through the intermediate draft protocol versions. The only thing this affects the name of the Origin header. 26 | 27 | **maxReceivedFrameSize** - uint - *Default: 1MiB* 28 | The maximum allowed received frame size in bytes. Single frame messages will also be limited to this maximum. 29 | 30 | **maxReceivedMessageSize** - uint - *Default: 8MiB* 31 | The maximum allowed aggregate message size (for fragmented messages) in bytes. 32 | 33 | **fragmentOutgoingMessages** - Boolean - *Default: true* 34 | Whether or not to fragment outgoing messages. If true, messages will be automatically fragmented into chunks of up to `fragmentationThreshold` bytes. 35 | 36 | **fragmentationThreshold** - uint - *Default: 16KiB* 37 | The maximum size of a frame in bytes before it is automatically fragmented. 38 | 39 | **assembleFragments** - boolean - *Default: true* 40 | If true, fragmented messages will be automatically assembled and the full message will be emitted via a `message` event. If false, each frame will be emitted on the WebSocketConnection object via a `frame` event and the application will be responsible for aggregating multiple fragmented frames. Single-frame messages will emit a `message` event in addition to the `frame` event. Most users will want to leave this set to `true`. 41 | 42 | **closeTimeout** - uint - *Default: 5000* 43 | The number of milliseconds to wait after sending a close frame for an acknowledgement to come back before giving up and just closing the socket. 44 | 45 | **tlsOptions** - object - *Default: {}* 46 | Options to pass to `https.request` if connecting via TLS. See [Node's HTTPS documentation](http://nodejs.org/api/https.html#https_https_request_options_callback) 47 | 48 | 49 | Methods 50 | ------- 51 | ###connect(requestUrl, requestedProtocols, [[[origin], headers], requestOptions]) 52 | 53 | Will establish a connection to the given `requestUrl`. `requestedProtocols` indicates a list of multiple subprotocols supported by the client. The remote server will select the best subprotocol that it supports and send that back when establishing the connection. `origin` is an optional field that can be used in user-agent scenarios to identify the page containing any scripting content that caused the connection to be requested. (This seems unlikely in node.. probably should leave it null most of the time.) `requestUrl` should be a standard websocket url, such as: 54 | `ws://www.mygreatapp.com:1234/websocketapp/` 55 | 56 | `headers` should be either `null` or an object specifying additional arbitrary HTTP request headers to send along with the request. This may be used to pass things like access tokens, etc. so that the server can verify authentication/authorization before deciding to accept and open the full WebSocket connection. 57 | 58 | `requestOptions` should be either `null` or an object specifying additional configuration options to be passed to `http.request` or `https.request`. This can be used to pass a custom `agent` to enable `WebSocketClient` usage from behind an HTTP or HTTPS proxy server using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar. 59 | 60 | `origin` must be specified if you want to pass `headers`, and both `origin` and `headers` must be specified if you want to pass `requestOptions`. The `origin` and `headers` parameters may be passed as `null`. 61 | 62 | 63 | Events 64 | ------ 65 | ###connect 66 | `function(webSocketConnection)` 67 | 68 | Emitted upon successfully negotiating the WebSocket handshake with the remote server. `webSocketConnection` is an instance of `WebSocketConnection` that can be used to send and receive messages with the remote server. 69 | 70 | ###connectFailed 71 | `function(errorDescription)` 72 | 73 | Emitted when there is an error connecting to the remote host or the handshake response sent by the server is invalid. 74 | 75 | ###httpResponse 76 | `function(response, webSocketClient)` 77 | 78 | Emitted when the server replies with anything other then "101 Switching Protocols". Provides an opportunity to handle redirects for example. The `response` parameter is an instance of the [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) class. This is not suitable for handling receiving of large response bodies, as the underlying socket will be immediately closed by WebSocket-Node as soon as all handlers for this event are executed. 79 | 80 | Normally, if the remote server sends an HTTP response with a response code other than 101, the `WebSocketClient` will automatically emit the `connectFailed` event with a description of what was received from the remote server. However, if there are one or more listeners attached to the `httpResponse` event, then the `connectFailed` event will not be emitted for non-101 responses received. `connectFailed` will still be emitted for non-HTTP errors, such as when the remote server is unreachable or not accepting TCP connections. 81 | 82 | 83 | Examples 84 | ======== 85 | 86 | Connect using a Proxy Server 87 | ---------------------------- 88 | 89 | Using [koichik/node-tunnel](https://github.com/koichik/node-tunnel): 90 | 91 | ```javascript 92 | var WebSocketClient = require('websocket').client; 93 | var client = new WebSocketClient(); 94 | var tunnel = require('tunnel'); 95 | 96 | var tunnelingAgent = tunnel.httpOverHttp({ 97 | proxy: { 98 | host: 'proxy.host.com', 99 | port: 8080 100 | } 101 | }); 102 | 103 | var requestOptions = { 104 | agent: tunnelingAgent 105 | }; 106 | 107 | client.connect('ws://echo.websocket.org/', null, null, null, requestOptions); 108 | ``` 109 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/WebSocketConnection.md: -------------------------------------------------------------------------------- 1 | WebSocketConnection 2 | =================== 3 | 4 | * [Constructor](#constructor) 5 | * [Properties](#properties) 6 | * [Methods](#methods) 7 | * [Events](#events) 8 | 9 | This object provides the interface through which you can communicate with connected peers. It is used in both WebSocketServer and WebSocketClient situations. 10 | 11 | Constructor 12 | ----------- 13 | This object is created internally by `WebSocketRequest`. 14 | 15 | Properties 16 | ---------- 17 | 18 | ###closeDescription 19 | 20 | After the connection is closed, contains a textual description of the reason for the connection closure, or `null` if the connection is still open. 21 | 22 | ###closeReasonCode 23 | 24 | After the connection is closed, contains the numeric close reason status code, or `-1` if the connection is still open. 25 | 26 | ###socket 27 | 28 | The underlying net.Socket instance for the connection. 29 | 30 | ###protocol 31 | 32 | The subprotocol that was chosen to be spoken on this connection. This field will have been converted to lower case. 33 | 34 | ###extensions 35 | 36 | An array of extensions that were negotiated for this connection. Currently unused, will always be an empty array. 37 | 38 | ###remoteAddress 39 | 40 | The IP address of the remote peer as a string. In the case of a server, the `X-Forwarded-For` header will be respected and preferred for the purposes of populating this field. If you need to get to the actual remote IP address, `webSocketConnection.socket.remoteAddress` will provide it. 41 | 42 | ###webSocketVersion 43 | 44 | A number indicating the version of the WebSocket protocol being spoken on this connection. 45 | 46 | ###connected 47 | 48 | A boolean value indicating whether or not the connection is still connected. *Read-only* 49 | 50 | Methods 51 | ------- 52 | ###close([reasonCode], [description]) 53 | 54 | Will gracefully close the connection. A close frame will be sent to the remote peer with the provided `reasonCode` and `description` indicating that we wish to close the connection, and we will then wait for up to `config.closeTimeout` milliseconds for an acknowledgment from the remote peer before terminating the underlying socket connection. The `closeTimeout` is passed as part of the `serverOptions` or `clientOptions` hashes to either the `WebSocketServer` or `WebSocketClient` constructors. Most of the time, you should call `close()` without arguments to initiate a normal connection closure. If you specify a `reasonCode` that is defined as one of the standard codes in the WebSocket protocol specification and do not provide a `description`, the default description for the given code will be used. If you would prefer not to send a description at all, pass an empty string `''`as the description parameter. 55 | 56 | ###drop([reasonCode], [description]) 57 | 58 | Will send a close frame to the remote peer with the provided `reasonCode` and `description` and will immediately close the socket without waiting for a response. This should generally be used only in error conditions. The default `reasonCode` is 1002 (Protocol Error). Close reasons defined by the WebSocket protocol draft include: 59 | 60 | ```javascript 61 | WebSocketConnection.CLOSE_REASON_NORMAL = 1000; 62 | WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001; 63 | WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002; 64 | WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003; 65 | WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning. 66 | WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire 67 | WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire 68 | WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007; 69 | WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008; 70 | WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009; 71 | WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010; 72 | ``` 73 | ###sendUTF(string) 74 | 75 | Immediately sends the specified string as a UTF-8 WebSocket message to the remote peer. If `config.fragmentOutgoingMessages` is `true` the message may be sent as multiple fragments if it exceeds `config.fragmentationThreshold` bytes. Any object that implements the `toString()` method may be passed to `sendUTF()` 76 | 77 | ###sendBytes(buffer) 78 | 79 | Immediately sends the specified Node `Buffer` object as a Binary WebSocket message to the remote peer. If `config.fragmentOutgoingMessages` is `true` the message may be sent as multiple fragments if it exceeds `config.fragmentationThreshold` bytes. 80 | 81 | ###send(data) 82 | 83 | A convenience function that will auto-detect the data type and send the appropriate WebSocket message accordingly. Immediately sends the specified data as either a UTF-8 or Binary message. If `data` is a Node Buffer, a binary message will be sent. Otherwise, the object provided must implement the `toString()` method, and the result of calling `toString()` on the `data` object will be sent as a UTF-8 message. 84 | 85 | ###ping(data) 86 | 87 | Sends a ping frame to the remote peer. `data` can be a Node `Buffer` or any object that implements `toString()`, such as a `string` or `number`. Ping frames must not exceed 125 bytes in length. 88 | 89 | ###pong(buffer) 90 | 91 | Sends a pong frame to the remote peer. Pong frames may be sent unsolicited and such pong frames will trigger no action on the receiving peer. Pong frames sent in response to a ping frame must mirror the payload data of the ping frame exactly. The `WebSocketConnection` object handles this internally for you, so there should be no need to use this method to respond to pings. Pong frames must not exceed 125 bytes in length. 92 | 93 | ###sendFrame(webSocketFrame) 94 | 95 | Serializes a `WebSocketFrame` object into binary data and immediately sends it to the remote peer. This is an advanced function, requiring you to manually compose your own `WebSocketFrame`. You should probably use `sendUTF` or `sendBytes` instead. 96 | 97 | Events 98 | ------ 99 | ###message 100 | `function(message)` 101 | 102 | Emitted whenever a complete single-frame message is received, or if `config.assembleFragments` is `true` (the default), it will also be emitted with a complete message assembled from multiple fragmented frames. This is the primary event to listen for to receive messages from the remote peer. The `message` object looks like the following: 103 | 104 | ```javascript 105 | // For Text Frames: 106 | { 107 | type: "utf8", 108 | utf8Data: "A string containing the received message." 109 | } 110 | 111 | // For Binary Frames: 112 | { 113 | type: "binary", 114 | binaryData: binaryDataBuffer // a Buffer object containing the binary message payload 115 | } 116 | ``` 117 | 118 | ###frame 119 | `function(webSocketFrame)` 120 | 121 | This event is emitted only if `config.assembleFragments` is `false` (default is `true`). This allows you to handle individual fragments as they are received without waiting on `WebSocketConnection` to buffer them into a single `message` event for you. This may be desirable if you are working with streaming data, as it is possible to send fragments continually without ever stopping. `webSocketFrame` is an instance of `WebSocketFrame` which has properties that represent all the individual fields in WebSocket's binary framing protocol. 122 | 123 | ###close 124 | `function(reasonCode, description)` 125 | 126 | This event is emitted when the connection has been fully closed and the socket is no longer connected. `reasonCode` is the numeric reason code for the connection closure. `description` is a textual explanation for the connection closure, if available. 127 | 128 | ###error 129 | `function(error)` 130 | 131 | This event is emitted when there has been a socket error. If this occurs, a `close` event will also be emitted. 132 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/WebSocketFrame.md: -------------------------------------------------------------------------------- 1 | WebSocketFrame 2 | ============== 3 | 4 | * [Constructor](#constructor) 5 | * [Properties](#properties) 6 | 7 | `var WebSocketFrame = require('websocket').frame` 8 | 9 | This object represents the low level individual frame and is used to drive how the bytes are serialized onto the wire. 10 | 11 | Constructor 12 | ----------- 13 | ```javascript 14 | new WebSocketFrame(); 15 | ``` 16 | 17 | Properties 18 | ---------- 19 | 20 | ###fin 21 | *Boolean* 22 | 23 | Indicates that this is either the only frame in a message, or the last frame in a fragmentation sequence. 24 | 25 | ###rsv1 26 | *Boolean* 27 | 28 | Represents the RSV1 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer. 29 | 30 | ###rsv2 31 | *Boolean* 32 | 33 | Represents the RSV2 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer. 34 | 35 | ###rsv3 36 | *Boolean* 37 | 38 | Represents the RSV3 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer. 39 | 40 | ###mask 41 | *uint* 42 | 43 | Whether or not this frame is (or should be) masked. For outgoing frames, when connected as a client, this flag is automatically forced to `true` by WebSocketConnection. Outgoing frames sent from the server-side of a connection are not masked. 44 | 45 | ###opcode 46 | *uint* 47 | 48 | Identifies which kind of frame this is. List of Opcodes: 49 | 50 | Hex - Dec - Description 51 | 0x00 - 0 - Continuation 52 | 0x01 - 1 - Text Frame 53 | 0x02 - 2 - Binary Frame 54 | 0x08 - 8 - Close Frame 55 | 0x09 - 9 - Ping Frame 56 | 0x0A - 10 - Pong Frame 57 | 58 | ###length 59 | *Read-only, uint* 60 | 61 | Identifies the length of the payload data on a received frame. When sending a frame, the length will be automatically calculated from the `binaryPayload` object. 62 | 63 | ###binaryPayload 64 | *Buffer object* 65 | 66 | The binary payload data. **NOTE**: Even text frames are sent with a Buffer providing the binary payload data. When sending a UTF-8 Text Frame, you must serialize your string into a Buffer object before constructing your frame, and when receiving a UTF-8 Text Frame, you must deserialize the string from the provided Buffer object. Do not read UTF-8 data from fragmented Text Frames, as it may have fragmented the data in the middle of a UTF-8 encoded character. You should buffer all fragments of a text message before attempting to decode the UTF-8 data. 67 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/WebSocketRequest.md: -------------------------------------------------------------------------------- 1 | WebSocketRequest 2 | ================ 3 | 4 | * [Constructor](#constructor) 5 | * [Properties](#properties) 6 | * [Methods](#methods) 7 | * [Events](#events) 8 | 9 | This object represents a client requesting to connect to the server, and allows you to accept or reject the connection based on whatever criteria you decide. 10 | 11 | Constructor 12 | ----------- 13 | This object is created internally by `WebSocketServer`. 14 | 15 | However if you need to integrate WebSocket support without mounting an instance of `WebSocketServer` to your http server directly, you can handle the `upgrade` event yourself and pass the appropriate parameters to the `WebSocketRequest` constructor. **NOTE:** You *must* pass a complete set of config options to the constructor. See the section *'Server Config Options'* above. The only option that isn't required in this context is `httpServer`. 16 | 17 | ```javascript 18 | new WebSocketRequest(socket, httpRequest, config); 19 | ``` 20 | 21 | The constructor won't immediately parse and validate the handshake from the client, so you need to call `readHandshake()`, which will `throw` an error if the handshake from the client is invalid or if an error is encountered, so it must always be wrapped in a try/catch block. 22 | 23 | Properties 24 | ---------- 25 | ###httpRequest 26 | 27 | A reference to the original Node HTTP request object. This may be useful in combination with some other Node-based web server, such as Express, for accessing cookies or session data. 28 | 29 | 30 | ###host 31 | 32 | A string containing the contents of the `Host` header passed by the client. This will include the port number if a non-standard port is used. 33 | 34 | Examples: 35 | ``` 36 | www.example.com 37 | www.example.com:8080 38 | 127.0.0.1:3000 39 | ``` 40 | 41 | ###resource 42 | 43 | A string containing the path that was requested by the client. 44 | 45 | ###resourceURL 46 | 47 | A Node URL object containing the parsed `resource`, including the query string parameters. 48 | 49 | ###remoteAddress 50 | 51 | The remote client's IP Address as a string. If an `X-Forwarded-For` header is present, the value will be taken from that header to facilitate WebSocket servers that live behind a reverse-proxy. 52 | 53 | ###websocketVersion 54 | 55 | **Deprecated, renamed to webSocketVersion** 56 | 57 | ###webSocketVersion 58 | 59 | A number indicating the version of the WebSocket protocol requested by the client. 60 | 61 | ###origin 62 | 63 | If the client is a web browser, `origin` will be a string containing the URL of the page containing the script that opened the connection. If the client is **not** a web browser, `origin` may be `null` or "*". 64 | 65 | ###requestedExtensions 66 | 67 | An array containing a list of extensions requested by the client. This is not currently used for anything. **Example:** 68 | 69 | ```javascript 70 | [ 71 | { 72 | name: "simple-extension"; 73 | }, 74 | { 75 | name: "my-great-compression-extension", 76 | params: [ 77 | { 78 | name: "compressionLevel", 79 | value: "10"; 80 | } 81 | ] 82 | } 83 | ] 84 | ``` 85 | 86 | ###requestedProtocols 87 | 88 | An array containing a list of strings that indicate the subprotocols the client would like to speak. The server should select the best one that it can support from the list and pass it to the accept() function when accepting the connection. Note that all the strings in the `requestedProtocols` array will have been converted to lower case, so that acceptance of a subprotocol can be case-insensitive. 89 | 90 | Methods 91 | ------- 92 | 93 | ###accept(acceptedProtocol, allowedOrigin) 94 | *Returns: WebSocketConnection instance* 95 | 96 | After inspecting the WebSocketRequest's properties, call this function on the request object to accept the connection. If you don't have a particular subprotocol you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. Note that the `acceptedProtocol` parameter is *case-insensitive*, and you must either pass a value that was originally requested by the client or `null`. For browser clients (in which the `origin` property would be non-null) you must pass that user's origin as the `allowedOrigin` parameter to confirm that you wish to accept connections from the given origin. The return value contains the established `WebSocketConnection` instance that can be used to communicate with the connected client. 97 | 98 | ###reject([httpStatus], [reason]) 99 | 100 | If you decide to reject the connection, you must call `reject`. You may optionally pass in an HTTP Status code (such as 404) and a textual description that will be sent to the client in the form of an "X-WebSocket-Reject-Reason" header. The connection will then be closed. 101 | 102 | Events 103 | ------ 104 | 105 | ###requestAccepted 106 | `function(webSocketConnection)` 107 | 108 | Emitted by the WebSocketRequest object when the `accept` method has been called and the connection has been established. `webSocketConnection` is the established `WebSocketConnection` instance that can be used to communicate with the connected client. 109 | 110 | ###requestRejected 111 | `function()` 112 | 113 | Emitted by the WebSocketRequest object when the `reject` method has been called and the connection has been terminated. 114 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/WebSocketServer.md: -------------------------------------------------------------------------------- 1 | WebSocketServer 2 | =============== 3 | 4 | * [Constructor](#constructor) 5 | * [Config Options](#server-config-options) 6 | * [Properties](#properties) 7 | * [Methods](#methods) 8 | * [Events](#events) 9 | 10 | `var WebSocketServer = require('websocket').server` 11 | 12 | Constructor 13 | ----------- 14 | 15 | ```javascript 16 | new WebSocketServer([serverConfig]); 17 | ``` 18 | 19 | Methods 20 | ------- 21 | 22 | ###mount(serverConfig) 23 | 24 | `mount` will attach the WebSocketServer instance to a Node http.Server instance. `serverConfig` is required, and is an object with configuration values. For those values, see **Server Config Options** below. If you passed `serverConfig` to the constructor, this function will automatically be invoked. 25 | 26 | ###unmount() 27 | 28 | `unmount` will detach the WebSocketServer instance from the Node http.Server instance. All existing connections are left alone and will not be affected, but no new WebSocket connections will be accepted. 29 | 30 | ###closeAllConnections() 31 | 32 | Will gracefully close all open WebSocket connections. 33 | 34 | ###shutDown() 35 | 36 | Gracefully closes all open WebSocket connections and unmounts the server from the Node http.Server instance. 37 | 38 | Server Config Options 39 | --------------------- 40 | **httpServer** - (http.Server instance) **Required**. 41 | The Node http or https server instance(s) to attach to. You can pass a single instance directly, or pass an array of instances to attach to multiple http/https servers. Passing an array is particularly useful when you want to accept encrypted and unencrypted WebSocket connections on both ws:// and wss:// protocols using the same WebSocketServer instance. 42 | 43 | **maxReceivedFrameSize** - uint - *Default: 64KiB* 44 | The maximum allowed received frame size in bytes. Single frame messages will also be limited to this maximum. 45 | 46 | **maxReceivedMessageSize** - uint - *Default: 1MiB* 47 | The maximum allowed aggregate message size (for fragmented messages) in bytes. 48 | 49 | **fragmentOutgoingMessages** - Boolean - *Default: true* 50 | Whether or not to fragment outgoing messages. If true, messages will be automatically fragmented into chunks of up to `fragmentationThreshold` bytes. 51 | 52 | **fragmentationThreshold** - uint - *Default: 16KiB* 53 | The maximum size of a frame in bytes before it is automatically fragmented. 54 | 55 | **keepalive** - boolean - *Default: true* 56 | If true, the server will automatically send a ping to all clients every `keepaliveInterval` milliseconds. Each client has an independent keepalive timer, which is reset when any data is received from that client. 57 | 58 | **keepaliveInterval** - uint - *Default: 20000* 59 | The interval in milliseconds to send keepalive pings to connected clients. 60 | 61 | **dropConnectionOnKeepaliveTimeout** - boolean - *Default: true* 62 | If true, the server will consider any connection that has not received any data within the amount of time specified by `keepaliveGracePeriod` after a keepalive ping has been sent. Ignored if `keepalive` is false. 63 | 64 | **keepaliveGracePeriod** - uint - *Default: 10000* 65 | The amount of time to wait after sending a keepalive ping before closing the connection if the connected peer does not respond. Ignored if `keepalive` or `dropConnectionOnKeepaliveTimeout` are false. The grace period timer is reset when any data is received from the client. 66 | 67 | **assembleFragments** - boolean - *Default: true* 68 | If true, fragmented messages will be automatically assembled and the full message will be emitted via a `message` event. If false, each frame will be emitted on the WebSocketConnection object via a `frame` event and the application will be responsible for aggregating multiple fragmented frames. Single-frame messages will emit a `message` event in addition to the `frame` event. Most users will want to leave this set to `true`. 69 | 70 | **autoAcceptConnections** - boolean - *Default: false* 71 | If this is true, websocket connections will be accepted regardless of the path and protocol specified by the client. The protocol accepted will be the first that was requested by the client. Clients from any origin will be accepted. This should only be used in the simplest of cases. You should probably leave this set to `false`; and inspect the request object to make sure it's acceptable before accepting it. 72 | 73 | **closeTimeout** - uint - *Default: 5000* 74 | The number of milliseconds to wait after sending a close frame for an acknowledgement to come back before giving up and just closing the socket. 75 | 76 | **disableNagleAlgorithm** - boolean - *Default: true* 77 | The Nagle Algorithm makes more efficient use of network resources by introducing a small delay before sending small packets so that multiple messages can be batched together before going onto the wire. This however comes at the cost of latency, so the default is to disable it. If you don't need low latency and are streaming lots of small messages, you can change this to 'false'; 78 | 79 | **ignoreXForwardedFor** - Boolean - *Default: false* 80 | Whether or not the `X-Forwarded-For` header should be respected. 81 | It's important to set this to 'true' when accepting connections 82 | from untrusted clients, as a malicious client could spoof its 83 | IP address by simply setting this header. It's meant to be added 84 | by a trusted proxy or other intermediary within your own 85 | infrastructure. 86 | More info: [X-Forwarded-For on Wikipedia](http://en.wikipedia.org/wiki/X-Forwarded-For) 87 | 88 | Events 89 | ------ 90 | There are three events emitted by a WebSocketServer instance that allow you to handle incoming requests, establish connections, and detect when a connection has been closed. 91 | 92 | ###request 93 | `function(webSocketRequest)` 94 | 95 | If `autoAcceptConnections` is set to `false`, a `request` event will be emitted by the server whenever a new WebSocket request is made. You should inspect the requested protocols and the user's origin to verify the connection, and then accept or reject it by calling webSocketRequest.accept('chosen-protocol', 'accepted-origin') or webSocketRequest.reject() 96 | 97 | ###connect 98 | `function(webSocketConnection)` 99 | 100 | Emitted whenever a new WebSocket connection is accepted. 101 | 102 | ###close 103 | `function(webSocketConnection, closeReason, description)` 104 | 105 | Whenever a connection is closed for any reason, the WebSocketServer instance will emit a `close` event, passing a reference to the WebSocketConnection instance that was closed. `closeReason` is the numeric reason status code for the connection closure, and `description` is a textual description of the close reason, if available. 106 | -------------------------------------------------------------------------------- /node_modules/websocket/docs/index.md: -------------------------------------------------------------------------------- 1 | WebSocket-Node Documentation 2 | ============================ 3 | 4 | WebSocket-Node includes both client and server functionality, available through WebSocketClient and WebSocketServer respectively. Once a connection is established, the API for sending and receiving messages is identical whether you're acting as a client or server. 5 | 6 | Click on one of the classes below to view its API documentation. 7 | 8 | * [WebSocketClient](./WebSocketClient.md) 9 | * [WebSocketConnection](./WebSocketConnection.md) 10 | * [WebSocketFrame](./WebSocketFrame.md) 11 | * [WebSocketRequest](./WebSocketRequest.md) 12 | * [WebSocketServer](./WebSocketServer.md) 13 | * [W3CWebSocket](./W3CWebSocket.md) 14 | -------------------------------------------------------------------------------- /node_modules/websocket/gulpfile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Dependencies. 3 | */ 4 | var gulp = require('gulp'); 5 | var jshint = require('gulp-jshint'); 6 | 7 | gulp.task('lint', function() { 8 | return gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js']) 9 | .pipe(jshint('.jshintrc')) 10 | .pipe(jshint.reporter('jshint-stylish', {verbose: true})) 11 | .pipe(jshint.reporter('fail')); 12 | }); 13 | 14 | gulp.task('default', gulp.series('lint')); 15 | -------------------------------------------------------------------------------- /node_modules/websocket/index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('./lib/websocket'); -------------------------------------------------------------------------------- /node_modules/websocket/lib/BufferUtil.fallback.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copied from: 3 | * ws: a node.js websocket client 4 | * Copyright(c) 2011 Einar Otto Stangvik 5 | * MIT Licensed 6 | */ 7 | 8 | /* jshint -W086 */ 9 | 10 | module.exports.BufferUtil = { 11 | merge: function(mergedBuffer, buffers) { 12 | var offset = 0; 13 | for (var i = 0, l = buffers.length; i < l; ++i) { 14 | var buf = buffers[i]; 15 | buf.copy(mergedBuffer, offset); 16 | offset += buf.length; 17 | } 18 | }, 19 | mask: function(source, mask, output, offset, length) { 20 | var maskNum = mask.readUInt32LE(0, true); 21 | var i = 0; 22 | for (; i < length - 3; i += 4) { 23 | var num = maskNum ^ source.readUInt32LE(i, true); 24 | if (num < 0) { num = 4294967296 + num; } 25 | output.writeUInt32LE(num, offset + i, true); 26 | } 27 | switch (length % 4) { 28 | case 3: output[offset + i + 2] = source[i + 2] ^ mask[2]; 29 | case 2: output[offset + i + 1] = source[i + 1] ^ mask[1]; 30 | case 1: output[offset + i] = source[i] ^ mask[0]; 31 | case 0: 32 | } 33 | }, 34 | unmask: function(data, mask) { 35 | var maskNum = mask.readUInt32LE(0, true); 36 | var length = data.length; 37 | var i = 0; 38 | for (; i < length - 3; i += 4) { 39 | var num = maskNum ^ data.readUInt32LE(i, true); 40 | if (num < 0) { num = 4294967296 + num; } 41 | data.writeUInt32LE(num, i, true); 42 | } 43 | switch (length % 4) { 44 | case 3: data[i + 2] = data[i + 2] ^ mask[2]; 45 | case 2: data[i + 1] = data[i + 1] ^ mask[1]; 46 | case 1: data[i] = data[i] ^ mask[0]; 47 | case 0: 48 | } 49 | } 50 | }; 51 | 52 | /* jshint +W086 */ -------------------------------------------------------------------------------- /node_modules/websocket/lib/BufferUtil.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copied from: 3 | * ws: a node.js websocket client 4 | * Copyright(c) 2011 Einar Otto Stangvik 5 | * MIT Licensed 6 | */ 7 | 8 | try { 9 | module.exports = require('../build/Release/bufferutil'); 10 | } catch (e) { try { 11 | module.exports = require('../build/default/bufferutil'); 12 | } catch (e) { try { 13 | module.exports = require('./BufferUtil.fallback'); 14 | } catch (e) { 15 | console.error('bufferutil.node seems to not have been built. Run npm install.'); 16 | throw e; 17 | }}} 18 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/Deprecation.js: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * Copyright 2010-2011 Worlize Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***********************************************************************/ 16 | 17 | var Deprecation = { 18 | disableWarnings: false, 19 | 20 | deprecationWarningMap: { 21 | 22 | }, 23 | 24 | warn: function(deprecationName) { 25 | if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) { 26 | console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]); 27 | this.deprecationWarningMap[deprecationName] = false; 28 | } 29 | } 30 | }; 31 | 32 | module.exports = Deprecation; 33 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/Validation.fallback.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * UTF-8 Validation Fallback Code originally from: 3 | * ws: a node.js websocket client 4 | * Copyright(c) 2011 Einar Otto Stangvik 5 | * MIT Licensed 6 | */ 7 | 8 | module.exports.Validation = { 9 | isValidUTF8: function() { 10 | return true; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/Validation.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * UTF-8 Validation Code originally from: 3 | * ws: a node.js websocket client 4 | * Copyright(c) 2011 Einar Otto Stangvik 5 | * MIT Licensed 6 | */ 7 | 8 | try { 9 | module.exports = require('../build/Release/validation'); 10 | } catch (e) { try { 11 | module.exports = require('../build/default/validation'); 12 | } catch (e) { try { 13 | module.exports = require('./Validation.fallback'); 14 | } catch (e) { 15 | console.error('validation.node seems not to have been built. Run npm install.'); 16 | throw e; 17 | }}} 18 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/W3CWebSocket.js: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * Copyright 2010-2014 Worlize Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***********************************************************************/ 16 | 17 | var WebSocketClient = require('./WebSocketClient'); 18 | var toBuffer = require('typedarray-to-buffer'); 19 | 20 | 21 | const CONNECTING = 0; 22 | const OPEN = 1; 23 | const CLOSING = 2; 24 | const CLOSED = 3; 25 | 26 | 27 | function WebSocket(url, protocols, origin, headers, requestOptions, clientConfig) { 28 | // Sanitize clientConfig. 29 | clientConfig = clientConfig || {}; 30 | clientConfig.assembleFragments = true; // Required in the W3C API. 31 | 32 | // W3C attributes and listeners. 33 | this._listeners = { 34 | onopen: undefined, 35 | onerror: undefined, 36 | onclose: undefined, 37 | onmessage: undefined 38 | }; 39 | this._url = url; 40 | this._readyState = CONNECTING; 41 | this._protocol = undefined; 42 | this._extensions = ''; 43 | this._bufferedAmount = 0; // Hack, always 0. 44 | this._binaryType = 'arraybuffer'; // TODO: Should be 'blob' by default, but Node has no Blob. 45 | 46 | // The WebSocketConnection instance. 47 | this._connection = undefined; 48 | 49 | // WebSocketClient instance. 50 | this._client = new WebSocketClient(clientConfig); 51 | 52 | this._client.on('connect', onConnect.bind(this)); 53 | this._client.on('connectFailed', onConnectFailed.bind(this)); 54 | 55 | this._client.connect(url, protocols, origin, headers, requestOptions); 56 | } 57 | 58 | 59 | // Expose W3C listener setters/getters. 60 | ['onopen', 'onerror', 'onclose', 'onmessage'].forEach(function(method) { 61 | Object.defineProperty(WebSocket.prototype, method, { 62 | get: function() { 63 | return this._listeners[method]; 64 | }, 65 | set: function(listener) { 66 | if (typeof listener === 'function') { 67 | this._listeners[method] = listener; 68 | } 69 | else { 70 | this._listeners[method] = undefined; 71 | } 72 | } 73 | }); 74 | }); 75 | 76 | 77 | // Expose W3C read only attributes. 78 | Object.defineProperties(WebSocket.prototype, { 79 | url: { get: function() { return this._url; } }, 80 | readyState: { get: function() { return this._readyState; } }, 81 | protocol: { get: function() { return this._protocol; } }, 82 | extensions: { get: function() { return this._extensions; } }, 83 | bufferedAmount: { get: function() { return this._bufferedAmount; } } 84 | }); 85 | 86 | 87 | // Expose W3C write/read attributes. 88 | Object.defineProperties(WebSocket.prototype, { 89 | binaryType: { 90 | get: function() { 91 | return this._binaryType; 92 | }, 93 | set: function(type) { 94 | // TODO: Just 'arraybuffer' supported. 95 | if (type !== 'arraybuffer') { 96 | throw new SyntaxError('just "blob" type allowed for "binaryType" attribute'); 97 | } 98 | this._binaryType = type; 99 | } 100 | } 101 | }); 102 | 103 | 104 | // Expose W3C readyState constants. 105 | [['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) { 106 | Object.defineProperty(WebSocket.prototype, property[0], { 107 | get: function() { return property[1]; } 108 | }); 109 | }); 110 | 111 | 112 | WebSocket.prototype.send = function(data) { 113 | if (this._readyState !== OPEN) { 114 | throw new Error('cannot call send() while not connected'); 115 | } 116 | 117 | // Text. 118 | if (typeof data === 'string' || data instanceof String) { 119 | this._connection.sendUTF(data); 120 | } 121 | // Binary. 122 | else { 123 | // Node Buffer. 124 | if (data instanceof Buffer) { 125 | this._connection.sendBytes(data); 126 | } 127 | // If ArrayBuffer or ArrayBufferView convert it to Node Buffer. 128 | else if (data.byteLength || data.byteLength === 0) { 129 | data = toBuffer(data); 130 | this._connection.sendBytes(data); 131 | } 132 | else { 133 | throw new Error('unknown binary data:', data); 134 | } 135 | } 136 | }; 137 | 138 | 139 | WebSocket.prototype.close = function() { 140 | switch(this._readyState) { 141 | case CONNECTING: 142 | // TODO: We don't have the WebSocketConnection instance yet so no 143 | // way to close the TCP connection. 144 | // Artificially invoke the onConnectFailed event. 145 | onConnectFailed.call(this); 146 | // And close if it connects after a while. 147 | this._client.on('connect', function(connection) { 148 | connection.close(); 149 | }); 150 | break; 151 | case OPEN: 152 | this._readyState = CLOSING; 153 | this._connection.close(); 154 | break; 155 | case CLOSING: 156 | case CLOSED: 157 | break; 158 | } 159 | }; 160 | 161 | 162 | /** 163 | * Private API. 164 | */ 165 | 166 | 167 | function OpenEvent(target) { 168 | this.type = 'open'; 169 | this.target = target; 170 | } 171 | 172 | 173 | function ErrorEvent(target) { 174 | this.type = 'error'; 175 | this.target = target; 176 | } 177 | 178 | 179 | function CloseEvent(target, code, reason) { 180 | this.type = 'close'; 181 | this.target = target; 182 | this.code = code; 183 | this.reason = reason; 184 | this.wasClean = (typeof code === 'undefined' || code === 1000); 185 | } 186 | 187 | 188 | function MessageEvent(target, data) { 189 | this.type = 'message'; 190 | this.target = target; 191 | this.data = data; 192 | } 193 | 194 | 195 | function onConnect(connection) { 196 | this._readyState = OPEN; 197 | this._connection = connection; 198 | this._protocol = connection.protocol; 199 | this._extensions = connection.extensions; 200 | 201 | this._connection.on('close', onClose.bind(this)); 202 | this._connection.on('message', onMessage.bind(this)); 203 | 204 | callListener.call(this, 'onopen', new OpenEvent(this)); 205 | } 206 | 207 | 208 | function onConnectFailed() { 209 | destroy.call(this); 210 | this._readyState = CLOSED; 211 | 212 | // Emit 'close' after 'error' even if 'error' listener throws. 213 | global.setTimeout(function() { 214 | callListener.call(this, 'onclose', new CloseEvent(this, 1006, 'connection failed')); 215 | }.bind(this)); 216 | callListener.call(this, 'onerror', new ErrorEvent(this)); 217 | } 218 | 219 | 220 | function onClose(code, reason) { 221 | destroy.call(this); 222 | this._readyState = CLOSED; 223 | 224 | callListener.call(this, 'onclose', new CloseEvent(this, code, reason || '')); 225 | } 226 | 227 | 228 | function onMessage(message) { 229 | if (message.utf8Data) { 230 | callListener.call(this, 'onmessage', new MessageEvent(this, message.utf8Data)); 231 | } 232 | else if (message.binaryData) { 233 | // Must convert from Node Buffer to ArrayBuffer. 234 | // TODO: or to a Blob (which does not exist in Node!). 235 | if (this.binaryType === 'arraybuffer') { 236 | var buffer = message.binaryData; 237 | var arraybuffer = new ArrayBuffer(buffer.length); 238 | var view = new Uint8Array(arraybuffer); 239 | for (var i=0, len=buffer.length; i= 2) { 45 | bufferList.joinInto(this.frameHeader, 0, 0, 2); 46 | bufferList.advance(2); 47 | var firstByte = this.frameHeader[0]; 48 | var secondByte = this.frameHeader[1]; 49 | 50 | this.fin = Boolean(firstByte & 0x80); 51 | this.rsv1 = Boolean(firstByte & 0x40); 52 | this.rsv2 = Boolean(firstByte & 0x20); 53 | this.rsv3 = Boolean(firstByte & 0x10); 54 | this.mask = Boolean(secondByte & 0x80); 55 | 56 | this.opcode = firstByte & 0x0F; 57 | this.length = secondByte & 0x7F; 58 | 59 | // Control frame sanity check 60 | if (this.opcode >= 0x08) { 61 | if (this.length > 125) { 62 | this.protocolError = true; 63 | this.dropReason = 'Illegal control frame longer than 125 bytes.'; 64 | return true; 65 | } 66 | if (!this.fin) { 67 | this.protocolError = true; 68 | this.dropReason = 'Control frames must not be fragmented.'; 69 | return true; 70 | } 71 | } 72 | 73 | if (this.length === 126) { 74 | this.parseState = WAITING_FOR_16_BIT_LENGTH; 75 | } 76 | else if (this.length === 127) { 77 | this.parseState = WAITING_FOR_64_BIT_LENGTH; 78 | } 79 | else { 80 | this.parseState = WAITING_FOR_MASK_KEY; 81 | } 82 | } 83 | } 84 | if (this.parseState === WAITING_FOR_16_BIT_LENGTH) { 85 | if (bufferList.length >= 2) { 86 | bufferList.joinInto(this.frameHeader, 2, 0, 2); 87 | bufferList.advance(2); 88 | this.length = this.frameHeader.readUInt16BE(2, true); 89 | this.parseState = WAITING_FOR_MASK_KEY; 90 | } 91 | } 92 | else if (this.parseState === WAITING_FOR_64_BIT_LENGTH) { 93 | if (bufferList.length >= 8) { 94 | bufferList.joinInto(this.frameHeader, 2, 0, 8); 95 | bufferList.advance(8); 96 | var lengthPair = [ 97 | this.frameHeader.readUInt32BE(2, true), 98 | this.frameHeader.readUInt32BE(2+4, true) 99 | ]; 100 | 101 | if (lengthPair[0] !== 0) { 102 | this.protocolError = true; 103 | this.dropReason = 'Unsupported 64-bit length frame received'; 104 | return true; 105 | } 106 | this.length = lengthPair[1]; 107 | this.parseState = WAITING_FOR_MASK_KEY; 108 | } 109 | } 110 | 111 | if (this.parseState === WAITING_FOR_MASK_KEY) { 112 | if (this.mask) { 113 | if (bufferList.length >= 4) { 114 | bufferList.joinInto(this.maskBytes, 0, 0, 4); 115 | bufferList.advance(4); 116 | this.parseState = WAITING_FOR_PAYLOAD; 117 | } 118 | } 119 | else { 120 | this.parseState = WAITING_FOR_PAYLOAD; 121 | } 122 | } 123 | 124 | if (this.parseState === WAITING_FOR_PAYLOAD) { 125 | if (this.length > this.maxReceivedFrameSize) { 126 | this.frameTooLarge = true; 127 | this.dropReason = 'Frame size of ' + this.length.toString(10) + 128 | ' bytes exceeds maximum accepted frame size'; 129 | return true; 130 | } 131 | 132 | if (this.length === 0) { 133 | this.binaryPayload = new Buffer(0); 134 | this.parseState = COMPLETE; 135 | return true; 136 | } 137 | if (bufferList.length >= this.length) { 138 | this.binaryPayload = bufferList.take(this.length); 139 | bufferList.advance(this.length); 140 | if (this.mask) { 141 | bufferUtil.unmask(this.binaryPayload, this.maskBytes); 142 | // xor(this.binaryPayload, this.maskBytes, 0); 143 | } 144 | 145 | if (this.opcode === 0x08) { // WebSocketOpcode.CONNECTION_CLOSE 146 | if (this.length === 1) { 147 | // Invalid length for a close frame. Must be zero or at least two. 148 | this.binaryPayload = new Buffer(0); 149 | this.invalidCloseFrameLength = true; 150 | } 151 | if (this.length >= 2) { 152 | this.closeStatus = this.binaryPayload.readUInt16BE(0, true); 153 | this.binaryPayload = this.binaryPayload.slice(2); 154 | } 155 | } 156 | 157 | this.parseState = COMPLETE; 158 | return true; 159 | } 160 | } 161 | return false; 162 | }; 163 | 164 | WebSocketFrame.prototype.throwAwayPayload = function(bufferList) { 165 | if (bufferList.length >= this.length) { 166 | bufferList.advance(this.length); 167 | this.parseState = COMPLETE; 168 | return true; 169 | } 170 | return false; 171 | }; 172 | 173 | WebSocketFrame.prototype.toBuffer = function(nullMask) { 174 | var maskKey; 175 | var headerLength = 2; 176 | var data; 177 | var outputPos; 178 | var firstByte = 0x00; 179 | var secondByte = 0x00; 180 | 181 | if (this.fin) { 182 | firstByte |= 0x80; 183 | } 184 | if (this.rsv1) { 185 | firstByte |= 0x40; 186 | } 187 | if (this.rsv2) { 188 | firstByte |= 0x20; 189 | } 190 | if (this.rsv3) { 191 | firstByte |= 0x10; 192 | } 193 | if (this.mask) { 194 | secondByte |= 0x80; 195 | } 196 | 197 | firstByte |= (this.opcode & 0x0F); 198 | 199 | // the close frame is a special case because the close reason is 200 | // prepended to the payload data. 201 | if (this.opcode === 0x08) { 202 | this.length = 2; 203 | if (this.binaryPayload) { 204 | this.length += this.binaryPayload.length; 205 | } 206 | data = new Buffer(this.length); 207 | data.writeUInt16BE(this.closeStatus, 0, true); 208 | if (this.length > 2) { 209 | this.binaryPayload.copy(data, 2); 210 | } 211 | } 212 | else if (this.binaryPayload) { 213 | data = this.binaryPayload; 214 | this.length = data.length; 215 | } 216 | else { 217 | this.length = 0; 218 | } 219 | 220 | if (this.length <= 125) { 221 | // encode the length directly into the two-byte frame header 222 | secondByte |= (this.length & 0x7F); 223 | } 224 | else if (this.length > 125 && this.length <= 0xFFFF) { 225 | // Use 16-bit length 226 | secondByte |= 126; 227 | headerLength += 2; 228 | } 229 | else if (this.length > 0xFFFF) { 230 | // Use 64-bit length 231 | secondByte |= 127; 232 | headerLength += 8; 233 | } 234 | 235 | var output = new Buffer(this.length + headerLength + (this.mask ? 4 : 0)); 236 | 237 | // write the frame header 238 | output[0] = firstByte; 239 | output[1] = secondByte; 240 | 241 | outputPos = 2; 242 | 243 | if (this.length > 125 && this.length <= 0xFFFF) { 244 | // write 16-bit length 245 | output.writeUInt16BE(this.length, outputPos, true); 246 | outputPos += 2; 247 | } 248 | else if (this.length > 0xFFFF) { 249 | // write 64-bit length 250 | output.writeUInt32BE(0x00000000, outputPos, true); 251 | output.writeUInt32BE(this.length, outputPos + 4, true); 252 | outputPos += 8; 253 | } 254 | 255 | if (this.mask) { 256 | maskKey = nullMask ? 0 : (Math.random()*0xFFFFFFFF) | 0; 257 | this.maskBytes.writeUInt32BE(maskKey, 0, true); 258 | 259 | // write the mask key 260 | this.maskBytes.copy(output, outputPos); 261 | outputPos += 4; 262 | 263 | if (data) { 264 | bufferUtil.mask(data, this.maskBytes, output, outputPos, this.length); 265 | } 266 | } 267 | else if (data) { 268 | data.copy(output, outputPos); 269 | } 270 | 271 | return output; 272 | }; 273 | 274 | WebSocketFrame.prototype.toString = function() { 275 | return 'Opcode: ' + this.opcode + ', fin: ' + this.fin + ', length: ' + this.length + ', hasPayload: ' + Boolean(this.binaryPayload) + ', masked: ' + this.mask; 276 | }; 277 | 278 | 279 | module.exports = WebSocketFrame; 280 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/WebSocketRouter.js: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * Copyright 2010-2011 Worlize Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***********************************************************************/ 16 | 17 | var extend = require('./utils').extend; 18 | var util = require('util'); 19 | var EventEmitter = require('events').EventEmitter; 20 | var WebSocketRouterRequest = require('./WebSocketRouterRequest'); 21 | 22 | function WebSocketRouter(config) { 23 | // Superclass Constructor 24 | EventEmitter.call(this); 25 | 26 | this.config = { 27 | // The WebSocketServer instance to attach to. 28 | server: null 29 | }; 30 | if (config) { 31 | extend(this.config, config); 32 | } 33 | this.handlers = []; 34 | 35 | this._requestHandler = this.handleRequest.bind(this); 36 | if (this.config.server) { 37 | this.attachServer(this.config.server); 38 | } 39 | } 40 | 41 | util.inherits(WebSocketRouter, EventEmitter); 42 | 43 | WebSocketRouter.prototype.attachServer = function(server) { 44 | if (server) { 45 | this.server = server; 46 | this.server.on('request', this._requestHandler); 47 | } 48 | else { 49 | throw new Error('You must specify a WebSocketServer instance to attach to.'); 50 | } 51 | }; 52 | 53 | WebSocketRouter.prototype.detachServer = function() { 54 | if (this.server) { 55 | this.server.removeListener('request', this._requestHandler); 56 | this.server = null; 57 | } 58 | else { 59 | throw new Error('Cannot detach from server: not attached.'); 60 | } 61 | }; 62 | 63 | WebSocketRouter.prototype.mount = function(path, protocol, callback) { 64 | if (!path) { 65 | throw new Error('You must specify a path for this handler.'); 66 | } 67 | if (!protocol) { 68 | protocol = '____no_protocol____'; 69 | } 70 | if (!callback) { 71 | throw new Error('You must specify a callback for this handler.'); 72 | } 73 | 74 | path = this.pathToRegExp(path); 75 | if (!(path instanceof RegExp)) { 76 | throw new Error('Path must be specified as either a string or a RegExp.'); 77 | } 78 | var pathString = path.toString(); 79 | 80 | // normalize protocol to lower-case 81 | protocol = protocol.toLocaleLowerCase(); 82 | 83 | if (this.findHandlerIndex(pathString, protocol) !== -1) { 84 | throw new Error('You may only mount one handler per path/protocol combination.'); 85 | } 86 | 87 | this.handlers.push({ 88 | 'path': path, 89 | 'pathString': pathString, 90 | 'protocol': protocol, 91 | 'callback': callback 92 | }); 93 | }; 94 | WebSocketRouter.prototype.unmount = function(path, protocol) { 95 | var index = this.findHandlerIndex(this.pathToRegExp(path).toString(), protocol); 96 | if (index !== -1) { 97 | this.handlers.splice(index, 1); 98 | } 99 | else { 100 | throw new Error('Unable to find a route matching the specified path and protocol.'); 101 | } 102 | }; 103 | 104 | WebSocketRouter.prototype.findHandlerIndex = function(pathString, protocol) { 105 | protocol = protocol.toLocaleLowerCase(); 106 | for (var i=0, len=this.handlers.length; i < len; i++) { 107 | var handler = this.handlers[i]; 108 | if (handler.pathString === pathString && handler.protocol === protocol) { 109 | return i; 110 | } 111 | } 112 | return -1; 113 | }; 114 | 115 | WebSocketRouter.prototype.pathToRegExp = function(path) { 116 | if (typeof(path) === 'string') { 117 | if (path === '*') { 118 | path = /^.*$/; 119 | } 120 | else { 121 | path = path.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); 122 | path = new RegExp('^' + path + '$'); 123 | } 124 | } 125 | return path; 126 | }; 127 | 128 | WebSocketRouter.prototype.handleRequest = function(request) { 129 | var requestedProtocols = request.requestedProtocols; 130 | if (requestedProtocols.length === 0) { 131 | requestedProtocols = ['____no_protocol____']; 132 | } 133 | 134 | // Find a handler with the first requested protocol first 135 | for (var i=0; i < requestedProtocols.length; i++) { 136 | var requestedProtocol = requestedProtocols[i].toLocaleLowerCase(); 137 | 138 | // find the first handler that can process this request 139 | for (var j=0, len=this.handlers.length; j < len; j++) { 140 | var handler = this.handlers[j]; 141 | if (handler.path.test(request.resourceURL.pathname)) { 142 | if (requestedProtocol === handler.protocol || 143 | handler.protocol === '*') 144 | { 145 | var routerRequest = new WebSocketRouterRequest(request, requestedProtocol); 146 | handler.callback(routerRequest); 147 | return; 148 | } 149 | } 150 | } 151 | } 152 | 153 | // If we get here we were unable to find a suitable handler. 154 | request.reject(404, 'No handler is available for the given request.'); 155 | }; 156 | 157 | module.exports = WebSocketRouter; 158 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/WebSocketRouterRequest.js: -------------------------------------------------------------------------------- 1 | /************************************************************************ 2 | * Copyright 2010-2011 Worlize Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | ***********************************************************************/ 16 | 17 | var util = require('util'); 18 | var EventEmitter = require('events').EventEmitter; 19 | 20 | function WebSocketRouterRequest(webSocketRequest, resolvedProtocol) { 21 | // Superclass Constructor 22 | EventEmitter.call(this); 23 | 24 | this.webSocketRequest = webSocketRequest; 25 | if (resolvedProtocol === '____no_protocol____') { 26 | this.protocol = null; 27 | } 28 | else { 29 | this.protocol = resolvedProtocol; 30 | } 31 | this.origin = webSocketRequest.origin; 32 | this.resource = webSocketRequest.resource; 33 | this.resourceURL = webSocketRequest.resourceURL; 34 | this.httpRequest = webSocketRequest.httpRequest; 35 | this.remoteAddress = webSocketRequest.remoteAddress; 36 | this.webSocketVersion = webSocketRequest.webSocketVersion; 37 | this.requestedExtensions = webSocketRequest.requestedExtensions; 38 | this.cookies = webSocketRequest.cookies; 39 | } 40 | 41 | util.inherits(WebSocketRouterRequest, EventEmitter); 42 | 43 | WebSocketRouterRequest.prototype.accept = function(origin, cookies) { 44 | var connection = this.webSocketRequest.accept(this.protocol, origin, cookies); 45 | this.emit('requestAccepted', connection); 46 | return connection; 47 | }; 48 | 49 | WebSocketRouterRequest.prototype.reject = function(status, reason, extraHeaders) { 50 | this.webSocketRequest.reject(status, reason, extraHeaders); 51 | this.emit('requestRejected', this); 52 | }; 53 | 54 | module.exports = WebSocketRouterRequest; 55 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/browser.js: -------------------------------------------------------------------------------- 1 | var _global = (function() { return this; })(); 2 | var nativeWebSocket = _global.WebSocket || _global.MozWebSocket; 3 | 4 | 5 | /** 6 | * Expose a W3C WebSocket class with just one or two arguments. 7 | */ 8 | function W3CWebSocket(uri, protocols) { 9 | var native_instance; 10 | 11 | if (protocols) { 12 | native_instance = new nativeWebSocket(uri, protocols); 13 | } 14 | else { 15 | native_instance = new nativeWebSocket(uri); 16 | } 17 | 18 | /** 19 | * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket 20 | * class). Since it is an Object it will be returned as it is when creating an 21 | * instance of W3CWebSocket via 'new W3CWebSocket()'. 22 | * 23 | * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 24 | */ 25 | return native_instance; 26 | } 27 | 28 | 29 | /** 30 | * Module exports. 31 | */ 32 | module.exports = { 33 | 'w3cwebsocket' : nativeWebSocket ? W3CWebSocket : null, 34 | 'version' : require('./version') 35 | }; 36 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/utils.js: -------------------------------------------------------------------------------- 1 | var noop = exports.noop = function(){}; 2 | 3 | exports.extend = function extend(dest, source) { 4 | for (var prop in source) { 5 | dest[prop] = source[prop]; 6 | } 7 | }; 8 | 9 | exports.eventEmitterListenerCount = 10 | require('events').EventEmitter.listenerCount || 11 | function(emitter, type) { return emitter.listeners(type).length; }; 12 | 13 | 14 | 15 | 16 | 17 | exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) { 18 | var logFunction = require('debug')(identifier); 19 | if (logFunction.enabled) { 20 | var logger = new BufferingLogger(identifier, uniqueID, logFunction); 21 | var debug = logger.log.bind(logger); 22 | debug.printOutput = logger.printOutput.bind(logger); 23 | debug.enabled = logFunction.enabled; 24 | return debug; 25 | } 26 | logFunction.printOutput = noop; 27 | return logFunction; 28 | }; 29 | 30 | function BufferingLogger(identifier, uniqueID, logFunction) { 31 | this.logFunction = logFunction; 32 | this.identifier = identifier; 33 | this.uniqueID = uniqueID; 34 | this.buffer = []; 35 | } 36 | 37 | BufferingLogger.prototype.log = function() { 38 | this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]); 39 | return this; 40 | }; 41 | 42 | BufferingLogger.prototype.clear = function() { 43 | this.buffer = []; 44 | return this; 45 | }; 46 | 47 | BufferingLogger.prototype.printOutput = function(logFunction) { 48 | if (!logFunction) { logFunction = this.logFunction; } 49 | var uniqueID = this.uniqueID; 50 | this.buffer.forEach(function(entry) { 51 | var date = entry[0].toLocaleString(); 52 | var args = entry[1].slice(); 53 | var formatString = args[0]; 54 | if (formatString !== (void 0) && formatString !== null) { 55 | formatString = '%s - %s - ' + formatString.toString(); 56 | args.splice(0, 1, formatString, date, uniqueID); 57 | logFunction.apply(global, args); 58 | } 59 | }); 60 | }; 61 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/version.js: -------------------------------------------------------------------------------- 1 | module.exports = require('../package.json').version; 2 | -------------------------------------------------------------------------------- /node_modules/websocket/lib/websocket.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'server' : require('./WebSocketServer'), 3 | 'client' : require('./WebSocketClient'), 4 | 'router' : require('./WebSocketRouter'), 5 | 'frame' : require('./WebSocketFrame'), 6 | 'request' : require('./WebSocketRequest'), 7 | 'connection' : require('./WebSocketConnection'), 8 | 'w3cwebsocket' : require('./W3CWebSocket'), 9 | 'deprecation' : require('./Deprecation'), 10 | 'version' : require('./version') 11 | }; 12 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "laxbreak": true 3 | } 4 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/.npmignore: -------------------------------------------------------------------------------- 1 | support 2 | test 3 | examples 4 | example 5 | *.sock 6 | dist 7 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/History.md: -------------------------------------------------------------------------------- 1 | 2 | 2.1.1 / 2014-12-29 3 | ================== 4 | 5 | * browser: use `typeof` to check for `console` existence 6 | * browser: check for `console.log` truthiness (fix IE 8/9) 7 | * browser: add support for Chrome apps 8 | * Readme: added Windows usage remarks 9 | * Add `bower.json` to properly support bower install 10 | 11 | 2.1.0 / 2014-10-15 12 | ================== 13 | 14 | * node: implement `DEBUG_FD` env variable support 15 | * package: update "browserify" to v6.1.0 16 | * package: add "license" field to package.json (#135, @panuhorsmalahti) 17 | 18 | 2.0.0 / 2014-09-01 19 | ================== 20 | 21 | * package: update "browserify" to v5.11.0 22 | * node: use stderr rather than stdout for logging (#29, @stephenmathieson) 23 | 24 | 1.0.4 / 2014-07-15 25 | ================== 26 | 27 | * dist: recompile 28 | * example: remove `console.info()` log usage 29 | * example: add "Content-Type" UTF-8 header to browser example 30 | * browser: place %c marker after the space character 31 | * browser: reset the "content" color via `color: inherit` 32 | * browser: add colors support for Firefox >= v31 33 | * debug: prefer an instance `log()` function over the global one (#119) 34 | * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) 35 | 36 | 1.0.3 / 2014-07-09 37 | ================== 38 | 39 | * Add support for multiple wildcards in namespaces (#122, @seegno) 40 | * browser: fix lint 41 | 42 | 1.0.2 / 2014-06-10 43 | ================== 44 | 45 | * browser: update color palette (#113, @gscottolson) 46 | * common: make console logging function configurable (#108, @timoxley) 47 | * node: fix %o colors on old node <= 0.8.x 48 | * Makefile: find node path using shell/which (#109, @timoxley) 49 | 50 | 1.0.1 / 2014-06-06 51 | ================== 52 | 53 | * browser: use `removeItem()` to clear localStorage 54 | * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) 55 | * package: add "contributors" section 56 | * node: fix comment typo 57 | * README: list authors 58 | 59 | 1.0.0 / 2014-06-04 60 | ================== 61 | 62 | * make ms diff be global, not be scope 63 | * debug: ignore empty strings in enable() 64 | * node: make DEBUG_COLORS able to disable coloring 65 | * *: export the `colors` array 66 | * npmignore: don't publish the `dist` dir 67 | * Makefile: refactor to use browserify 68 | * package: add "browserify" as a dev dependency 69 | * Readme: add Web Inspector Colors section 70 | * node: reset terminal color for the debug content 71 | * node: map "%o" to `util.inspect()` 72 | * browser: map "%j" to `JSON.stringify()` 73 | * debug: add custom "formatters" 74 | * debug: use "ms" module for humanizing the diff 75 | * Readme: add "bash" syntax highlighting 76 | * browser: add Firebug color support 77 | * browser: add colors for WebKit browsers 78 | * node: apply log to `console` 79 | * rewrite: abstract common logic for Node & browsers 80 | * add .jshintrc file 81 | 82 | 0.8.1 / 2014-04-14 83 | ================== 84 | 85 | * package: re-add the "component" section 86 | 87 | 0.8.0 / 2014-03-30 88 | ================== 89 | 90 | * add `enable()` method for nodejs. Closes #27 91 | * change from stderr to stdout 92 | * remove unnecessary index.js file 93 | 94 | 0.7.4 / 2013-11-13 95 | ================== 96 | 97 | * remove "browserify" key from package.json (fixes something in browserify) 98 | 99 | 0.7.3 / 2013-10-30 100 | ================== 101 | 102 | * fix: catch localStorage security error when cookies are blocked (Chrome) 103 | * add debug(err) support. Closes #46 104 | * add .browser prop to package.json. Closes #42 105 | 106 | 0.7.2 / 2013-02-06 107 | ================== 108 | 109 | * fix package.json 110 | * fix: Mobile Safari (private mode) is broken with debug 111 | * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript 112 | 113 | 0.7.1 / 2013-02-05 114 | ================== 115 | 116 | * add repository URL to package.json 117 | * add DEBUG_COLORED to force colored output 118 | * add browserify support 119 | * fix component. Closes #24 120 | 121 | 0.7.0 / 2012-05-04 122 | ================== 123 | 124 | * Added .component to package.json 125 | * Added debug.component.js build 126 | 127 | 0.6.0 / 2012-03-16 128 | ================== 129 | 130 | * Added support for "-" prefix in DEBUG [Vinay Pulim] 131 | * Added `.enabled` flag to the node version [TooTallNate] 132 | 133 | 0.5.0 / 2012-02-02 134 | ================== 135 | 136 | * Added: humanize diffs. Closes #8 137 | * Added `debug.disable()` to the CS variant 138 | * Removed padding. Closes #10 139 | * Fixed: persist client-side variant again. Closes #9 140 | 141 | 0.4.0 / 2012-02-01 142 | ================== 143 | 144 | * Added browser variant support for older browsers [TooTallNate] 145 | * Added `debug.enable('project:*')` to browser variant [TooTallNate] 146 | * Added padding to diff (moved it to the right) 147 | 148 | 0.3.0 / 2012-01-26 149 | ================== 150 | 151 | * Added millisecond diff when isatty, otherwise UTC string 152 | 153 | 0.2.0 / 2012-01-22 154 | ================== 155 | 156 | * Added wildcard support 157 | 158 | 0.1.0 / 2011-12-02 159 | ================== 160 | 161 | * Added: remove colors unless stderr isatty [TooTallNate] 162 | 163 | 0.0.1 / 2010-01-03 164 | ================== 165 | 166 | * Initial release 167 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/Makefile: -------------------------------------------------------------------------------- 1 | 2 | # get Makefile directory name: http://stackoverflow.com/a/5982798/376773 3 | THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) 4 | THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) 5 | 6 | # BIN directory 7 | BIN := $(THIS_DIR)/node_modules/.bin 8 | 9 | # applications 10 | NODE ?= $(shell which node) 11 | NPM ?= $(NODE) $(shell which npm) 12 | BROWSERIFY ?= $(NODE) $(BIN)/browserify 13 | 14 | all: dist/debug.js 15 | 16 | install: node_modules 17 | 18 | clean: 19 | @rm -rf node_modules dist 20 | 21 | dist: 22 | @mkdir -p $@ 23 | 24 | dist/debug.js: node_modules browser.js debug.js dist 25 | @$(BROWSERIFY) \ 26 | --standalone debug \ 27 | . > $@ 28 | 29 | node_modules: package.json 30 | @NODE_ENV= $(NPM) install 31 | @touch node_modules 32 | 33 | .PHONY: all install clean 34 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/Readme.md: -------------------------------------------------------------------------------- 1 | # debug 2 | 3 | tiny node.js debugging utility modelled after node core's debugging technique. 4 | 5 | ## Installation 6 | 7 | ```bash 8 | $ npm install debug 9 | ``` 10 | 11 | ## Usage 12 | 13 | With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. 14 | 15 | Example _app.js_: 16 | 17 | ```js 18 | var debug = require('debug')('http') 19 | , http = require('http') 20 | , name = 'My App'; 21 | 22 | // fake app 23 | 24 | debug('booting %s', name); 25 | 26 | http.createServer(function(req, res){ 27 | debug(req.method + ' ' + req.url); 28 | res.end('hello\n'); 29 | }).listen(3000, function(){ 30 | debug('listening'); 31 | }); 32 | 33 | // fake worker of some kind 34 | 35 | require('./worker'); 36 | ``` 37 | 38 | Example _worker.js_: 39 | 40 | ```js 41 | var debug = require('debug')('worker'); 42 | 43 | setInterval(function(){ 44 | debug('doing some work'); 45 | }, 1000); 46 | ``` 47 | 48 | The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: 49 | 50 | ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) 51 | 52 | ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) 53 | 54 | #### Windows note 55 | 56 | On Windows the environment variable is set using the `set` command. 57 | 58 | ```cmd 59 | set DEBUG=*,-not_this 60 | ``` 61 | 62 | Then, run the program to be debugged as ususal. 63 | 64 | ## Millisecond diff 65 | 66 | When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. 67 | 68 | ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) 69 | 70 | When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: 71 | 72 | ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) 73 | 74 | ## Conventions 75 | 76 | If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". 77 | 78 | ## Wildcards 79 | 80 | The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. 81 | 82 | You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". 83 | 84 | ## Browser support 85 | 86 | Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. 87 | 88 | ```js 89 | a = debug('worker:a'); 90 | b = debug('worker:b'); 91 | 92 | setInterval(function(){ 93 | a('doing some work'); 94 | }, 1000); 95 | 96 | setInterval(function(){ 97 | b('doing some work'); 98 | }, 1200); 99 | ``` 100 | 101 | #### Web Inspector Colors 102 | 103 | Colors are also enabled on "Web Inspectors" that understand the `%c` formatting 104 | option. These are WebKit web inspectors, Firefox ([since version 105 | 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) 106 | and the Firebug plugin for Firefox (any version). 107 | 108 | Colored output looks something like: 109 | 110 | ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) 111 | 112 | ### stderr vs stdout 113 | 114 | You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally: 115 | 116 | Example _stderr.js_: 117 | 118 | ```js 119 | var debug = require('../'); 120 | var log = debug('app:log'); 121 | 122 | // by default console.log is used 123 | log('goes to stdout!'); 124 | 125 | var error = debug('app:error'); 126 | // set this namespace to log via console.error 127 | error.log = console.error.bind(console); // don't forget to bind to console! 128 | error('goes to stderr'); 129 | log('still goes to stdout!'); 130 | 131 | // set all output to go via console.warn 132 | // overrides all per-namespace log settings 133 | debug.log = console.warn.bind(console); 134 | log('now goes to stderr via console.warn'); 135 | error('still goes to stderr, but via console.warn now'); 136 | ``` 137 | 138 | ## Authors 139 | 140 | - TJ Holowaychuk 141 | - Nathan Rajlich 142 | 143 | ## License 144 | 145 | (The MIT License) 146 | 147 | Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> 148 | 149 | Permission is hereby granted, free of charge, to any person obtaining 150 | a copy of this software and associated documentation files (the 151 | 'Software'), to deal in the Software without restriction, including 152 | without limitation the rights to use, copy, modify, merge, publish, 153 | distribute, sublicense, and/or sell copies of the Software, and to 154 | permit persons to whom the Software is furnished to do so, subject to 155 | the following conditions: 156 | 157 | The above copyright notice and this permission notice shall be 158 | included in all copies or substantial portions of the Software. 159 | 160 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 161 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 162 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 163 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 164 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 165 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 166 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 167 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "visionmedia/debug", 3 | "main": "dist/debug.js", 4 | "version": "2.1.1", 5 | "homepage": "https://github.com/visionmedia/debug", 6 | "authors": [ 7 | "TJ Holowaychuk " 8 | ], 9 | "description": "visionmedia/debug", 10 | "moduleType": [ 11 | "amd", 12 | "es6", 13 | "globals", 14 | "node" 15 | ], 16 | "keywords": [ 17 | "visionmedia", 18 | "debug" 19 | ], 20 | "license": "MIT", 21 | "ignore": [ 22 | "**/.*", 23 | "node_modules", 24 | "bower_components", 25 | "test", 26 | "tests" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/browser.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * This is the web browser implementation of `debug()`. 4 | * 5 | * Expose `debug()` as the module. 6 | */ 7 | 8 | exports = module.exports = require('./debug'); 9 | exports.log = log; 10 | exports.formatArgs = formatArgs; 11 | exports.save = save; 12 | exports.load = load; 13 | exports.useColors = useColors; 14 | 15 | /** 16 | * Use chrome.storage.local if we are in an app 17 | */ 18 | 19 | var storage; 20 | 21 | if (typeof chrome !== 'undefined' && typeof chrome.storage !== 'undefined') 22 | storage = chrome.storage.local; 23 | else 24 | storage = window.localStorage; 25 | 26 | /** 27 | * Colors. 28 | */ 29 | 30 | exports.colors = [ 31 | 'lightseagreen', 32 | 'forestgreen', 33 | 'goldenrod', 34 | 'dodgerblue', 35 | 'darkorchid', 36 | 'crimson' 37 | ]; 38 | 39 | /** 40 | * Currently only WebKit-based Web Inspectors, Firefox >= v31, 41 | * and the Firebug extension (any Firefox version) are known 42 | * to support "%c" CSS customizations. 43 | * 44 | * TODO: add a `localStorage` variable to explicitly enable/disable colors 45 | */ 46 | 47 | function useColors() { 48 | // is webkit? http://stackoverflow.com/a/16459606/376773 49 | return ('WebkitAppearance' in document.documentElement.style) || 50 | // is firebug? http://stackoverflow.com/a/398120/376773 51 | (window.console && (console.firebug || (console.exception && console.table))) || 52 | // is firefox >= v31? 53 | // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages 54 | (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); 55 | } 56 | 57 | /** 58 | * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. 59 | */ 60 | 61 | exports.formatters.j = function(v) { 62 | return JSON.stringify(v); 63 | }; 64 | 65 | 66 | /** 67 | * Colorize log arguments if enabled. 68 | * 69 | * @api public 70 | */ 71 | 72 | function formatArgs() { 73 | var args = arguments; 74 | var useColors = this.useColors; 75 | 76 | args[0] = (useColors ? '%c' : '') 77 | + this.namespace 78 | + (useColors ? ' %c' : ' ') 79 | + args[0] 80 | + (useColors ? '%c ' : ' ') 81 | + '+' + exports.humanize(this.diff); 82 | 83 | if (!useColors) return args; 84 | 85 | var c = 'color: ' + this.color; 86 | args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); 87 | 88 | // the final "%c" is somewhat tricky, because there could be other 89 | // arguments passed either before or after the %c, so we need to 90 | // figure out the correct index to insert the CSS into 91 | var index = 0; 92 | var lastC = 0; 93 | args[0].replace(/%[a-z%]/g, function(match) { 94 | if ('%%' === match) return; 95 | index++; 96 | if ('%c' === match) { 97 | // we only are interested in the *last* %c 98 | // (the user may have provided their own) 99 | lastC = index; 100 | } 101 | }); 102 | 103 | args.splice(lastC, 0, c); 104 | return args; 105 | } 106 | 107 | /** 108 | * Invokes `console.log()` when available. 109 | * No-op when `console.log` is not a "function". 110 | * 111 | * @api public 112 | */ 113 | 114 | function log() { 115 | // this hackery is required for IE8/9, where 116 | // the `console.log` function doesn't have 'apply' 117 | return 'object' === typeof console 118 | && console.log 119 | && Function.prototype.apply.call(console.log, console, arguments); 120 | } 121 | 122 | /** 123 | * Save `namespaces`. 124 | * 125 | * @param {String} namespaces 126 | * @api private 127 | */ 128 | 129 | function save(namespaces) { 130 | try { 131 | if (null == namespaces) { 132 | storage.removeItem('debug'); 133 | } else { 134 | storage.debug = namespaces; 135 | } 136 | } catch(e) {} 137 | } 138 | 139 | /** 140 | * Load `namespaces`. 141 | * 142 | * @return {String} returns the previously persisted debug modes 143 | * @api private 144 | */ 145 | 146 | function load() { 147 | var r; 148 | try { 149 | r = storage.debug; 150 | } catch(e) {} 151 | return r; 152 | } 153 | 154 | /** 155 | * Enable namespaces listed in `localStorage.debug` initially. 156 | */ 157 | 158 | exports.enable(load()); 159 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "debug", 3 | "repo": "visionmedia/debug", 4 | "description": "small debugging utility", 5 | "version": "2.1.1", 6 | "keywords": [ 7 | "debug", 8 | "log", 9 | "debugger" 10 | ], 11 | "main": "browser.js", 12 | "scripts": [ 13 | "browser.js", 14 | "debug.js" 15 | ], 16 | "dependencies": { 17 | "guille/ms.js": "0.6.1" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/debug.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * This is the common logic for both the Node.js and web browser 4 | * implementations of `debug()`. 5 | * 6 | * Expose `debug()` as the module. 7 | */ 8 | 9 | exports = module.exports = debug; 10 | exports.coerce = coerce; 11 | exports.disable = disable; 12 | exports.enable = enable; 13 | exports.enabled = enabled; 14 | exports.humanize = require('ms'); 15 | 16 | /** 17 | * The currently active debug mode names, and names to skip. 18 | */ 19 | 20 | exports.names = []; 21 | exports.skips = []; 22 | 23 | /** 24 | * Map of special "%n" handling functions, for the debug "format" argument. 25 | * 26 | * Valid key names are a single, lowercased letter, i.e. "n". 27 | */ 28 | 29 | exports.formatters = {}; 30 | 31 | /** 32 | * Previously assigned color. 33 | */ 34 | 35 | var prevColor = 0; 36 | 37 | /** 38 | * Previous log timestamp. 39 | */ 40 | 41 | var prevTime; 42 | 43 | /** 44 | * Select a color. 45 | * 46 | * @return {Number} 47 | * @api private 48 | */ 49 | 50 | function selectColor() { 51 | return exports.colors[prevColor++ % exports.colors.length]; 52 | } 53 | 54 | /** 55 | * Create a debugger with the given `namespace`. 56 | * 57 | * @param {String} namespace 58 | * @return {Function} 59 | * @api public 60 | */ 61 | 62 | function debug(namespace) { 63 | 64 | // define the `disabled` version 65 | function disabled() { 66 | } 67 | disabled.enabled = false; 68 | 69 | // define the `enabled` version 70 | function enabled() { 71 | 72 | var self = enabled; 73 | 74 | // set `diff` timestamp 75 | var curr = +new Date(); 76 | var ms = curr - (prevTime || curr); 77 | self.diff = ms; 78 | self.prev = prevTime; 79 | self.curr = curr; 80 | prevTime = curr; 81 | 82 | // add the `color` if not set 83 | if (null == self.useColors) self.useColors = exports.useColors(); 84 | if (null == self.color && self.useColors) self.color = selectColor(); 85 | 86 | var args = Array.prototype.slice.call(arguments); 87 | 88 | args[0] = exports.coerce(args[0]); 89 | 90 | if ('string' !== typeof args[0]) { 91 | // anything else let's inspect with %o 92 | args = ['%o'].concat(args); 93 | } 94 | 95 | // apply any `formatters` transformations 96 | var index = 0; 97 | args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { 98 | // if we encounter an escaped % then don't increase the array index 99 | if (match === '%%') return match; 100 | index++; 101 | var formatter = exports.formatters[format]; 102 | if ('function' === typeof formatter) { 103 | var val = args[index]; 104 | match = formatter.call(self, val); 105 | 106 | // now we need to remove `args[index]` since it's inlined in the `format` 107 | args.splice(index, 1); 108 | index--; 109 | } 110 | return match; 111 | }); 112 | 113 | if ('function' === typeof exports.formatArgs) { 114 | args = exports.formatArgs.apply(self, args); 115 | } 116 | var logFn = enabled.log || exports.log || console.log.bind(console); 117 | logFn.apply(self, args); 118 | } 119 | enabled.enabled = true; 120 | 121 | var fn = exports.enabled(namespace) ? enabled : disabled; 122 | 123 | fn.namespace = namespace; 124 | 125 | return fn; 126 | } 127 | 128 | /** 129 | * Enables a debug mode by namespaces. This can include modes 130 | * separated by a colon and wildcards. 131 | * 132 | * @param {String} namespaces 133 | * @api public 134 | */ 135 | 136 | function enable(namespaces) { 137 | exports.save(namespaces); 138 | 139 | var split = (namespaces || '').split(/[\s,]+/); 140 | var len = split.length; 141 | 142 | for (var i = 0; i < len; i++) { 143 | if (!split[i]) continue; // ignore empty strings 144 | namespaces = split[i].replace(/\*/g, '.*?'); 145 | if (namespaces[0] === '-') { 146 | exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); 147 | } else { 148 | exports.names.push(new RegExp('^' + namespaces + '$')); 149 | } 150 | } 151 | } 152 | 153 | /** 154 | * Disable debug output. 155 | * 156 | * @api public 157 | */ 158 | 159 | function disable() { 160 | exports.enable(''); 161 | } 162 | 163 | /** 164 | * Returns true if the given mode name is enabled, false otherwise. 165 | * 166 | * @param {String} name 167 | * @return {Boolean} 168 | * @api public 169 | */ 170 | 171 | function enabled(name) { 172 | var i, len; 173 | for (i = 0, len = exports.skips.length; i < len; i++) { 174 | if (exports.skips[i].test(name)) { 175 | return false; 176 | } 177 | } 178 | for (i = 0, len = exports.names.length; i < len; i++) { 179 | if (exports.names[i].test(name)) { 180 | return true; 181 | } 182 | } 183 | return false; 184 | } 185 | 186 | /** 187 | * Coerce `val`. 188 | * 189 | * @param {Mixed} val 190 | * @return {Mixed} 191 | * @api private 192 | */ 193 | 194 | function coerce(val) { 195 | if (val instanceof Error) return val.stack || val.message; 196 | return val; 197 | } 198 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/node.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Module dependencies. 4 | */ 5 | 6 | var tty = require('tty'); 7 | var util = require('util'); 8 | 9 | /** 10 | * This is the Node.js implementation of `debug()`. 11 | * 12 | * Expose `debug()` as the module. 13 | */ 14 | 15 | exports = module.exports = require('./debug'); 16 | exports.log = log; 17 | exports.formatArgs = formatArgs; 18 | exports.save = save; 19 | exports.load = load; 20 | exports.useColors = useColors; 21 | 22 | /** 23 | * Colors. 24 | */ 25 | 26 | exports.colors = [6, 2, 3, 4, 5, 1]; 27 | 28 | /** 29 | * The file descriptor to write the `debug()` calls to. 30 | * Set the `DEBUG_FD` env variable to override with another value. i.e.: 31 | * 32 | * $ DEBUG_FD=3 node script.js 3>debug.log 33 | */ 34 | 35 | var fd = parseInt(process.env.DEBUG_FD, 10) || 2; 36 | var stream = 1 === fd ? process.stdout : 37 | 2 === fd ? process.stderr : 38 | createWritableStdioStream(fd); 39 | 40 | /** 41 | * Is stdout a TTY? Colored output is enabled when `true`. 42 | */ 43 | 44 | function useColors() { 45 | var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); 46 | if (0 === debugColors.length) { 47 | return tty.isatty(fd); 48 | } else { 49 | return '0' !== debugColors 50 | && 'no' !== debugColors 51 | && 'false' !== debugColors 52 | && 'disabled' !== debugColors; 53 | } 54 | } 55 | 56 | /** 57 | * Map %o to `util.inspect()`, since Node doesn't do that out of the box. 58 | */ 59 | 60 | var inspect = (4 === util.inspect.length ? 61 | // node <= 0.8.x 62 | function (v, colors) { 63 | return util.inspect(v, void 0, void 0, colors); 64 | } : 65 | // node > 0.8.x 66 | function (v, colors) { 67 | return util.inspect(v, { colors: colors }); 68 | } 69 | ); 70 | 71 | exports.formatters.o = function(v) { 72 | return inspect(v, this.useColors) 73 | .replace(/\s*\n\s*/g, ' '); 74 | }; 75 | 76 | /** 77 | * Adds ANSI color escape codes if enabled. 78 | * 79 | * @api public 80 | */ 81 | 82 | function formatArgs() { 83 | var args = arguments; 84 | var useColors = this.useColors; 85 | var name = this.namespace; 86 | 87 | if (useColors) { 88 | var c = this.color; 89 | 90 | args[0] = ' \u001b[9' + c + 'm' + name + ' ' 91 | + '\u001b[0m' 92 | + args[0] + '\u001b[3' + c + 'm' 93 | + ' +' + exports.humanize(this.diff) + '\u001b[0m'; 94 | } else { 95 | args[0] = new Date().toUTCString() 96 | + ' ' + name + ' ' + args[0]; 97 | } 98 | return args; 99 | } 100 | 101 | /** 102 | * Invokes `console.error()` with the specified arguments. 103 | */ 104 | 105 | function log() { 106 | return stream.write(util.format.apply(this, arguments) + '\n'); 107 | } 108 | 109 | /** 110 | * Save `namespaces`. 111 | * 112 | * @param {String} namespaces 113 | * @api private 114 | */ 115 | 116 | function save(namespaces) { 117 | if (null == namespaces) { 118 | // If you set a process.env field to null or undefined, it gets cast to the 119 | // string 'null' or 'undefined'. Just delete instead. 120 | delete process.env.DEBUG; 121 | } else { 122 | process.env.DEBUG = namespaces; 123 | } 124 | } 125 | 126 | /** 127 | * Load `namespaces`. 128 | * 129 | * @return {String} returns the previously persisted debug modes 130 | * @api private 131 | */ 132 | 133 | function load() { 134 | return process.env.DEBUG; 135 | } 136 | 137 | /** 138 | * Copied from `node/src/node.js`. 139 | * 140 | * XXX: It's lame that node doesn't expose this API out-of-the-box. It also 141 | * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. 142 | */ 143 | 144 | function createWritableStdioStream (fd) { 145 | var stream; 146 | var tty_wrap = process.binding('tty_wrap'); 147 | 148 | // Note stream._type is used for test-module-load-list.js 149 | 150 | switch (tty_wrap.guessHandleType(fd)) { 151 | case 'TTY': 152 | stream = new tty.WriteStream(fd); 153 | stream._type = 'tty'; 154 | 155 | // Hack to have stream not keep the event loop alive. 156 | // See https://github.com/joyent/node/issues/1726 157 | if (stream._handle && stream._handle.unref) { 158 | stream._handle.unref(); 159 | } 160 | break; 161 | 162 | case 'FILE': 163 | var fs = require('fs'); 164 | stream = new fs.SyncWriteStream(fd, { autoClose: false }); 165 | stream._type = 'fs'; 166 | break; 167 | 168 | case 'PIPE': 169 | case 'TCP': 170 | var net = require('net'); 171 | stream = new net.Socket({ 172 | fd: fd, 173 | readable: false, 174 | writable: true 175 | }); 176 | 177 | // FIXME Should probably have an option in net.Socket to create a 178 | // stream from an existing fd which is writable only. But for now 179 | // we'll just add this hack and set the `readable` member to false. 180 | // Test: ./node test/fixtures/echo.js < /etc/passwd 181 | stream.readable = false; 182 | stream.read = null; 183 | stream._type = 'pipe'; 184 | 185 | // FIXME Hack to have stream not keep the event loop alive. 186 | // See https://github.com/joyent/node/issues/1726 187 | if (stream._handle && stream._handle.unref) { 188 | stream._handle.unref(); 189 | } 190 | break; 191 | 192 | default: 193 | // Probably an error on in uv_guess_handle() 194 | throw new Error('Implement me. Unknown stream file type!'); 195 | } 196 | 197 | // For supporting legacy API we put the FD here. 198 | stream.fd = fd; 199 | 200 | stream._isStdio = true; 201 | 202 | return stream; 203 | } 204 | 205 | /** 206 | * Enable namespaces listed in `process.env.DEBUG` initially. 207 | */ 208 | 209 | exports.enable(load()); 210 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/node_modules/ms/.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | test 3 | History.md 4 | Makefile 5 | component.json 6 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/node_modules/ms/README.md: -------------------------------------------------------------------------------- 1 | # ms.js: miliseconds conversion utility 2 | 3 | ```js 4 | ms('1d') // 86400000 5 | ms('10h') // 36000000 6 | ms('2h') // 7200000 7 | ms('1m') // 60000 8 | ms('5s') // 5000 9 | ms('100') // 100 10 | ``` 11 | 12 | ```js 13 | ms(60000) // "1m" 14 | ms(2 * 60000) // "2m" 15 | ms(ms('10 hours')) // "10h" 16 | ``` 17 | 18 | ```js 19 | ms(60000, { long: true }) // "1 minute" 20 | ms(2 * 60000, { long: true }) // "2 minutes" 21 | ms(ms('10 hours', { long: true })) // "10 hours" 22 | ``` 23 | 24 | - Node/Browser compatible. Published as `ms` in NPM. 25 | - If a number is supplied to `ms`, a string with a unit is returned. 26 | - If a string that contains the number is supplied, it returns it as 27 | a number (e.g: it returns `100` for `'100'`). 28 | - If you pass a string with a number and a valid unit, the number of 29 | equivalent ms is returned. 30 | 31 | ## License 32 | 33 | MIT -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/node_modules/ms/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Helpers. 3 | */ 4 | 5 | var s = 1000; 6 | var m = s * 60; 7 | var h = m * 60; 8 | var d = h * 24; 9 | var y = d * 365.25; 10 | 11 | /** 12 | * Parse or format the given `val`. 13 | * 14 | * Options: 15 | * 16 | * - `long` verbose formatting [false] 17 | * 18 | * @param {String|Number} val 19 | * @param {Object} options 20 | * @return {String|Number} 21 | * @api public 22 | */ 23 | 24 | module.exports = function(val, options){ 25 | options = options || {}; 26 | if ('string' == typeof val) return parse(val); 27 | return options.long 28 | ? long(val) 29 | : short(val); 30 | }; 31 | 32 | /** 33 | * Parse the given `str` and return milliseconds. 34 | * 35 | * @param {String} str 36 | * @return {Number} 37 | * @api private 38 | */ 39 | 40 | function parse(str) { 41 | var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); 42 | if (!match) return; 43 | var n = parseFloat(match[1]); 44 | var type = (match[2] || 'ms').toLowerCase(); 45 | switch (type) { 46 | case 'years': 47 | case 'year': 48 | case 'y': 49 | return n * y; 50 | case 'days': 51 | case 'day': 52 | case 'd': 53 | return n * d; 54 | case 'hours': 55 | case 'hour': 56 | case 'h': 57 | return n * h; 58 | case 'minutes': 59 | case 'minute': 60 | case 'm': 61 | return n * m; 62 | case 'seconds': 63 | case 'second': 64 | case 's': 65 | return n * s; 66 | case 'ms': 67 | return n; 68 | } 69 | } 70 | 71 | /** 72 | * Short format for `ms`. 73 | * 74 | * @param {Number} ms 75 | * @return {String} 76 | * @api private 77 | */ 78 | 79 | function short(ms) { 80 | if (ms >= d) return Math.round(ms / d) + 'd'; 81 | if (ms >= h) return Math.round(ms / h) + 'h'; 82 | if (ms >= m) return Math.round(ms / m) + 'm'; 83 | if (ms >= s) return Math.round(ms / s) + 's'; 84 | return ms + 'ms'; 85 | } 86 | 87 | /** 88 | * Long format for `ms`. 89 | * 90 | * @param {Number} ms 91 | * @return {String} 92 | * @api private 93 | */ 94 | 95 | function long(ms) { 96 | return plural(ms, d, 'day') 97 | || plural(ms, h, 'hour') 98 | || plural(ms, m, 'minute') 99 | || plural(ms, s, 'second') 100 | || ms + ' ms'; 101 | } 102 | 103 | /** 104 | * Pluralization helper. 105 | */ 106 | 107 | function plural(ms, n, name) { 108 | if (ms < n) return; 109 | if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; 110 | return Math.ceil(ms / n) + ' ' + name + 's'; 111 | } 112 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/node_modules/ms/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ms", 3 | "version": "0.6.2", 4 | "description": "Tiny ms conversion utility", 5 | "repository": { 6 | "type": "git", 7 | "url": "git://github.com/guille/ms.js.git" 8 | }, 9 | "main": "./index", 10 | "devDependencies": { 11 | "mocha": "*", 12 | "expect.js": "*", 13 | "serve": "*" 14 | }, 15 | "component": { 16 | "scripts": { 17 | "ms/index.js": "index.js" 18 | } 19 | }, 20 | "readme": "# ms.js: miliseconds conversion utility\n\n```js\nms('1d') // 86400000\nms('10h') // 36000000\nms('2h') // 7200000\nms('1m') // 60000\nms('5s') // 5000\nms('100') // 100\n```\n\n```js\nms(60000) // \"1m\"\nms(2 * 60000) // \"2m\"\nms(ms('10 hours')) // \"10h\"\n```\n\n```js\nms(60000, { long: true }) // \"1 minute\"\nms(2 * 60000, { long: true }) // \"2 minutes\"\nms(ms('10 hours', { long: true })) // \"10 hours\"\n```\n\n- Node/Browser compatible. Published as `ms` in NPM.\n- If a number is supplied to `ms`, a string with a unit is returned.\n- If a string that contains the number is supplied, it returns it as\na number (e.g: it returns `100` for `'100'`).\n- If you pass a string with a number and a valid unit, the number of\nequivalent ms is returned.\n\n## License\n\nMIT", 21 | "readmeFilename": "README.md", 22 | "bugs": { 23 | "url": "https://github.com/guille/ms.js/issues" 24 | }, 25 | "_id": "ms@0.6.2", 26 | "dist": { 27 | "shasum": "7140294140402e01eb8729a7019188c3ac5d0142" 28 | }, 29 | "_from": "ms@0.6.2", 30 | "_resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz" 31 | } 32 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/debug/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "debug", 3 | "version": "2.1.1", 4 | "repository": { 5 | "type": "git", 6 | "url": "git://github.com/visionmedia/debug.git" 7 | }, 8 | "description": "small debugging utility", 9 | "keywords": [ 10 | "debug", 11 | "log", 12 | "debugger" 13 | ], 14 | "author": { 15 | "name": "TJ Holowaychuk", 16 | "email": "tj@vision-media.ca" 17 | }, 18 | "contributors": [ 19 | { 20 | "name": "Nathan Rajlich", 21 | "email": "nathan@tootallnate.net", 22 | "url": "http://n8.io" 23 | } 24 | ], 25 | "license": "MIT", 26 | "dependencies": { 27 | "ms": "0.6.2" 28 | }, 29 | "devDependencies": { 30 | "browserify": "6.1.0", 31 | "mocha": "*" 32 | }, 33 | "main": "./node.js", 34 | "browser": "./browser.js", 35 | "component": { 36 | "scripts": { 37 | "debug/index.js": "browser.js", 38 | "debug/debug.js": "debug.js" 39 | } 40 | }, 41 | "readme": "# debug\n\n tiny node.js debugging utility modelled after node core's debugging technique.\n\n## Installation\n\n```bash\n$ npm install debug\n```\n\n## Usage\n\n With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n\nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n#### Windows note\n\n On Windows the environment variable is set using the `set` command. \n \n ```cmd\n set DEBUG=*,-not_this\n ```\n\nThen, run the program to be debugged as ususal.\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n\n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\".\n\n## Wildcards\n\n The `*` character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.\n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n b('doing some work');\n}, 1200);\n```\n\n#### Web Inspector Colors\n\n Colors are also enabled on \"Web Inspectors\" that understand the `%c` formatting\n option. These are WebKit web inspectors, Firefox ([since version\n 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))\n and the Firebug plugin for Firefox (any version).\n\n Colored output looks something like:\n\n ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png)\n\n### stderr vs stdout\n\nYou can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally:\n\nExample _stderr.js_:\n\n```js\nvar debug = require('../');\nvar log = debug('app:log');\n\n// by default console.log is used\nlog('goes to stdout!');\n\nvar error = debug('app:error');\n// set this namespace to log via console.error\nerror.log = console.error.bind(console); // don't forget to bind to console!\nerror('goes to stderr');\nlog('still goes to stdout!');\n\n// set all output to go via console.warn\n// overrides all per-namespace log settings\ndebug.log = console.warn.bind(console);\nlog('now goes to stderr via console.warn');\nerror('still goes to stderr, but via console.warn now');\n```\n\n## Authors\n\n - TJ Holowaychuk\n - Nathan Rajlich\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", 42 | "readmeFilename": "Readme.md", 43 | "bugs": { 44 | "url": "https://github.com/visionmedia/debug/issues" 45 | }, 46 | "_id": "debug@2.1.1", 47 | "dist": { 48 | "shasum": "23c9bdcc1e8f7e0e6ad6a782a79f469faba86965" 49 | }, 50 | "_from": "debug@~2.1.0", 51 | "_resolved": "https://registry.npmjs.org/debug/-/debug-2.1.1.tgz" 52 | } 53 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/nan/.dntrc: -------------------------------------------------------------------------------- 1 | ## DNT config file 2 | ## see https://github.com/rvagg/dnt 3 | 4 | NODE_VERSIONS="\ 5 | master \ 6 | v0.11.13 \ 7 | v0.11.10 \ 8 | v0.11.9 \ 9 | v0.11.8 \ 10 | v0.11.7 \ 11 | v0.11.6 \ 12 | v0.11.5 \ 13 | v0.11.4 \ 14 | v0.10.26 \ 15 | v0.10.25 \ 16 | v0.10.24 \ 17 | v0.10.23 \ 18 | v0.10.22 \ 19 | v0.10.21 \ 20 | v0.10.20 \ 21 | v0.10.19 \ 22 | v0.10.18 \ 23 | v0.8.26 \ 24 | v0.8.25 \ 25 | v0.8.24 \ 26 | v0.8.23 \ 27 | v0.8.22 \ 28 | " 29 | OUTPUT_PREFIX="nan-" 30 | TEST_CMD="\ 31 | cd /dnt/test/ && \ 32 | npm install && \ 33 | node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild && \ 34 | node_modules/.bin/tap --gc js/*-test.js; \ 35 | " 36 | 37 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/nan/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2013, NAN contributors: 2 | - Rod Vagg 3 | - Benjamin Byholm 4 | - Trevor Norris 5 | - Nathan Rajlich 6 | - Brett Lawson 7 | - Ben Noordhuis 8 | (the "Original Author") 9 | All rights reserved. 10 | 11 | MIT +no-false-attribs License 12 | 13 | Permission is hereby granted, free of charge, to any person 14 | obtaining a copy of this software and associated documentation 15 | files (the "Software"), to deal in the Software without 16 | restriction, including without limitation the rights to use, 17 | copy, modify, merge, publish, distribute, sublicense, and/or sell 18 | copies of the Software, and to permit persons to whom the 19 | Software is furnished to do so, subject to the following 20 | conditions: 21 | 22 | The above copyright notice and this permission notice shall be 23 | included in all copies or substantial portions of the Software. 24 | 25 | Distributions of all or part of the Software intended to be used 26 | by the recipients as they would use the unmodified Software, 27 | containing modifications that substantially alter, remove, or 28 | disable functionality of the Software, outside of the documented 29 | configuration mechanisms provided by the Software, shall be 30 | modified such that the Original Author's bug reporting email 31 | addresses and urls are either replaced with the contact information 32 | of the parties responsible for the changes, or removed entirely. 33 | 34 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 35 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 36 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 37 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 38 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 39 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 40 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 41 | OTHER DEALINGS IN THE SOFTWARE. 42 | 43 | 44 | Except where noted, this license applies to any and all software 45 | programs and associated documentation files created by the 46 | Original Author, when distributed with the Software. 47 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/nan/build/config.gypi: -------------------------------------------------------------------------------- 1 | # Do not edit. File was generated by node-gyp's "configure" step 2 | { 3 | "target_defaults": { 4 | "cflags": [], 5 | "default_configuration": "Release", 6 | "defines": [], 7 | "include_dirs": [], 8 | "libraries": [] 9 | }, 10 | "variables": { 11 | "clang": 0, 12 | "gcc_version": 47, 13 | "host_arch": "x64", 14 | "node_install_npm": "true", 15 | "node_prefix": "", 16 | "node_shared_cares": "false", 17 | "node_shared_http_parser": "false", 18 | "node_shared_libuv": "false", 19 | "node_shared_openssl": "false", 20 | "node_shared_v8": "false", 21 | "node_shared_zlib": "false", 22 | "node_tag": "", 23 | "node_unsafe_optimizations": 0, 24 | "node_use_dtrace": "false", 25 | "node_use_etw": "false", 26 | "node_use_openssl": "true", 27 | "node_use_perfctr": "false", 28 | "node_use_systemtap": "false", 29 | "python": "/usr/bin/python", 30 | "target_arch": "x64", 31 | "v8_enable_gdbjit": 0, 32 | "v8_no_strict_aliasing": 1, 33 | "v8_use_snapshot": "true", 34 | "nodedir": "/home/rvagg/.node-gyp/0.10.21", 35 | "copy_dev_lib": "true", 36 | "standalone_static_library": 1 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/nan/include_dirs.js: -------------------------------------------------------------------------------- 1 | console.log(require('path').relative('.', __dirname)); 2 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '0.10' 4 | env: 5 | global: 6 | - secure: i51rE9rZGHbcZWlL58j3H1qtL23OIV2r0X4TcQKNI3pw2mubdHFJmfPNNO19ItfReu8wwQMxOehKamwaNvqMiKWyHfn/QcThFQysqzgGZ6AgnUbYx9od6XFNDeWd1sVBf7QBAL07y7KWlYGWCwFwWjabSVySzQhEBdisPcskfkI= 7 | - secure: BKq6/5z9LK3KDkTjs7BGeBZ1KsWgz+MsAXZ4P64NSeVGFaBdXU45+ww1mwxXFt5l22/mhyOQZfebQl+kGVqRSZ+DEgQeCymkNZ6CD8c6w6cLuOJXiXwuu/cDM2DD0tfGeu2YZC7yEikP7BqEFwH3D324rRzSGLF2RSAAwkOI7bE= 8 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/.zuul.yml: -------------------------------------------------------------------------------- 1 | ui: tape 2 | browsers: 3 | - name: chrome 4 | version: 26..latest 5 | - name: firefox 6 | version: 21..latest 7 | - name: safari 8 | version: 5..latest 9 | - name: ie 10 | version: 6..latest 11 | - name: opera 12 | version: 12..latest 13 | - name: iphone 14 | version: 5.0..latest 15 | - name: ipad 16 | version: 5.0..latest 17 | - name: android 18 | version: 4.0..latest 19 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Feross Aboukhadijeh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/README.md: -------------------------------------------------------------------------------- 1 | # typedarray-to-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url] 2 | 3 | #### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy. 4 | 5 | [![saucelabs][saucelabs-image]][saucelabs-url] 6 | 7 | [travis-image]: https://img.shields.io/travis/feross/typedarray-to-buffer.svg?style=flat 8 | [travis-url]: https://travis-ci.org/feross/typedarray-to-buffer 9 | [npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg?style=flat 10 | [npm-url]: https://npmjs.org/package/typedarray-to-buffer 11 | [downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg?style=flat 12 | [saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg 13 | [saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer 14 | 15 | Say you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or 16 | [browserify](http://browserify.org/) and you're working with lots of binary data. 17 | 18 | Unfortunately, sometimes the browser or someone else's API gives you an `ArrayBuffer` 19 | or a typed array like `Uint8Array` to work with and you need to convert it to a 20 | `Buffer`. What do you do? 21 | 22 | Of course: `new Buffer(uint8array)` 23 | 24 | But, alas, every time you do `new Buffer(uint8array)` **the entire array gets copied**. 25 | The `Buffer` constructor does a copy; this is 26 | defined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module 27 | matches the node API exactly. 28 | 29 | So, how can we avoid this expensive copy in 30 | [performance critical applications](https://github.com/feross/buffer/issues/22)? 31 | 32 | ***Simply use this module, of course!*** 33 | 34 | ## install 35 | 36 | ```bash 37 | npm install typedarray-to-buffer 38 | ``` 39 | 40 | ## usage 41 | 42 | To convert a typed array to a `Buffer` **without a copy**, do this: 43 | 44 | ```js 45 | var toBuffer = require('typedarray-to-buffer') 46 | 47 | var arr = new Uint8Array([1, 2, 3]) 48 | arr = toBuffer(arr) 49 | 50 | // arr is a buffer now! 51 | 52 | arr.toString() // '\u0001\u0002\u0003' 53 | arr.readUInt16BE(0) // 258 54 | ``` 55 | 56 | ## how it works 57 | 58 | If the browser supports typed arrays, then `toBuffer` will **augment the typed array** you 59 | pass in with the `Buffer` methods and return it. See [how does Buffer 60 | work?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation 61 | works. 62 | 63 | This module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This 64 | respects the "view" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other 65 | words, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will 66 | contain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't 67 | require a copy. 68 | 69 | If the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer` 70 | object, copy the data into it, and return it. There's no simple performance optimization 71 | we can do for old browsers. Oh well. 72 | 73 | If this module is used in node, then it will just call `new Buffer`. This is just for 74 | the convenience of modules that work in both node and the browser. 75 | 76 | ## license 77 | 78 | MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). 79 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Convert a typed array to a Buffer without a copy 3 | * 4 | * Author: Feross Aboukhadijeh 5 | * License: MIT 6 | * 7 | * `npm install typedarray-to-buffer` 8 | */ 9 | 10 | var isTypedArray = require('is-typedarray').strict 11 | 12 | module.exports = function (arr) { 13 | // If `Buffer` is the browser `buffer` module, and the browser supports typed arrays, 14 | // then avoid a copy. Otherwise, create a `Buffer` with a copy. 15 | var constructor = Buffer.TYPED_ARRAY_SUPPORT 16 | ? Buffer._augment 17 | : function (arr) { return new Buffer(arr) } 18 | 19 | if (arr instanceof Uint8Array) { 20 | return constructor(arr) 21 | } else if (arr instanceof ArrayBuffer) { 22 | return constructor(new Uint8Array(arr)) 23 | } else if (isTypedArray(arr)) { 24 | // Use the typed array's underlying ArrayBuffer to back new Buffer. This respects 25 | // the "view" on the ArrayBuffer, i.e. byteOffset and byteLength. No copy. 26 | return constructor(new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength)) 27 | } else { 28 | // Unsupported type, just pass it through to the `Buffer` constructor. 29 | return new Buffer(arr) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/node_modules/is-typedarray/LICENSE.md: -------------------------------------------------------------------------------- 1 | This software is released under the MIT license: 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so, 8 | subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 15 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 16 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 17 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 18 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/node_modules/is-typedarray/README.md: -------------------------------------------------------------------------------- 1 | # is-typedarray [![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) 2 | 3 | Detect whether or not an object is a 4 | [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). 5 | 6 | ## Usage 7 | 8 | [![NPM](https://nodei.co/npm/is-typedarray.png)](https://nodei.co/npm/is-typedarray/) 9 | 10 | ### isTypedArray(array) 11 | 12 | Returns `true` when array is a Typed Array, and `false` when it is not. 13 | 14 | ## License 15 | 16 | MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details. 17 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/node_modules/is-typedarray/index.js: -------------------------------------------------------------------------------- 1 | module.exports = isTypedArray 2 | isTypedArray.strict = isStrictTypedArray 3 | isTypedArray.loose = isLooseTypedArray 4 | 5 | var toString = Object.prototype.toString 6 | var names = { 7 | '[object Int8Array]': true 8 | , '[object Int16Array]': true 9 | , '[object Int32Array]': true 10 | , '[object Uint8Array]': true 11 | , '[object Uint16Array]': true 12 | , '[object Uint32Array]': true 13 | , '[object Float32Array]': true 14 | , '[object Float64Array]': true 15 | } 16 | 17 | function isTypedArray(arr) { 18 | return ( 19 | isStrictTypedArray(arr) 20 | || isLooseTypedArray(arr) 21 | ) 22 | } 23 | 24 | function isStrictTypedArray(arr) { 25 | return ( 26 | arr instanceof Int8Array 27 | || arr instanceof Int16Array 28 | || arr instanceof Int32Array 29 | || arr instanceof Uint8Array 30 | || arr instanceof Uint16Array 31 | || arr instanceof Uint32Array 32 | || arr instanceof Float32Array 33 | || arr instanceof Float64Array 34 | ) 35 | } 36 | 37 | function isLooseTypedArray(arr) { 38 | return names[toString.call(arr)] 39 | } 40 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/node_modules/is-typedarray/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "is-typedarray", 3 | "version": "0.0.0", 4 | "description": "Detect whether or not an object is a Typed Array", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node test" 8 | }, 9 | "author": { 10 | "name": "Hugh Kennedy", 11 | "email": "hughskennedy@gmail.com", 12 | "url": "http://hughsk.io/" 13 | }, 14 | "license": "MIT", 15 | "dependencies": {}, 16 | "devDependencies": { 17 | "tape": "^2.13.1" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git://github.com/hughsk/is-typedarray.git" 22 | }, 23 | "keywords": [ 24 | "typed", 25 | "array", 26 | "detect", 27 | "is", 28 | "util" 29 | ], 30 | "bugs": { 31 | "url": "https://github.com/hughsk/is-typedarray/issues" 32 | }, 33 | "homepage": "https://github.com/hughsk/is-typedarray", 34 | "readme": "# is-typedarray [![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges)\n\nDetect whether or not an object is a\n[Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays).\n\n## Usage\n\n[![NPM](https://nodei.co/npm/is-typedarray.png)](https://nodei.co/npm/is-typedarray/)\n\n### isTypedArray(array)\n\nReturns `true` when array is a Typed Array, and `false` when it is not.\n\n## License\n\nMIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details.\n", 35 | "readmeFilename": "README.md", 36 | "_id": "is-typedarray@0.0.0", 37 | "dist": { 38 | "shasum": "4a3a67aa6173800cdb0e4fad779ad20bd828c9d9" 39 | }, 40 | "_from": "is-typedarray@0.0.0", 41 | "_resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-0.0.0.tgz" 42 | } 43 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/node_modules/is-typedarray/test.js: -------------------------------------------------------------------------------- 1 | var test = require('tape') 2 | var ista = require('./') 3 | 4 | test('strict', function(t) { 5 | t.ok(ista.strict(new Int8Array), 'Int8Array') 6 | t.ok(ista.strict(new Int16Array), 'Int16Array') 7 | t.ok(ista.strict(new Int32Array), 'Int32Array') 8 | t.ok(ista.strict(new Uint8Array), 'Uint8Array') 9 | t.ok(ista.strict(new Uint16Array), 'Uint16Array') 10 | t.ok(ista.strict(new Uint32Array), 'Uint32Array') 11 | t.ok(ista.strict(new Float32Array), 'Float32Array') 12 | t.ok(ista.strict(new Float64Array), 'Float64Array') 13 | 14 | t.ok(!ista.strict(new Array), 'Array') 15 | t.ok(!ista.strict([]), '[]') 16 | 17 | t.end() 18 | }) 19 | 20 | test('loose', function(t) { 21 | t.ok(ista.loose(new Int8Array), 'Int8Array') 22 | t.ok(ista.loose(new Int16Array), 'Int16Array') 23 | t.ok(ista.loose(new Int32Array), 'Int32Array') 24 | t.ok(ista.loose(new Uint8Array), 'Uint8Array') 25 | t.ok(ista.loose(new Uint16Array), 'Uint16Array') 26 | t.ok(ista.loose(new Uint32Array), 'Uint32Array') 27 | t.ok(ista.loose(new Float32Array), 'Float32Array') 28 | t.ok(ista.loose(new Float64Array), 'Float64Array') 29 | 30 | t.ok(!ista.loose(new Array), 'Array') 31 | t.ok(!ista.loose([]), '[]') 32 | 33 | t.end() 34 | }) 35 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typedarray-to-buffer", 3 | "description": "Convert a typed array to a Buffer without a copy", 4 | "version": "3.0.1", 5 | "author": { 6 | "name": "Feross Aboukhadijeh", 7 | "email": "feross@feross.org", 8 | "url": "http://feross.org/" 9 | }, 10 | "bugs": { 11 | "url": "https://github.com/feross/typedarray-to-buffer/issues" 12 | }, 13 | "dependencies": { 14 | "is-typedarray": "0.0.0" 15 | }, 16 | "devDependencies": { 17 | "tape": "2.x", 18 | "zuul": "^1.13.0" 19 | }, 20 | "homepage": "http://feross.org", 21 | "keywords": [ 22 | "buffer", 23 | "typed array", 24 | "convert", 25 | "no copy", 26 | "uint8array", 27 | "uint16array", 28 | "uint32array", 29 | "int16array", 30 | "int32array", 31 | "float32array", 32 | "float64array", 33 | "browser", 34 | "arraybuffer", 35 | "dataview" 36 | ], 37 | "license": "MIT", 38 | "main": "index.js", 39 | "repository": { 40 | "type": "git", 41 | "url": "git://github.com/feross/typedarray-to-buffer.git" 42 | }, 43 | "scripts": { 44 | "test": "npm run test-node && npm run test-browser", 45 | "test-browser": "zuul -- test/*.js", 46 | "test-browser-local": "zuul --local -- test/*.js", 47 | "test-node": "tape test/*.js" 48 | }, 49 | "testling": { 50 | "files": "test/*.js" 51 | }, 52 | "readme": "# typedarray-to-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url]\n\n#### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy.\n\n[![saucelabs][saucelabs-image]][saucelabs-url]\n\n[travis-image]: https://img.shields.io/travis/feross/typedarray-to-buffer.svg?style=flat\n[travis-url]: https://travis-ci.org/feross/typedarray-to-buffer\n[npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg?style=flat\n[npm-url]: https://npmjs.org/package/typedarray-to-buffer\n[downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg?style=flat\n[saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg\n[saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer\n\nSay you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or\n[browserify](http://browserify.org/) and you're working with lots of binary data.\n\nUnfortunately, sometimes the browser or someone else's API gives you an `ArrayBuffer`\nor a typed array like `Uint8Array` to work with and you need to convert it to a\n`Buffer`. What do you do?\n\nOf course: `new Buffer(uint8array)`\n\nBut, alas, every time you do `new Buffer(uint8array)` **the entire array gets copied**.\nThe `Buffer` constructor does a copy; this is\ndefined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module\nmatches the node API exactly.\n\nSo, how can we avoid this expensive copy in\n[performance critical applications](https://github.com/feross/buffer/issues/22)?\n\n***Simply use this module, of course!***\n\n## install\n\n```bash\nnpm install typedarray-to-buffer\n```\n\n## usage\n\nTo convert a typed array to a `Buffer` **without a copy**, do this:\n\n```js\nvar toBuffer = require('typedarray-to-buffer')\n\nvar arr = new Uint8Array([1, 2, 3])\narr = toBuffer(arr)\n\n// arr is a buffer now!\n\narr.toString() // '\\u0001\\u0002\\u0003'\narr.readUInt16BE(0) // 258\n```\n\n## how it works\n\nIf the browser supports typed arrays, then `toBuffer` will **augment the typed array** you\npass in with the `Buffer` methods and return it. See [how does Buffer\nwork?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation\nworks.\n\nThis module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This\nrespects the \"view\" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other\nwords, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will\ncontain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't\nrequire a copy.\n\nIf the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer`\nobject, copy the data into it, and return it. There's no simple performance optimization\nwe can do for old browsers. Oh well.\n\nIf this module is used in node, then it will just call `new Buffer`. This is just for\nthe convenience of modules that work in both node and the browser.\n\n## license\n\nMIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org).\n", 53 | "readmeFilename": "README.md", 54 | "_id": "typedarray-to-buffer@3.0.1", 55 | "dist": { 56 | "shasum": "27dc25d992a691fc937fb4a88b5ff1c2338c0ffd" 57 | }, 58 | "_from": "typedarray-to-buffer@~3.0.0", 59 | "_resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.0.1.tgz" 60 | } 61 | -------------------------------------------------------------------------------- /node_modules/websocket/node_modules/typedarray-to-buffer/test/basic.js: -------------------------------------------------------------------------------- 1 | var test = require('tape') 2 | var toBuffer = require('../') 3 | 4 | test('convert to buffer from Uint8Array', function (t) { 5 | if (typeof Uint8Array !== 'undefined') { 6 | var arr = new Uint8Array([1, 2, 3]) 7 | arr = toBuffer(arr) 8 | 9 | t.deepEqual(arr, new Buffer([1, 2, 3]), 'contents equal') 10 | t.ok(Buffer.isBuffer(arr), 'is buffer') 11 | t.equal(arr.readUInt8(0), 1) 12 | t.equal(arr.readUInt8(1), 2) 13 | t.equal(arr.readUInt8(2), 3) 14 | } else { 15 | t.pass('browser lacks Uint8Array support, skip test') 16 | } 17 | t.end() 18 | }) 19 | 20 | test('convert to buffer from another arrayview type (Uint32Array)', function (t) { 21 | if (typeof Uint32Array !== 'undefined') { 22 | var arr = new Uint32Array([1, 2, 3]) 23 | arr = toBuffer(arr) 24 | 25 | t.deepEqual(arr, new Buffer([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]), 'contents equal') 26 | t.ok(Buffer.isBuffer(arr), 'is buffer') 27 | t.equal(arr.readUInt32LE(0), 1) 28 | t.equal(arr.readUInt32LE(4), 2) 29 | t.equal(arr.readUInt32LE(8), 3) 30 | t.equal(arr instanceof Uint8Array, !!Buffer.TYPED_ARRAY_SUPPORT) 31 | 32 | } else { 33 | t.pass('browser lacks Uint32Array support, skip test') 34 | } 35 | t.end() 36 | }) 37 | 38 | test('convert to buffer from ArrayBuffer', function (t) { 39 | if (typeof Uint32Array !== 'undefined') { 40 | var arr = new Uint32Array([1, 2, 3]).subarray(1, 2) 41 | arr = toBuffer(arr) 42 | 43 | t.deepEqual(arr, new Buffer([2, 0, 0, 0]), 'contents equal') 44 | t.ok(Buffer.isBuffer(arr), 'is buffer') 45 | t.equal(arr.readUInt32LE(0), 2) 46 | t.equal(arr instanceof Uint8Array, !!Buffer.TYPED_ARRAY_SUPPORT) 47 | 48 | } else { 49 | t.pass('browser lacks ArrayBuffer support, skip test') 50 | } 51 | t.end() 52 | }) 53 | -------------------------------------------------------------------------------- /node_modules/websocket/src/bufferutil.cc: -------------------------------------------------------------------------------- 1 | /*! 2 | * BufferUtil originally from: 3 | * ws: a node.js websocket client 4 | * Copyright(c) 2011 Einar Otto Stangvik 5 | * MIT Licensed 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "nan.h" 17 | 18 | using namespace v8; 19 | using namespace node; 20 | 21 | class BufferUtil : public ObjectWrap 22 | { 23 | public: 24 | 25 | static void Initialize(v8::Handle target) 26 | { 27 | NanScope(); 28 | Local t = NanNew(New); 29 | t->InstanceTemplate()->SetInternalFieldCount(1); 30 | NODE_SET_METHOD(t, "unmask", BufferUtil::Unmask); 31 | NODE_SET_METHOD(t, "mask", BufferUtil::Mask); 32 | NODE_SET_METHOD(t, "merge", BufferUtil::Merge); 33 | target->Set(NanSymbol("BufferUtil"), t->GetFunction()); 34 | } 35 | 36 | protected: 37 | 38 | static NAN_METHOD(New) 39 | { 40 | NanScope(); 41 | BufferUtil* bufferUtil = new BufferUtil(); 42 | bufferUtil->Wrap(args.This()); 43 | NanReturnValue(args.This()); 44 | } 45 | 46 | static NAN_METHOD(Merge) 47 | { 48 | NanScope(); 49 | Local bufferObj = args[0]->ToObject(); 50 | char* buffer = Buffer::Data(bufferObj); 51 | Local array = Local::Cast(args[1]); 52 | unsigned int arrayLength = array->Length(); 53 | size_t offset = 0; 54 | unsigned int i; 55 | for (i = 0; i < arrayLength; ++i) { 56 | Local src = array->Get(i)->ToObject(); 57 | size_t length = Buffer::Length(src); 58 | memcpy(buffer + offset, Buffer::Data(src), length); 59 | offset += length; 60 | } 61 | NanReturnValue(NanTrue()); 62 | } 63 | 64 | static NAN_METHOD(Unmask) 65 | { 66 | NanScope(); 67 | Local buffer_obj = args[0]->ToObject(); 68 | size_t length = Buffer::Length(buffer_obj); 69 | Local mask_obj = args[1]->ToObject(); 70 | unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj); 71 | unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj); 72 | size_t len32 = length / 4; 73 | unsigned int i; 74 | for (i = 0; i < len32; ++i) *(from + i) ^= *mask; 75 | from += i; 76 | switch (length % 4) { 77 | case 3: *((unsigned char*)from+2) = *((unsigned char*)from+2) ^ ((unsigned char*)mask)[2]; 78 | case 2: *((unsigned char*)from+1) = *((unsigned char*)from+1) ^ ((unsigned char*)mask)[1]; 79 | case 1: *((unsigned char*)from ) = *((unsigned char*)from ) ^ ((unsigned char*)mask)[0]; 80 | case 0:; 81 | } 82 | NanReturnValue(NanTrue()); 83 | } 84 | 85 | static NAN_METHOD(Mask) 86 | { 87 | NanScope(); 88 | Local buffer_obj = args[0]->ToObject(); 89 | Local mask_obj = args[1]->ToObject(); 90 | unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj); 91 | Local output_obj = args[2]->ToObject(); 92 | unsigned int dataOffset = args[3]->Int32Value(); 93 | unsigned int length = args[4]->Int32Value(); 94 | unsigned int* to = (unsigned int*)(Buffer::Data(output_obj) + dataOffset); 95 | unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj); 96 | unsigned int len32 = length / 4; 97 | unsigned int i; 98 | for (i = 0; i < len32; ++i) *(to + i) = *(from + i) ^ *mask; 99 | to += i; 100 | from += i; 101 | switch (length % 4) { 102 | case 3: *((unsigned char*)to+2) = *((unsigned char*)from+2) ^ *((unsigned char*)mask+2); 103 | case 2: *((unsigned char*)to+1) = *((unsigned char*)from+1) ^ *((unsigned char*)mask+1); 104 | case 1: *((unsigned char*)to ) = *((unsigned char*)from ) ^ *((unsigned char*)mask); 105 | case 0:; 106 | } 107 | NanReturnValue(NanTrue()); 108 | } 109 | }; 110 | 111 | extern "C" void init (Handle target) 112 | { 113 | NanScope(); 114 | BufferUtil::Initialize(target); 115 | } 116 | 117 | NODE_MODULE(bufferutil, init) 118 | -------------------------------------------------------------------------------- /node_modules/websocket/src/validation.cc: -------------------------------------------------------------------------------- 1 | /*! 2 | * UTF-8 Validation Code originally from: 3 | * ws: a node.js websocket client 4 | * Copyright(c) 2011 Einar Otto Stangvik 5 | * MIT Licensed 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "nan.h" 16 | 17 | using namespace v8; 18 | using namespace node; 19 | 20 | #define UNI_SUR_HIGH_START (uint32_t) 0xD800 21 | #define UNI_SUR_LOW_END (uint32_t) 0xDFFF 22 | #define UNI_REPLACEMENT_CHAR (uint32_t) 0x0000FFFD 23 | #define UNI_MAX_LEGAL_UTF32 (uint32_t) 0x0010FFFF 24 | 25 | static const uint8_t trailingBytesForUTF8[256] = { 26 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 27 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 28 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 29 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 30 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 31 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 32 | 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 33 | 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 34 | }; 35 | 36 | static const uint32_t offsetsFromUTF8[6] = { 37 | 0x00000000, 0x00003080, 0x000E2080, 38 | 0x03C82080, 0xFA082080, 0x82082080 39 | }; 40 | 41 | static int isLegalUTF8(const uint8_t *source, const int length) 42 | { 43 | uint8_t a; 44 | const uint8_t *srcptr = source+length; 45 | switch (length) { 46 | default: return 0; 47 | /* Everything else falls through when "true"... */ 48 | /* RFC3629 makes 5 & 6 bytes UTF-8 illegal 49 | case 6: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; 50 | case 5: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; */ 51 | case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; 52 | case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; 53 | case 2: if ((a = (*--srcptr)) > 0xBF) return 0; 54 | switch (*source) { 55 | /* no fall-through in this inner switch */ 56 | case 0xE0: if (a < 0xA0) return 0; break; 57 | case 0xED: if (a > 0x9F) return 0; break; 58 | case 0xF0: if (a < 0x90) return 0; break; 59 | case 0xF4: if (a > 0x8F) return 0; break; 60 | default: if (a < 0x80) return 0; 61 | } 62 | 63 | case 1: if (*source >= 0x80 && *source < 0xC2) return 0; 64 | } 65 | if (*source > 0xF4) return 0; 66 | return 1; 67 | } 68 | 69 | int is_valid_utf8 (size_t len, char *value) 70 | { 71 | /* is the string valid UTF-8? */ 72 | for (unsigned int i = 0; i < len; i++) { 73 | uint32_t ch = 0; 74 | uint8_t extrabytes = trailingBytesForUTF8[(uint8_t) value[i]]; 75 | 76 | if (extrabytes + i >= len) 77 | return 0; 78 | 79 | if (isLegalUTF8 ((uint8_t *) (value + i), extrabytes + 1) == 0) return 0; 80 | 81 | switch (extrabytes) { 82 | case 5 : ch += (uint8_t) value[i++]; ch <<= 6; 83 | case 4 : ch += (uint8_t) value[i++]; ch <<= 6; 84 | case 3 : ch += (uint8_t) value[i++]; ch <<= 6; 85 | case 2 : ch += (uint8_t) value[i++]; ch <<= 6; 86 | case 1 : ch += (uint8_t) value[i++]; ch <<= 6; 87 | case 0 : ch += (uint8_t) value[i]; 88 | } 89 | 90 | ch -= offsetsFromUTF8[extrabytes]; 91 | 92 | if (ch <= UNI_MAX_LEGAL_UTF32) { 93 | if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) 94 | return 0; 95 | } else { 96 | return 0; 97 | } 98 | } 99 | 100 | return 1; 101 | } 102 | 103 | class Validation : public ObjectWrap 104 | { 105 | public: 106 | 107 | static void Initialize(v8::Handle target) 108 | { 109 | NanScope(); 110 | Local t = NanNew(New); 111 | t->InstanceTemplate()->SetInternalFieldCount(1); 112 | NODE_SET_METHOD(t, "isValidUTF8", Validation::IsValidUTF8); 113 | target->Set(NanSymbol("Validation"), t->GetFunction()); 114 | } 115 | 116 | protected: 117 | 118 | static NAN_METHOD(New) 119 | { 120 | NanScope(); 121 | Validation* validation = new Validation(); 122 | validation->Wrap(args.This()); 123 | NanReturnValue(args.This()); 124 | } 125 | 126 | static NAN_METHOD(IsValidUTF8) 127 | { 128 | NanScope(); 129 | if (!Buffer::HasInstance(args[0])) { 130 | return NanThrowTypeError("First argument needs to be a buffer"); 131 | } 132 | Local buffer_obj = args[0]->ToObject(); 133 | char *buffer_data = Buffer::Data(buffer_obj); 134 | size_t buffer_length = Buffer::Length(buffer_obj); 135 | NanReturnValue(is_valid_utf8(buffer_length, buffer_data) == 1 ? NanTrue() : NanFalse()); 136 | } 137 | }; 138 | 139 | extern "C" void init (Handle target) 140 | { 141 | NanScope(); 142 | Validation::Initialize(target); 143 | } 144 | 145 | NODE_MODULE(validation, init) 146 | -------------------------------------------------------------------------------- /node_modules/websocket/vendor/FastBufferList.js: -------------------------------------------------------------------------------- 1 | // This file was copied from https://github.com/substack/node-bufferlist 2 | // and modified to be able to copy bytes from the bufferlist directly into 3 | // a pre-existing fixed-size buffer without an additional memory allocation. 4 | 5 | // bufferlist.js 6 | // Treat a linked list of buffers as a single variable-size buffer. 7 | var Buffer = require('buffer').Buffer; 8 | var EventEmitter = require('events').EventEmitter; 9 | 10 | module.exports = BufferList; 11 | module.exports.BufferList = BufferList; // backwards compatibility 12 | 13 | function BufferList(opts) { 14 | if (!(this instanceof BufferList)) return new BufferList(opts); 15 | EventEmitter.call(this); 16 | var self = this; 17 | 18 | if (typeof(opts) == 'undefined') opts = {}; 19 | 20 | // default encoding to use for take(). Leaving as 'undefined' 21 | // makes take() return a Buffer instead. 22 | self.encoding = opts.encoding; 23 | 24 | // constructor to use for Buffer-esque operations 25 | self.construct = opts.construct || Buffer; 26 | 27 | var head = { next : null, buffer : null }; 28 | var last = { next : null, buffer : null }; 29 | 30 | // length can get negative when advanced past the end 31 | // and this is the desired behavior 32 | var length = 0; 33 | self.__defineGetter__('length', function () { 34 | return length; 35 | }); 36 | 37 | // keep an offset of the head to decide when to head = head.next 38 | var offset = 0; 39 | 40 | // Write to the bufferlist. Emits 'write'. Always returns true. 41 | self.write = function (buf) { 42 | if (!head.buffer) { 43 | head.buffer = buf; 44 | last = head; 45 | } 46 | else { 47 | last.next = { next : null, buffer : buf }; 48 | last = last.next; 49 | } 50 | length += buf.length; 51 | self.emit('write', buf); 52 | return true; 53 | }; 54 | 55 | self.end = function (buf) { 56 | if (Buffer.isBuffer(buf)) self.write(buf); 57 | }; 58 | 59 | // Push buffers to the end of the linked list. (deprecated) 60 | // Return this (self). 61 | self.push = function () { 62 | var args = [].concat.apply([], arguments); 63 | args.forEach(self.write); 64 | return self; 65 | }; 66 | 67 | // For each buffer, perform some action. 68 | // If fn's result is a true value, cut out early. 69 | // Returns this (self). 70 | self.forEach = function (fn) { 71 | if (!head.buffer) return new self.construct(0); 72 | 73 | if (head.buffer.length - offset <= 0) return self; 74 | var firstBuf = head.buffer.slice(offset); 75 | 76 | var b = { buffer : firstBuf, next : head.next }; 77 | 78 | while (b && b.buffer) { 79 | var r = fn(b.buffer); 80 | if (r) break; 81 | b = b.next; 82 | } 83 | 84 | return self; 85 | }; 86 | 87 | // Create a single Buffer out of all the chunks or some subset specified by 88 | // start and one-past the end (like slice) in bytes. 89 | self.join = function (start, end) { 90 | if (!head.buffer) return new self.construct(0); 91 | if (start == undefined) start = 0; 92 | if (end == undefined) end = self.length; 93 | 94 | var big = new self.construct(end - start); 95 | var ix = 0; 96 | self.forEach(function (buffer) { 97 | if (start < (ix + buffer.length) && ix < end) { 98 | // at least partially contained in the range 99 | buffer.copy( 100 | big, 101 | Math.max(0, ix - start), 102 | Math.max(0, start - ix), 103 | Math.min(buffer.length, end - ix) 104 | ); 105 | } 106 | ix += buffer.length; 107 | if (ix > end) return true; // stop processing past end 108 | }); 109 | 110 | return big; 111 | }; 112 | 113 | self.joinInto = function (targetBuffer, targetStart, sourceStart, sourceEnd) { 114 | if (!head.buffer) return new self.construct(0); 115 | if (sourceStart == undefined) sourceStart = 0; 116 | if (sourceEnd == undefined) sourceEnd = self.length; 117 | 118 | var big = targetBuffer; 119 | if (big.length - targetStart < sourceEnd - sourceStart) { 120 | throw new Error("Insufficient space available in target Buffer."); 121 | } 122 | var ix = 0; 123 | self.forEach(function (buffer) { 124 | if (sourceStart < (ix + buffer.length) && ix < sourceEnd) { 125 | // at least partially contained in the range 126 | buffer.copy( 127 | big, 128 | Math.max(targetStart, targetStart + ix - sourceStart), 129 | Math.max(0, sourceStart - ix), 130 | Math.min(buffer.length, sourceEnd - ix) 131 | ); 132 | } 133 | ix += buffer.length; 134 | if (ix > sourceEnd) return true; // stop processing past end 135 | }); 136 | 137 | return big; 138 | }; 139 | 140 | // Advance the buffer stream by n bytes. 141 | // If n the aggregate advance offset passes the end of the buffer list, 142 | // operations such as .take() will return empty strings until enough data is 143 | // pushed. 144 | // Returns this (self). 145 | self.advance = function (n) { 146 | offset += n; 147 | length -= n; 148 | while (head.buffer && offset >= head.buffer.length) { 149 | offset -= head.buffer.length; 150 | head = head.next 151 | ? head.next 152 | : { buffer : null, next : null } 153 | ; 154 | } 155 | self.emit('advance', n); 156 | return self; 157 | }; 158 | 159 | // Take n bytes from the start of the buffers. 160 | // Returns a string. 161 | // If there are less than n bytes in all the buffers or n is undefined, 162 | // returns the entire concatenated buffer string. 163 | self.take = function (n, encoding) { 164 | if (n == undefined) n = self.length; 165 | else if (typeof n !== 'number') { 166 | encoding = n; 167 | n = self.length; 168 | } 169 | var b = head; 170 | if (!encoding) encoding = self.encoding; 171 | if (encoding) { 172 | var acc = ''; 173 | self.forEach(function (buffer) { 174 | if (n <= 0) return true; 175 | acc += buffer.toString( 176 | encoding, 0, Math.min(n,buffer.length) 177 | ); 178 | n -= buffer.length; 179 | }); 180 | return acc; 181 | } else { 182 | // If no 'encoding' is specified, then return a Buffer. 183 | return self.join(0, n); 184 | } 185 | }; 186 | 187 | // The entire concatenated buffer as a string. 188 | self.toString = function () { 189 | return self.take('binary'); 190 | }; 191 | } 192 | require('util').inherits(BufferList, EventEmitter); 193 | --------------------------------------------------------------------------------