<commit_before>define('/style/js/biz/server-info.js', function(require, exports, module) {
	var whistle = window.whistle = {};
	var curServerInfo;

	$(document.body).on('click', '.reload', function() {
		location.reload();
	});

	function getServerInfo() {
		$.ajax({
			url: '/cgi-bin/server-info',
			dataType: 'json',
			timeout: 10000,
			success: handleServerInfo,
			error: showDisconnectedDialog,
			complete: function() {
				setTimeout(getServerInfo, 2000);
			}
		});
	}

	function handleServerInfo(data) {
		data = data.server;
		hideDisconnectedDialog();
		checkServerInfo(data) ? hideServerChangedDialog() : showServerChangedDialog(data);
	}

	function checkServerInfo(newServerInfo, serverInfo) {
		serverInfo = serverInfo || whistle.serverInfo;

		return !(serverInfo.port != newServerInfo.port || serverInfo.host != newServerInfo.host ||
				serverInfo.ipv4.sort().join() != newServerInfo.ipv4.sort().join() ||
				serverInfo.ipv6.sort().join() != newServerInfo.ipv6.sort().join());
	}

	function renderAboutDialog(serverInfo) {
		var html = ['Host:  ' + serverInfo.host, 'Port:  ' + serverInfo.port];
		if (serverInfo.ipv4.length) {
			html.push('IPv4:
' + serverInfo.ipv4.join('
'));
		}
		if (serverInfo.ipv6.length) {
			html.push('IPv6:
' + serverInfo.ipv6.join('
'));
		}
		$('.about-server-info').html(html.join('
'));
	}

	function showDisconnectedDialog() {
		curServerInfo = null;
		if (whistle.disconnected) {
			return;
		}
		hideServerChangedDialog();
		whistle.disconnected = true;
		$('.server-disconnected-dialog').modal('show');
	}

	function hideDisconnectedDialog() {
		whistle.disconnected = false;
		$('.server-disconnected-dialog').modal('hide');
	}

	function showServerChangedDialog(serverInfo) {
		if (checkServerInfo(serverInfo, curServerInfo)) {
			return;
		}
		curServerInfo = serverInfo;
		hideDisconnectedDialog();
		$('.server-changed-dialog').modal('show');
		renderAboutDialog(serverInfo);
	}

	function hideServerChangedDialog() {
		$('.server-changed-dialog').modal('hide');
	}

	module.exports = function init(serverInfo) {
		whistle.serverInfo = serverInfo;
		renderAboutDialog(serverInfo);
		setTimeout(getServerInfo, 1000);
	};
});
<commit_msg>show error dialog<commit_after>define('/style/js/biz/server-info.js', function(require, exports, module) {
	var whistle = window.whistle = {};
	var curServerInfo;
	var serverStateDialog = $('.server-disconnected-dialog');

	var post = $.post;
	$.post = function() {
		if (whistle.disconnected) {
			serverStateDialog.modal('show');
		}
		post.apply($, arguments);
	};

	$(document.body).on('click', '.reload', function() {
		location.reload();
	});

	function getServerInfo() {
		$.ajax({
			url: '/cgi-bin/server-info',
			dataType: 'json',
			timeout: 10000,
			success: handleServerInfo,
			error: showDisconnectedDialog,
			complete: function() {
				setTimeout(getServerInfo, 2000);
			}
		});
	}

	function handleServerInfo(data) {
		data = data.server;
		hideDisconnectedDialog();
		checkServerInfo(data) ? hideServerChangedDialog() : showServerChangedDialog(data);
	}

	function checkServerInfo(newServerInfo, serverInfo) {
		serverInfo = serverInfo || whistle.serverInfo;

		return !(serverInfo.port != newServerInfo.port || serverInfo.host != newServerInfo.host ||
				serverInfo.ipv4.sort().join() != newServerInfo.ipv4.sort().join() ||
				serverInfo.ipv6.sort().join() != newServerInfo.ipv6.sort().join());
	}

	function renderAboutDialog(serverInfo) {
		var html = ['Host:  ' + serverInfo.host, 'Port:  ' + serverInfo.port];
		if (serverInfo.ipv4.length) {
			html.push('IPv4:
' + serverInfo.ipv4.join('
'));
		}
		if (serverInfo.ipv6.length) {
			html.push('IPv6:
' + serverInfo.ipv6.join('
'));
		}
		$('.about-server-info').html(html.join('
'));
	}

	function showDisconnectedDialog() {
		curServerInfo = null;
		if (whistle.disconnected) {
			return;
		}
		hideServerChangedDialog();
		whistle.disconnected = true;
		$('.server-disconnected-dialog').modal('show');
	}

	function hideDisconnectedDialog() {
		whistle.disconnected = false;
		$('.server-disconnected-dialog').modal('hide');
	}

	function showServerChangedDialog(serverInfo) {
		if (checkServerInfo(serverInfo, curServerInfo)) {
			return;
		}
		curServerInfo = serverInfo;
		hideDisconnectedDialog();
		$('.server-changed-dialog').modal('show');
		renderAboutDialog(serverInfo);
	}

	function hideServerChangedDialog() {
		$('.server-changed-dialog').modal('hide');
	}

	module.exports = function init(serverInfo) {
		whistle.serverInfo = serverInfo;
		renderAboutDialog(serverInfo);
		setTimeout(getServerInfo, 1000);
	};
});
<|endoftext|>


<commit_before>import { clientsClaim, skipWaiting } from 'workbox-core';
import {
  cleanupOutdatedCaches,
  precacheAndRoute,
  matchPrecache,
} from 'workbox-precaching';
import {
  registerRoute,
  setDefaultHandler,
  setCatchHandler,
} from 'workbox-routing';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import {
  CacheFirst,
  StaleWhileRevalidate,
  NetworkFirst,
  NetworkOnly,
} from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { BroadcastUpdatePlugin } from 'workbox-broadcast-update';
import * as googleAnalytics from 'workbox-google-analytics';

precacheAndRoute(self.__WB_MANIFEST, {
  // Ignore all URL parameters:
  // https://developers.google.com/web/tools/workbox/modules/workbox-precaching#ignore_url_parameters
  ignoreURLParametersMatching: [/.*/],
});

cleanupOutdatedCaches();

// default strategy
setDefaultHandler(
  new StaleWhileRevalidate({
    cacheName: 'default',
  })
);

// Google Analytics
registerRoute(
  ({ request }) =>
    request.url === 'https://www.google-analytics.com/analytics.js',
  new CacheFirst({
    cacheName: 'shell',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 10 * 24 * 60 * 60, // 10 Days
      }),
    ],
  })
);

// Pages
// Try to get fresh HTML from network, but don't wait for more than 5 seconds
registerRoute(
  ({ request }) => request.destination === 'document',
  new NetworkFirst({
    cacheName: 'pages',
    networkTimeoutSeconds: 5,
    plugins: [new BroadcastUpdatePlugin()],
  })
);

// Images
registerRoute(
  ({ request }) => request.destination === 'image',
  new StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 200,
        maxAgeSeconds: 90 * 24 * 60 * 60, // 90 Days
      }),
    ],
  })
);

setCatchHandler(({ event }) => {
  switch (event.request.destination) {
    case 'document':
      return matchPrecache('/');

    case 'image':
      return new Response(
        '<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 225" xmlns="https://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice"><title id="offline-title">Offline</title><path fill="rgba(145,145,145,0.5)" d="M0 0h400v225H0z" /><text fill="rgba(0,0,0,0.33)" font-family="Georgia,serif" font-size="27" text-anchor="middle" x="200" y="113" dominant-baseline="central">offline</text></svg>',
        { headers: { 'Content-Type': 'image/svg+xml' } }
      );

    default:
      // If we don't have a fallback, just return an error response.
      return new Response('Service Temporarily Unavailable', {
        status: 503,
        statusText: 'Service Temporarily Unavailable',
        contentType: 'text/plain',
      });
  }
});

googleAnalytics.initialize({
  hitFilter: (params) => {
    const queueTimeInSeconds = Math.round(params.get('qt') / 1000);
    params.set('cm2', queueTimeInSeconds);
  },
  parameterOverrides: {
    cd4: 'offline',
  },
});

skipWaiting();
clientsClaim();
<commit_msg>More verbose error when the Service Worker can't answer the request<commit_after>import { clientsClaim, skipWaiting } from 'workbox-core';
import {
  cleanupOutdatedCaches,
  precacheAndRoute,
  matchPrecache,
} from 'workbox-precaching';
import {
  registerRoute,
  setDefaultHandler,
  setCatchHandler,
} from 'workbox-routing';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import {
  CacheFirst,
  StaleWhileRevalidate,
  NetworkFirst,
  NetworkOnly,
} from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { BroadcastUpdatePlugin } from 'workbox-broadcast-update';
import * as googleAnalytics from 'workbox-google-analytics';

precacheAndRoute(self.__WB_MANIFEST, {
  // Ignore all URL parameters:
  // https://developers.google.com/web/tools/workbox/modules/workbox-precaching#ignore_url_parameters
  ignoreURLParametersMatching: [/.*/],
});

cleanupOutdatedCaches();

// default strategy
setDefaultHandler(
  new StaleWhileRevalidate({
    cacheName: 'default',
  })
);

// Google Analytics
registerRoute(
  ({ request }) =>
    request.url === 'https://www.google-analytics.com/analytics.js',
  new CacheFirst({
    cacheName: 'shell',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 10 * 24 * 60 * 60, // 10 Days
      }),
    ],
  })
);

// Pages
// Try to get fresh HTML from network, but don't wait for more than 5 seconds
registerRoute(
  ({ request }) => request.destination === 'document',
  new NetworkFirst({
    cacheName: 'pages',
    networkTimeoutSeconds: 5,
    plugins: [new BroadcastUpdatePlugin()],
  })
);

// Images
registerRoute(
  ({ request }) => request.destination === 'image',
  new StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 200,
        maxAgeSeconds: 90 * 24 * 60 * 60, // 90 Days
      }),
    ],
  })
);

setCatchHandler(({ event }) => {
  switch (event.request.destination) {
    case 'document':
      return matchPrecache('/');

    case 'image':
      return new Response(
        '<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 225" xmlns="https://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice"><title id="offline-title">Offline</title><path fill="rgba(145,145,145,0.5)" d="M0 0h400v225H0z" /><text fill="rgba(0,0,0,0.33)" font-family="Georgia,serif" font-size="27" text-anchor="middle" x="200" y="113" dominant-baseline="central">offline</text></svg>',
        { headers: { 'Content-Type': 'image/svg+xml' } }
      );

    default:
      // If we don't have a fallback, just return an error response.
      return new Response(
        "Service Temporarily Unavailable, Service Worker couldn't respond.",
        {
          status: 503,
          statusText:
            "Service Temporarily Unavailable, Service Worker couldn't respond.",
          contentType: 'text/plain',
        }
      );
  }
});

googleAnalytics.initialize({
  hitFilter: (params) => {
    const queueTimeInSeconds = Math.round(params.get('qt') / 1000);
    params.set('cm2', queueTimeInSeconds);
  },
  parameterOverrides: {
    cd4: 'offline',
  },
});

skipWaiting();
clientsClaim();
<|endoftext|>


<commit_before>(function($) {
$.fn.lifestream.feeds.vimeo = function( config, callback ) {

  var template = $.extend({},
  {
    liked: 'liked ${title}',
    posted: 'posted ${title}'
  },
  config.template),

  parseVimeo = function( input, item_type ) {
    var output = [], i = 0, j, item, type = item_type || 'liked', date, description;

    if (input) {
      j = input.length;
      for( ; i < j; i++) {
        item = input[i];
        if (type === 'posted') {
          date = new Date( item.upload_date.replace(' ', 'T') );
        } else {
          date = new Date( item.liked_on.replace(' ', 'T') );
        }

        if (item.description) {
          description = item.description.replace(/"/g, "'").replace( /<.+?>/gi, '');
        } else {
          description = '';
        }

        output.push({
          date: date,
          config: config,
          html: $.tmpl( template[type], {
            url: item.url,
            description: item.description ? item.description
              .replace(/"/g, "'")
              .replace( /<.+?>/gi, '') : '',
            title: item.title
          })
        });
      }
    }

    return output;
  };

  $.ajax({
    url: $.fn.lifestream.createYqlUrl('SELECT * FROM xml WHERE ' +
      'url="http://vimeo.com/api/v2/' + config.user + '/likes.xml" OR ' +
      'url="http://vimeo.com/api/v2/' + config.user + '/videos.xml"'),
    dataType: 'jsonp',
    success: function( response ) {
      var output = [];

      // check for likes & parse
      if ( response.query.results.videos[0].video.length > 0 ) {
        output = output.concat(parseVimeo(
          response.query.results.videos[0].video
        ));
      }

      // check for uploads & parse
      if ( response.query.results.videos[1].video.length > 0 ) {
        output = output.concat(
          parseVimeo(response.query.results.videos[1].video, 'posted')
        );
      }

      callback(output);
    }
  });

  // Expose the template.
  // We use this to check which templates are available
  return {
    'template' : template
  };

};
})(jQuery);<commit_msg>Handle empty Vimeo lists gracefully (fix NPE)<commit_after>(function($) {
$.fn.lifestream.feeds.vimeo = function( config, callback ) {

  var template = $.extend({},
  {
    liked: 'liked ${title}',
    posted: 'posted ${title}'
  },
  config.template),

  parseVimeo = function( input, item_type ) {
    var output = [], i = 0, j, item, type = item_type || 'liked', date, description;

    if (input) {
      j = input.length;
      for( ; i < j; i++) {
        item = input[i];
        if (type === 'posted') {
          date = new Date( item.upload_date.replace(' ', 'T') );
        } else {
          date = new Date( item.liked_on.replace(' ', 'T') );
        }

        if (item.description) {
          description = item.description.replace(/"/g, "'").replace( /<.+?>/gi, '');
        } else {
          description = '';
        }

        output.push({
          date: date,
          config: config,
          html: $.tmpl( template[type], {
            url: item.url,
            description: item.description ? item.description
              .replace(/"/g, "'")
              .replace( /<.+?>/gi, '') : '',
            title: item.title
          })
        });
      }
    }

    return output;
  };

  $.ajax({
    url: $.fn.lifestream.createYqlUrl('SELECT * FROM xml WHERE ' +
      'url="http://vimeo.com/api/v2/' + config.user + '/likes.xml" OR ' +
      'url="http://vimeo.com/api/v2/' + config.user + '/videos.xml"'),
    dataType: 'jsonp',
    success: function( response ) {
      var output = [];

      // check for likes & parse
      if ( response.query.results.videos[0] != null &&
           response.query.results.videos[0].video.length > 0 ) {
        output = output.concat(parseVimeo(
          response.query.results.videos[0].video
        ));
      }

      // check for uploads & parse
      if ( response.query.results.videos[1] != null &&
           response.query.results.videos[1].video.length > 0 ) {
        output = output.concat(
          parseVimeo(response.query.results.videos[1].video, 'posted')
        );
      }

      callback(output);
    }
  });

  // Expose the template.
  // We use this to check which templates are available
  return {
    'template' : template
  };

};
})(jQuery);<|endoftext|>


<commit_before>var path = require('path');

require.paths.unshift(path.join(__dirname, 'vendor'),
                      path.join(__dirname, 'cradle'));

var sys = require("sys"),
   http = require("http"),
 events = require('events'),
  posix = require("posix"),
    url = require('url');

var querystring = require('querystring');

var cradle = exports;

cradle.host = '127.0.0.1';
cradle.port = 5984;
cradle.options = {
    cache: false
};

cradle.setup = function (settings) {
    this.host = settings.host;
    this.port = parseInt(settings.port);
    this.options.cache = settings.cache || false;

    return this;
};

cradle.Connection = function Connection(/* variable args */) {
    var args = Array.prototype.slice.call(arguments),
        host, port, options = {};

    if (args.length === 1) {
        // An options hash was passed
        if (typeof(args[0]) === 'object') {
            host = args[0].host;
            port = parseInt(args[0].port);
        // A string was passed
        } else {
            host = args[0];
        }
    // The host and port were passed separately
    } else if (args.length === 2) {
        host = args[0];
        port = parseInt(args[1]);
    }

    this.host = host || cradle.host;
    this.port = port || cradle.port;
    this.options = process.mixin({}, cradle.options, options);

    this.socket = http.createClient(this.port, this.host);
};

cradle.Connection.prototype.request = function (method, path, options, data, headers) {
    var promise = new(events.Promise), request;

    path = (path || '/').replace('http://', '').replace(/\/{2,}/g, '/');
    headers = process.mixin({ host: this.host }, headers || {});

    if (data) {
        data = JSON.stringify(data, function (k, val) {
            if (typeof(val) === 'function') {
                return val.toString();
            } else { return val }
        });
        headers["Content-Length"] = data.length;
        headers["Content-Type"] = "application/json";
    }
    if (path.charAt(0) !== '/') { path = '/' + path }
    if (options) {
        for (var k in options) {
            if (typeof(options[k]) === 'boolean') {
                options[k] = String(options[k]);
            }
        }
        path += '?' + querystring.stringify(options);
    }

    //sys.debug(method + ' ' + path + ' -- ' + data +' '+ JSON.stringify(headers));
    request = this.socket.request(method.toUpperCase(), path, headers);

    if (data) { request.sendBody(data, 'utf8') }

    request.finish(function (res) {
        var body = '';

        res.setBodyEncoding('utf8');
        res.addListener('body', function (chunk) {
            body += (chunk || '');
        }).addListener('complete', function () {
            var obj, response;

            try { obj = JSON.parse(body) }
            catch (e) { return promise.emitError(e) }

            response = new(cradle.Response)(res, obj);

            if (response.error) {
                promise.emitError(response);
            } else {
                promise.emitSuccess(response);
            }
        });
    });
    return promise;
};

cradle.Connection.prototype.database = function (name) {
    var that = this;

    return {
        name: name,
        //
        // Database query cache
        //
        cache: {
            store: {},
            get: function (id) {
                return this.query('get', id);
            },
            save: function (id, doc) {
                return this.query('save', id, doc);
            },
            purge: function () {
                return this.query('purge');
            },
            has: function (id) {
                return this.query('has', id);
            },
            query: function (op, id, doc) {
                if (that.options.cache) {
                    switch (op) {
                        case 'has'  : return id in this.store;
                        case 'get'  : return this.store[id];
                        case 'save' : return this.store[id] = doc;
                        case 'purge': if (id) { delete(this.store[id]) }
                                      else { this.store = {} };
                                      break;
                    }
                } else { return false }
            }
        },
        query: function (method, path, options, data, headers) {
            return that.request(
                method, [name, path].join('/'), options, data, headers
            );
        },
        exists: function () {
            var promise = new(events.Promise);

            this.query('GET', '/').addCallback(function (res) {
                promise.emitSuccess(true);
            }).addErrback(function (res) {
                if (res._headers.status === 404) {
                    promise.emitSuccess(false);
                } else if (res._headers.status === 200) {
                    promise.emitError(res);
                }
            });
            return promise;
        },
        get: function (id, rev) {
            var that = this, options = {};

            if (typeof(rev) === 'string') { options = {rev: rev} }
            else if (rev && typeof(rev) === 'object') { options = rev }

            return this.query('GET', id, options).addCallback(function (res) {
                that.cache.save(res.id, res.doc);
            });
        },
        save: function (/* [id], [rev], doc, ... */) {
            var id, doc = {}, that = this, args = Array.prototype.slice.call(arguments);

            // PUT a single document, with an id
            if (typeof(args[0]) === 'string' && args.length > 1) {
                id = args[0];
                // Design document
                if (/^_design\/\w+$/.test(id)) {
                    doc.language = "javascript";
                    doc.views = args[args.length - 1];
                } else {
                    doc = args[args.length - 1];
                }
                // _rev
                if (typeof(args[1]) === 'string') { doc._rev = args[1] }
                else if (this.cache.has(id)) {
                    doc._rev = this.cache.get(id)._rev;
                }

                return this.query('PUT', id, {}, doc).addCallback(writeThrough);
            // POST a single document
            } else if (args.length === 1 && !Array.isArray(args[0])) {
                doc = args[0];
                return this.query('POST', '/', {}, doc).addCallback(writeThrough);
            // Bulk insert
            } else {
                if (Array.isArray(args[0])) {
                    doc = {docs: args[0]};
                    if (args[1] === true) { doc.all_or_nothing = true }
                } else {
                    doc = {docs: args};
                }
                return this.query('POST', '/_bulk_docs', {}, doc);
            }

            function writeThrough(res) {
                that.cache.save(id, process.mixin({}, doc, { _rev: res.rev }));
            }
        },
        update: function (id, obj) {
            var doc = this.cache.get(id);
            if (doc) {
                return this.save(id, process.mixin(true, {}, doc, obj));
            } else {
                throw new(Error)(id + " wasn't found in cache-store, couldn't update");
            }
        },
        destroy: function () {
            if (arguments.length > 0) {
                throw new(Error)("destroy() doesn't take any arguments");
            } else {
                return this.query('DELETE', '/');
            }
        },
        remove: function (id, rev) {
            var that = this;
            if (! (rev = rev || this.cache.get(id))) {
                throw new(Error)("rev needs to be supplied");
            }
            return this.query('DELETE', id, {rev: rev}).addCallback(function (res) {
                that.cache.purge(id);
            });
        },
        create: function () {
            return this.query('PUT', '/');
        },
        info: function () {
            return this.query('GET', '/');
        },
        all: function (options) {
            return this.query('GET', '/_all_docs', options);
        },
        compact: function (design) {
            return this.query('POST', '/_compact' + (design ? '/' + design : ''));
        },
        viewCleanup: function () {
            return this.query('POST', '/_view_cleanup');
        },
        allBySeq: function (options) {
            return this.query('GET', '/_all_docs_by_seq', options);
        },
        view: function (path, options) {
            path = path.split('/');

            if (options) {
                ['key', 'startkey', 'endkey'].forEach(function (k) {
                    if (k in options) { options[k] = JSON.stringify(options[k]) }
                });
            }

            return this.query(
                'GET', ['_design', path[0], '_view', path[1]].join('/'), options
            );
        },

        push: function (doc) {}
    }

};

cradle.Connection.prototype.databases = function () {
    return this.request('GET', '/_all_dbs');
};
cradle.Connection.prototype.config = function () {
    return this.request('GET', '/_config');
};
cradle.Connection.prototype.info = function () {
    return this.request('GET', '/');
};
cradle.Connection.prototype.stats = function () {
    return this.request('GET', '/_stats');
};
cradle.Connection.prototype.activeTasks = function () {
    return this.request('GET', '/_active_tasks');
};
cradle.Connection.prototype.uuids = function (count) {
    return this.request('GET', '/_uuids', count ? {count: count} : {});
};

cradle.Response = function Response(response, json) {
    var that = this;

    this._headers = {
        status: response.statusCode
    };

    this.doc = json;

    if (json instanceof Array) {
        return json;
    }

    Object.keys(json).forEach(function (k) {
        that.__defineGetter__(k, function () { return json[k] });
    });

    if (!this.id && this._id) this.id = this._id;
    if (!this.rev && this._rev) this.rev = this._rev;

    if (this.rows) {
        this.forEach = function (f) { return that.rows.forEach(f) };
        this.map = function (f) { return that.rows.map(f) };
    }
};

<commit_msg>save(): only fetch _rev from cache if it wasn't supplied<commit_after>var path = require('path');

require.paths.unshift(path.join(__dirname, 'vendor'),
                      path.join(__dirname, 'cradle'));

var sys = require("sys"),
   http = require("http"),
 events = require('events'),
  posix = require("posix"),
    url = require('url');

var querystring = require('querystring');

var cradle = exports;

cradle.host = '127.0.0.1';
cradle.port = 5984;
cradle.options = {
    cache: false
};

cradle.setup = function (settings) {
    this.host = settings.host;
    this.port = parseInt(settings.port);
    this.options.cache = settings.cache || false;

    return this;
};

cradle.Connection = function Connection(/* variable args */) {
    var args = Array.prototype.slice.call(arguments),
        host, port, options = {};

    if (args.length === 1) {
        // An options hash was passed
        if (typeof(args[0]) === 'object') {
            host = args[0].host;
            port = parseInt(args[0].port);
        // A string was passed
        } else {
            host = args[0];
        }
    // The host and port were passed separately
    } else if (args.length === 2) {
        host = args[0];
        port = parseInt(args[1]);
    }

    this.host = host || cradle.host;
    this.port = port || cradle.port;
    this.options = process.mixin({}, cradle.options, options);

    this.socket = http.createClient(this.port, this.host);
};

cradle.Connection.prototype.request = function (method, path, options, data, headers) {
    var promise = new(events.Promise), request;

    path = (path || '/').replace('http://', '').replace(/\/{2,}/g, '/');
    headers = process.mixin({ host: this.host }, headers || {});

    if (data) {
        data = JSON.stringify(data, function (k, val) {
            if (typeof(val) === 'function') {
                return val.toString();
            } else { return val }
        });
        headers["Content-Length"] = data.length;
        headers["Content-Type"] = "application/json";
    }
    if (path.charAt(0) !== '/') { path = '/' + path }
    if (options) {
        for (var k in options) {
            if (typeof(options[k]) === 'boolean') {
                options[k] = String(options[k]);
            }
        }
        path += '?' + querystring.stringify(options);
    }

    //sys.debug(method + ' ' + path + ' -- ' + data +' '+ JSON.stringify(headers));
    request = this.socket.request(method.toUpperCase(), path, headers);

    if (data) { request.sendBody(data, 'utf8') }

    request.finish(function (res) {
        var body = '';

        res.setBodyEncoding('utf8');
        res.addListener('body', function (chunk) {
            body += (chunk || '');
        }).addListener('complete', function () {
            var obj, response;

            try { obj = JSON.parse(body) }
            catch (e) { return promise.emitError(e) }

            response = new(cradle.Response)(res, obj);

            if (response.error) {
                promise.emitError(response);
            } else {
                promise.emitSuccess(response);
            }
        });
    });
    return promise;
};

cradle.Connection.prototype.database = function (name) {
    var that = this;

    return {
        name: name,
        //
        // Database query cache
        //
        cache: {
            store: {},
            get: function (id) {
                return this.query('get', id);
            },
            save: function (id, doc) {
                return this.query('save', id, doc);
            },
            purge: function () {
                return this.query('purge');
            },
            has: function (id) {
                return this.query('has', id);
            },
            query: function (op, id, doc) {
                if (that.options.cache) {
                    switch (op) {
                        case 'has'  : return id in this.store;
                        case 'get'  : return this.store[id];
                        case 'save' : return this.store[id] = doc;
                        case 'purge': if (id) { delete(this.store[id]) }
                                      else { this.store = {} };
                                      break;
                    }
                } else { return false }
            }
        },
        query: function (method, path, options, data, headers) {
            return that.request(
                method, [name, path].join('/'), options, data, headers
            );
        },
        exists: function () {
            var promise = new(events.Promise);

            this.query('GET', '/').addCallback(function (res) {
                promise.emitSuccess(true);
            }).addErrback(function (res) {
                if (res._headers.status === 404) {
                    promise.emitSuccess(false);
                } else if (res._headers.status === 200) {
                    promise.emitError(res);
                }
            });
            return promise;
        },
        get: function (id, rev) {
            var that = this, options = {};

            if (typeof(rev) === 'string') { options = {rev: rev} }
            else if (rev && typeof(rev) === 'object') { options = rev }

            return this.query('GET', id, options).addCallback(function (res) {
                that.cache.save(res.id, res.doc);
            });
        },
        save: function (/* [id], [rev], doc, ... */) {
            var id, doc = {}, that = this, args = Array.prototype.slice.call(arguments);

            // PUT a single document, with an id
            if (typeof(args[0]) === 'string' && args.length > 1) {
                id = args[0];
                // Design document
                if (/^_design\/\w+$/.test(id)) {
                    doc.language = "javascript";
                    doc.views = args[args.length - 1];
                } else {
                    doc = args[args.length - 1];
                }
                // _rev
                if (typeof(args[1]) === 'string') { doc._rev = args[1] }
                else if (!doc._rev && this.cache.has(id)) {
                    doc._rev = this.cache.get(id)._rev;
                }

                return this.query('PUT', id, {}, doc).addCallback(writeThrough);
            // POST a single document
            } else if (args.length === 1 && !Array.isArray(args[0])) {
                doc = args[0];
                return this.query('POST', '/', {}, doc).addCallback(writeThrough);
            // Bulk insert
            } else {
                if (Array.isArray(args[0])) {
                    doc = {docs: args[0]};
                    if (args[1] === true) { doc.all_or_nothing = true }
                } else {
                    doc = {docs: args};
                }
                return this.query('POST', '/_bulk_docs', {}, doc);
            }

            function writeThrough(res) {
                that.cache.save(id, process.mixin({}, doc, { _rev: res.rev }));
            }
        },
        update: function (id, obj) {
            var doc = this.cache.get(id);
            if (doc) {
                return this.save(id, process.mixin(true, {}, doc, obj));
            } else {
                throw new(Error)(id + " wasn't found in cache-store, couldn't update");
            }
        },
        destroy: function () {
            if (arguments.length > 0) {
                throw new(Error)("destroy() doesn't take any arguments");
            } else {
                return this.query('DELETE', '/');
            }
        },
        remove: function (id, rev) {
            var that = this;
            if (! (rev = rev || this.cache.get(id))) {
                throw new(Error)("rev needs to be supplied");
            }
            return this.query('DELETE', id, {rev: rev}).addCallback(function (res) {
                that.cache.purge(id);
            });
        },
        create: function () {
            return this.query('PUT', '/');
        },
        info: function () {
            return this.query('GET', '/');
        },
        all: function (options) {
            return this.query('GET', '/_all_docs', options);
        },
        compact: function (design) {
            return this.query('POST', '/_compact' + (design ? '/' + design : ''));
        },
        viewCleanup: function () {
            return this.query('POST', '/_view_cleanup');
        },
        allBySeq: function (options) {
            return this.query('GET', '/_all_docs_by_seq', options);
        },
        view: function (path, options) {
            path = path.split('/');

            if (options) {
                ['key', 'startkey', 'endkey'].forEach(function (k) {
                    if (k in options) { options[k] = JSON.stringify(options[k]) }
                });
            }

            return this.query(
                'GET', ['_design', path[0], '_view', path[1]].join('/'), options
            );
        },

        push: function (doc) {}
    }

};

cradle.Connection.prototype.databases = function () {
    return this.request('GET', '/_all_dbs');
};
cradle.Connection.prototype.config = function () {
    return this.request('GET', '/_config');
};
cradle.Connection.prototype.info = function () {
    return this.request('GET', '/');
};
cradle.Connection.prototype.stats = function () {
    return this.request('GET', '/_stats');
};
cradle.Connection.prototype.activeTasks = function () {
    return this.request('GET', '/_active_tasks');
};
cradle.Connection.prototype.uuids = function (count) {
    return this.request('GET', '/_uuids', count ? {count: count} : {});
};

cradle.Response = function Response(response, json) {
    var that = this;

    this._headers = {
        status: response.statusCode
    };

    this.doc = json;

    if (json instanceof Array) {
        return json;
    }

    Object.keys(json).forEach(function (k) {
        that.__defineGetter__(k, function () { return json[k] });
    });

    if (!this.id && this._id) this.id = this._id;
    if (!this.rev && this._rev) this.rev = this._rev;

    if (this.rows) {
        this.forEach = function (f) { return that.rows.forEach(f) };
        this.map = function (f) { return that.rows.map(f) };
    }
};

<|endoftext|>


<commit_before>GLOW.Uniform = (function() {
    "use strict"; "use restrict";

    // private data, functions and initializations here
    var once = false;
    var setFunctions = [];
    var setvFunctions = [];
    function lazyInit() {
        // lazy initialization so we know we got GL bound to a context

        // TODO: support other types of data than GLOW.Matrix/Vector
        setFunctions[GL.INT] = function(location, data) { GL.uniform1i(location, data.value); };
        setFunctions[GL.INT_VEC2] = function(location, data) { GL.uniform2i(location, data.value[0], data.value[1]); };
        setFunctions[GL.INT_VEC3] = function(location, data) { GL.uniform3i(location, data.value[0], data.value[1], data.value[2]); };
        setFunctions[GL.INT_VEC4] = function(location, data) { GL.uniform4i(location, data.value[0], data.value[1], data.value[2], data.value[3]); };
        setFunctions[GL.FLOAT] = function(location, data) { GL.uniform1f(location, data.value); };
        setFunctions[GL.FLOAT_VEC2] = function(location, data) { GL.uniform2f(location, data.value[0], data.value[1]); };
        setFunctions[GL.FLOAT_VEC3] = function(location, data) { GL.uniform3f(location, data.value[0], data.value[1], data.value[2]); };
        setFunctions[GL.FLOAT_VEC4] = function(location, data) { GL.uniform4f(location, data.value[0], data.value[1], data.value[2], data.value[3]); };

        setFunctions[GL.FLOAT_MAT2] = function(location, data) { GL.uniformMatrix2fv(location, data.transposeUniform, data.value); };
        setFunctions[GL.FLOAT_MAT3] = function(location, data) { GL.uniformMatrix3fv(location, data.transposeUniform, data.value); };
        setFunctions[GL.FLOAT_MAT4] = function(location, data) { GL.uniformMatrix4fv(location, data.transposeUniform, data.value); };
        setFunctions[GL.SAMPLER_2D] = function(location, data) {
            if (data.texture !== undefined && data.textureUnit !== -1 && !GLOW.currentContext.cache.textureCached(data)) {
                GL.uniform1i( location, data.textureUnit);
                GL.activeTexture(GL.TEXTURE0 + data.textureUnit);
                GL.bindTexture(GL.TEXTURE_2D, data.texture);
            }
        };
        setFunctions[GL.SAMPLER_CUBE] = function(location, data) {
            /* TODO */
        };

        setvFunctions[GL.INT] = function(location, data) { GL.uniform1iv(location, data.value); };
        setvFunctions[GL.INT_VEC2] = function(location, data) { GL.uniform2iv(location, data.value); };
        setvFunctions[GL.INT_VEC3] = function(location, data) { GL.uniform3iv(location, data.value); };
        setvFunctions[GL.INT_VEC4] = function(location, data) { GL.uniform4iv(location, data.value); };
        setvFunctions[GL.FLOAT] = function(location, data) { GL.uniform1fv(location, data.value); };
        setvFunctions[GL.FLOAT_VEC2] = function(location, data) { GL.uniform2fv(location, data.value); };
        setvFunctions[GL.FLOAT_VEC3] = function(location, data) { GL.uniform3fv(location, data.value); };
        setvFunctions[GL.FLOAT_VEC4] = function(location, data) { GL.uniform4fv(location, data.value); };
    }

    // constructor
    function uniform(parameters, data) {
        if (!once) {
            once = true;
            lazyInit();
        }

        this.id = GLOW.uniqueId();
        this.data = data;
        this.location = parameters.location;
        this.locationNumber = parameters.locationNumber;

        // todo should all of these really get stored?
        this.name = parameters.name;
        this.length = parameters.length;
        this.type = parameters.type;

        this.uniformFunction = (this.length !== undefined && this.length > 1) ?
            setvFunctions[this.type] : setFunctions[this.type];
    }

    // methods
    uniform.prototype.set = function() {
        if (!GLOW.currentContext.cache.uniformCached(this)) {
            this.uniformFunction(this.location, this.data);
        }
    };

    return uniform;
})();
<commit_msg>avoid passing parameters that are properties on the object<commit_after>GLOW.Uniform = (function() {
    "use strict"; "use restrict";

    // private data, functions and initializations here
    var once = false;
    var setFunctions = [];
    var setvFunctions = [];
    function lazyInit() {
        // lazy initialization so we know we got GL bound to a context

        // TODO: support other types of data than GLOW.Matrix/Vector
        setFunctions[GL.INT] = function() { GL.uniform1i(this.location, this.data.value); };
        setFunctions[GL.INT_VEC2] = function() { GL.uniform2i(this.location, this.data.value[0], this.data.value[1]); };
        setFunctions[GL.INT_VEC3] = function() { GL.uniform3i(this.location, this.data.value[0], this.data.value[1], this.data.value[2]); };
        setFunctions[GL.INT_VEC4] = function() { GL.uniform4i(this.location, this.data.value[0], this.data.value[1], this.data.value[2], this.data.value[3]); };
        setFunctions[GL.FLOAT] = function() { GL.uniform1f(this.location, this.data.value); };
        setFunctions[GL.FLOAT_VEC2] = function() { GL.uniform2f(this.location, this.data.value[0], this.data.value[1]); };
        setFunctions[GL.FLOAT_VEC3] = function() { GL.uniform3f(this.location, this.data.value[0], this.data.value[1], this.data.value[2]); };
        setFunctions[GL.FLOAT_VEC4] = function() { GL.uniform4f(this.location, this.data.value[0], this.data.value[1], this.data.value[2], this.data.value[3]); };

        setFunctions[GL.FLOAT_MAT2] = function() { GL.uniformMatrix2fv(this.location, this.data.transposeUniform, this.data.value); };
        setFunctions[GL.FLOAT_MAT3] = function() { GL.uniformMatrix3fv(this.location, this.data.transposeUniform, this.data.value); };
        setFunctions[GL.FLOAT_MAT4] = function() { GL.uniformMatrix4fv(this.location, this.data.transposeUniform, this.data.value); };
        setFunctions[GL.SAMPLER_2D] = function() {
            if (this.data.texture !== undefined && this.data.textureUnit !== -1 && !GLOW.currentContext.cache.textureCached(this.data)) {
                GL.uniform1i(this.location, this.data.textureUnit);
                GL.activeTexture(GL.TEXTURE0 + this.data.textureUnit);
                GL.bindTexture(GL.TEXTURE_2D, this.data.texture);
            }
        };
        setFunctions[GL.SAMPLER_CUBE] = function() {
            /* TODO */
        };

        setvFunctions[GL.INT] = function() { GL.uniform1iv(this.location, this.data.value); };
        setvFunctions[GL.INT_VEC2] = function() { GL.uniform2iv(this.location, this.data.value); };
        setvFunctions[GL.INT_VEC3] = function() { GL.uniform3iv(this.location, this.data.value); };
        setvFunctions[GL.INT_VEC4] = function() { GL.uniform4iv(this.location, this.data.value); };
        setvFunctions[GL.FLOAT] = function() { GL.uniform1fv(this.location, this.data.value); };
        setvFunctions[GL.FLOAT_VEC2] = function() { GL.uniform2fv(this.location, this.data.value); };
        setvFunctions[GL.FLOAT_VEC3] = function() { GL.uniform3fv(this.location, this.data.value); };
        setvFunctions[GL.FLOAT_VEC4] = function() { GL.uniform4fv(this.location, this.data.value); };
    }

    // constructor
    function uniform(parameters, data) {
        if (!once) {
            once = true;
            lazyInit();
        }

        this.id = GLOW.uniqueId();
        this.data = data;
        this.location = parameters.location;
        this.locationNumber = parameters.locationNumber;

        // todo should all of these really get stored?
        this.name = parameters.name;
        this.length = parameters.length;
        this.type = parameters.type;

        this.uniformFunction = (this.length !== undefined && this.length > 1) ?
            setvFunctions[this.type] : setFunctions[this.type];
    }

    // methods
    uniform.prototype.set = function() {
        if (!GLOW.currentContext.cache.uniformCached(this)) {
            this.uniformFunction();
        }
    };

    return uniform;
})();
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const chalk = require('chalk');
const npm = require('npm');
const path = require('path');
const semver = require('semver');
const semverDiff = require('semver-diff');

const LOG_PREFIX = "%log-prefix%";

var pkgJson;

/**
 * console.log wrapper, these logs will pass through the overwritten stdout.write
 *
 * @param message
 */
function log(message) {
    console.log(LOG_PREFIX + message)
}

/**
 * Overwrite the standard stdout.write, to silence npm
 *
 * @returns {Function}
 */
function hook() {
    var old_write = process.stdout.write;

    process.stdout.write = (function (write) {
        return function (string, encoding, fd) {
            if (string.startsWith(LOG_PREFIX)) {
                arguments[0] = string.replace(LOG_PREFIX, "");
                write.apply(process.stdout, arguments);
            }
        }
    })(process.stdout.write);

    return function () {
        process.stdout.write = old_write
    }
}

/**
 * Fetches the latest version of the package from the registry
 *
 * @param packageName
 * @returns {Promise}
 */
function getLatestVersion(packageName) {
    return new Promise(function (resolve, reject) {
        npm.load({silent: true}, function (err) {
            if (err) reject(err);

            npm.commands.info([packageName], function (er, data) {
                try {
                    resolve(Object.keys(data)[0])
                }
                catch (err) {
                    log(chalk.red("Something went wrong") + " when determining the latest version of " + chalk.cyan(packageName));
                    reject(err);
                }
            });
        });
    })
}

/**
 * Bundles the update statuses of all given packages
 *
 * @param packages
 * @returns {Promise}
 */
function getLatestVersions(packages) {
    return new Promise(function (resolve, reject) {
        var promises = [];
        var updateReport = {
            satisfied: [],
            unsatisfied: []
        };

        Object.keys(packages).forEach(function (pkg) {
            var currentSemVer = (packages[pkg]);
            var versionPromise = getLatestVersion(pkg);

            versionPromise.then(function (latestSemVer) {
                var pkgObject = {
                    name: pkg,
                    from: currentSemVer,
                    to: latestSemVer
                };

                var diff = semverDiff(currentSemVer, latestSemVer);

                if (diff) {
                    pkgObject.status = diff;
                    updateReport.unsatisfied.push(pkgObject);
                } else {
                    pkgObject.status = 'satisfies';
                    updateReport.satisfied.push(pkgObject);
                }
            });

            promises.push(versionPromise);
        });

        Promise.all(promises)
            .then(function () {
                resolve(updateReport);
            })
            .catch(function (err) {
                reject(err);
            });
    })
}

/**
 * dep-rep executor, creates a report of the package update statuses.
 *
 * @param logToConsole log output or not (boolean)
 * @returns {Promise}
 */
function exec(logToConsole) {
    return new Promise(function (resolve, reject) {
        var dependencies = Object.assign(
            {},
            pkgJson.dependencies,
            pkgJson.devDependencies,
            pkgJson.optionalDependencies,
            pkgJson.peerDependencies
        );

        // No dependencies defined?
        if (dependencies === {}) {
            console.log("No deps, no dice! No dependencies were found in the given package.json");
            return reject("No deps, no dice!");
        }

        Object.keys(dependencies).forEach(function (dependency) {
            // Bare bones prune for git or http dependencies
            if (dependencies[dependency].indexOf("http") > -1 || dependencies[dependency].indexOf("git") > -1) {
                delete dependencies[dependency];
            }
        });

        var unhook = hook();

        getLatestVersions(dependencies)
            .then(function (result) {
                unhook();
                if (logToConsole) report(result);
                resolve(result);
            })
            .catch(reject(function (err) {
                reject(err);
            }));
    })
}

/**
 * Sets up the necessary config for dep-rep to do it's work
 *
 * @param pathToPackage
 * @param logToConsole
 * @returns {Promise}
 */
function analyze(pathToPackage, logToConsole) {
    pkgJson = require(path.resolve(process.cwd(), pathToPackage || 'package.json'));

    return (exec(logToConsole));
}

/**
 * Writes the report to the console
 *
 * @param result
 */
function report(result) {
    if (result.satisfied.length > 0) {
        console.log();

        result.satisfied.forEach(function (pkg) {
            console.log(chalk.white(pkg.name) + " " + pkg.from + chalk.green(" includes the latest version ") + pkg.to)
        });
    }

    if (result.unsatisfied.length > 0) {
        result.unsatisfied.forEach(function (pkg) {
            console.log(chalk.white(pkg.name) + " " + pkg.from + chalk.yellow(" can be updated to ") + pkg.to + " (" + pkg.status + ")")
        });
    } else {
        console.log(chalk.green("\nAll your dependencies are up to date ") + chalk.white(":") + chalk.red("o") + chalk.white(")\n"))
    }

}

module.exports = {
    analyze: analyze
};
<commit_msg>New report structure<commit_after>#!/usr/bin/env node
'use strict';

const chalk = require('chalk');
const npm = require('npm');
const path = require('path');
const semver = require('semver');
const semverDiff = require('semver-diff');

const LOG_PREFIX = "%log-prefix%";

var pkgJson;

/**
 * console.log wrapper, these logs will pass through the overwritten stdout.write
 *
 * @param message
 */
function log(message) {
    console.log(LOG_PREFIX + message)
}

/**
 * Overwrite the standard stdout.write, to silence npm
 *
 * @returns {Function}
 */
function hook() {
    var old_write = process.stdout.write;

    process.stdout.write = (function (write) {
        return function (string, encoding, fd) {
            if (string.startsWith(LOG_PREFIX)) {
                arguments[0] = string.replace(LOG_PREFIX, "");
                write.apply(process.stdout, arguments);
            }
        }
    })(process.stdout.write);

    return function () {
        process.stdout.write = old_write
    }
}

/**
 * Fetches the latest version of the package from the registry
 *
 * @param packageName
 * @returns {Promise}
 */
function getLatestVersion(packageName) {
    return new Promise(function (resolve, reject) {
        npm.load({silent: true}, function (err) {
            if (err) reject(err);

            npm.commands.info([packageName], function (er, data) {
                try {
                    resolve(Object.keys(data)[0])
                }
                catch (err) {
                    log(chalk.red("Something went wrong") + " when determining the latest version of " + chalk.cyan(packageName));
                    reject(err);
                }
            });
        });
    })
}

/**
 * Bundles the update statuses of all given packages
 *
 * @param packages
 * @returns {Promise}
 */
function getLatestVersions(packages) {
    return new Promise(function (resolve, reject) {
        var promises = [];
        var updateReport = {};

        Object.keys(packages).forEach(function (packageName) {
            var currentSemVer = (packages[packageName]);
            var versionPromise = getLatestVersion(packageName);

            versionPromise
                .then(function (latestSemVer) {
                    console.log(packageName);
                    var pkgObject = {
                        name: packageName,
                        from: currentSemVer,
                        to: latestSemVer,
                        satisfied: semver.satisfies(latestSemVer, currentSemVer)
                    };

                    // Add the diff status if dependency no longer includes the latest version
                    if (!pkgObject.satisfied) {
                        pkgObject.diff = semverDiff(currentSemVer, latestSemVer);
                    }

                    updateReport[packageName] = pkgObject;
                })
                .catch(function (err) {
                    log(err);
                });

            promises.push(versionPromise);
        });

        Promise.all(promises)
            .then(function () {
                resolve(updateReport);
            })
            .catch(function (err) {
                reject(err);
            });
    })
}

/**
 * dep-rep executor, creates a report of the package update statuses.
 *
 * @param logToConsole log output or not (boolean)
 * @returns {Promise}
 */
function exec(logToConsole) {
    return new Promise(function (resolve, reject) {
        var dependencies = Object.assign(
            {},
            pkgJson.dependencies,
            pkgJson.devDependencies,
            pkgJson.optionalDependencies,
            pkgJson.peerDependencies
        );

        // No dependencies defined?
        if (dependencies === {}) {
            console.log("No deps, no dice! No dependencies were found in the given package.json");
            return reject("No deps, no dice!");
        }

        Object.keys(dependencies).forEach(function (dependency) {
            // Bare bones prune for git or http dependencies
            if (dependencies[dependency].indexOf("http") > -1 || dependencies[dependency].indexOf("git") > -1) {
                delete dependencies[dependency];
            }
        });

        var unhook = hook();

        getLatestVersions(dependencies)
            .then(function (result) {
                unhook();
                if (logToConsole) report(result);
                resolve(result);
            })
            .catch(reject(function (err) {
                reject(err);
            }));
    })
}

/**
 * Sets up the necessary config for dep-rep to do it's work
 *
 * @param pathToPackage
 * @param logToConsole
 * @returns {Promise}
 */
function analyze(options) {
    pkgJson = require(path.resolve(process.cwd(), options.p || 'package.json'));

    return (exec(options.log));
}

/**
 * Writes the report to the console
 *
 * @param result
 */
function report(result) {
    var satisfied = [];
    var unsatisfied = [];

    Object.keys(result)
        .sort()
        .forEach(function (packageName) {
            var pkg = result[packageName];
            pkg.name = packageName;

            if (pkg.satisfied) {
                satisfied.push(pkg);
            } else {
                unsatisfied.push(pkg);
            }
        });

    if (satisfied.length > 0) {
        console.log("\nSatisfied dependencies");
        console.log("========================\n");

        satisfied.forEach(function (pkg) {
            console.log(chalk.white(pkg.name) + " " + pkg.from + chalk.green(" includes the latest version ") + pkg.to)
        });
    }

    if (unsatisfied.length > 0) {
        console.log("\nUnsatisfied dependencies");
        console.log("========================\n");

        unsatisfied.forEach(function (pkg) {
            console.log(chalk.white(pkg.name) + " " + pkg.from + chalk.yellow(" can be updated to ") + pkg.to + " (" + pkg.diff + ")")
        });
        console.log();
    } else {
        console.log(chalk.green("\nAll your dependencies are up to date ") + chalk.white(":") + chalk.red("o") + chalk.white(")\n"))
    }
}

module.exports = {
    analyze: analyze
};
<|endoftext|>


<commit_before>var async = require('async');
var Compiler = require('./compiler.js');
var DeployTracker = require('./deploy_tracker.js');
var ABIGenerator = require('./abi.js');
var web3;

var Deploy = function(options) {
  this.web3 = options.web3;
  this.contractsManager = options.contractsManager;
  this.logger = options.logger;
  this.env = options.env;

  this.deployTracker = new DeployTracker({
    logger: options.logger, chainConfig: options.chainConfig, web3: options.web3, env: this.env
  });
};

Deploy.prototype.checkAndDeployContract = function(contract, params, callback) {
  var self = this;
  var suppliedArgs;
  var realArgs;
  var arg;
  var l;
  var contractName;
  var referedContract;
  contract.error = false;

  if (contract.deploy === false) {
    self.logger.contractsState(self.contractsManager.contractsState());
    return callback();
  }

  if (contract.address !== undefined) {

    // determine arguments
    suppliedArgs = (params || contract.args);
    realArgs = [];

    for (l = 0; l < suppliedArgs.length; l++) {
      arg = suppliedArgs[l];
      if (arg[0] === "$") {
        contractName = arg.substr(1);
        referedContract = this.contractsManager.getContract(contractName);
        realArgs.push(referedContract.deployedAddress);
      } else {
        realArgs.push(arg);
      }
    }

    contract.deployedAddress = contract.address;
    self.deployTracker.trackContract(contract.className, contract.code, realArgs, contract.address);
    self.deployTracker.save();
    self.logger.contractsState(self.contractsManager.contractsState());
    return callback();
  }

  var trackedContract = self.deployTracker.getContract(contract.className, contract.code, contract.args);

  if (trackedContract && this.web3.eth.getCode(trackedContract.address) !== "0x") {
    self.logger.info(contract.className + " already deployed " + trackedContract.address);
    contract.deployedAddress = trackedContract.address;
    self.logger.contractsState(self.contractsManager.contractsState());
    callback();
  } else {

    // determine arguments
    suppliedArgs = (params || contract.args);
    realArgs = [];

    for (l = 0; l < suppliedArgs.length; l++) {
      arg = suppliedArgs[l];
      if (arg[0] === "$") {
        contractName = arg.substr(1);
        referedContract = this.contractsManager.getContract(contractName);
        realArgs.push(referedContract.deployedAddress);
      } else {
        realArgs.push(arg);
      }
    }

    this.deployContract(contract, realArgs, function(err, address) {
      self.deployTracker.trackContract(contract.className, contract.code, realArgs, address);
      self.deployTracker.save();
      self.logger.contractsState(self.contractsManager.contractsState());

      // TODO: replace evals with separate process so it's isolated and with
      // a callback
      if (contract.onDeploy !== undefined) {
        self.logger.info('executing onDeploy commands');
        var abiGenerator = new ABIGenerator({}, self.contractsManager);
        web3 = self.web3;
        var abi = abiGenerator.generateContracts(false);
        eval(abi); // jshint ignore:line

        var cmds = contract.onDeploy.join(';\n');
        eval(cmds); // jshint ignore:line
      }

      callback();
    });
  }

};

Deploy.prototype.deployContract = function(contract, params, callback) {
  var self = this;
  var contractObject = this.web3.eth.contract(contract.abiDefinition);

  var contractParams = (params || contract.args).slice();

  this.web3.eth.getAccounts(function(err, accounts) {
    //console.log("using address" + this.web3.eth.accounts[0]);

    // TODO: probably needs to be defaultAccount
    // TODO: it wouldn't necessary be the first address
    // use defined blockchain address or first address
    contractParams.push({
      //from: this.web3.eth.coinbase,
      from: accounts[0],
      data: contract.code,
      gas: contract.gas,
      gasPrice: contract.gasPrice
    });

    self.logger.info("deploying " + contract.className + " with " + contract.gas + " gas");
    contractParams.push(function(err, transaction) {
      self.logger.contractsState(self.contractsManager.contractsState());

      if (err) {
        self.logger.error("error deploying contract: " + contract.className);
        var errMsg = err.toString();
        if (errMsg === 'Error: The contract code couldn\'t be stored, please check your gas amount.') {
          errMsg = 'The contract code couldn\'t be stored, out of gas or constructor error';
        }
        self.logger.error(errMsg);
        contract.error = errMsg;
        callback(new Error(err));
      } else if (transaction.address !== undefined) {
        self.logger.info(contract.className + " deployed at " + transaction.address);
        contract.deployedAddress = transaction.address;
        contract.transactionHash = transaction.transactionHash;
        callback(null, transaction.address);
      }
    });

    contractObject["new"].apply(contractObject, contractParams);
  });
};

Deploy.prototype.deployAll = function(done) {
  var self = this;
  this.logger.info("deploying contracts");

  async.eachOfSeries(this.contractsManager.listContracts(),
                     function(contract, key, callback) {
                       self.logger.trace(arguments);
                       self.checkAndDeployContract(contract, null, callback);
                     },
                     function(err, results) {
                       self.logger.info("finished");
                       self.logger.trace(arguments);
                       done();
                     }
                    );

};

module.exports = Deploy;
<commit_msg>return callback<commit_after>var async = require('async');
var Compiler = require('./compiler.js');
var DeployTracker = require('./deploy_tracker.js');
var ABIGenerator = require('./abi.js');
var web3;

var Deploy = function(options) {
  this.web3 = options.web3;
  this.contractsManager = options.contractsManager;
  this.logger = options.logger;
  this.env = options.env;

  this.deployTracker = new DeployTracker({
    logger: options.logger, chainConfig: options.chainConfig, web3: options.web3, env: this.env
  });
};

Deploy.prototype.checkAndDeployContract = function(contract, params, callback) {
  var self = this;
  var suppliedArgs;
  var realArgs;
  var arg;
  var l;
  var contractName;
  var referedContract;
  contract.error = false;

  if (contract.deploy === false) {
    self.logger.contractsState(self.contractsManager.contractsState());
    return callback();
  }

  if (contract.address !== undefined) {

    // determine arguments
    suppliedArgs = (params || contract.args);
    realArgs = [];

    for (l = 0; l < suppliedArgs.length; l++) {
      arg = suppliedArgs[l];
      if (arg[0] === "$") {
        contractName = arg.substr(1);
        referedContract = this.contractsManager.getContract(contractName);
        realArgs.push(referedContract.deployedAddress);
      } else {
        realArgs.push(arg);
      }
    }

    contract.deployedAddress = contract.address;
    self.deployTracker.trackContract(contract.className, contract.code, realArgs, contract.address);
    self.deployTracker.save();
    self.logger.contractsState(self.contractsManager.contractsState());
    return callback();
  }

  var trackedContract = self.deployTracker.getContract(contract.className, contract.code, contract.args);

  if (trackedContract && this.web3.eth.getCode(trackedContract.address) !== "0x") {
    self.logger.info(contract.className + " already deployed " + trackedContract.address);
    contract.deployedAddress = trackedContract.address;
    self.logger.contractsState(self.contractsManager.contractsState());
    return callback();
  } else {

    // determine arguments
    suppliedArgs = (params || contract.args);
    realArgs = [];

    for (l = 0; l < suppliedArgs.length; l++) {
      arg = suppliedArgs[l];
      if (arg[0] === "$") {
        contractName = arg.substr(1);
        referedContract = this.contractsManager.getContract(contractName);
        realArgs.push(referedContract.deployedAddress);
      } else {
        realArgs.push(arg);
      }
    }

    this.deployContract(contract, realArgs, function(err, address) {
      self.deployTracker.trackContract(contract.className, contract.code, realArgs, address);
      self.deployTracker.save();
      self.logger.contractsState(self.contractsManager.contractsState());

      // TODO: replace evals with separate process so it's isolated and with
      // a callback
      if (contract.onDeploy !== undefined) {
        self.logger.info('executing onDeploy commands');
        var abiGenerator = new ABIGenerator({}, self.contractsManager);
        web3 = self.web3;
        var abi = abiGenerator.generateContracts(false);
        eval(abi); // jshint ignore:line

        var cmds = contract.onDeploy.join(';\n');
        eval(cmds); // jshint ignore:line
      }

      callback();
    });
  }

};

Deploy.prototype.deployContract = function(contract, params, callback) {
  var self = this;
  var contractObject = this.web3.eth.contract(contract.abiDefinition);

  var contractParams = (params || contract.args).slice();

  this.web3.eth.getAccounts(function(err, accounts) {
    //console.log("using address" + this.web3.eth.accounts[0]);

    // TODO: probably needs to be defaultAccount
    // TODO: it wouldn't necessary be the first address
    // use defined blockchain address or first address
    contractParams.push({
      //from: this.web3.eth.coinbase,
      from: accounts[0],
      data: contract.code,
      gas: contract.gas,
      gasPrice: contract.gasPrice
    });

    self.logger.info("deploying " + contract.className + " with " + contract.gas + " gas");
    contractParams.push(function(err, transaction) {
      self.logger.contractsState(self.contractsManager.contractsState());

      if (err) {
        self.logger.error("error deploying contract: " + contract.className);
        var errMsg = err.toString();
        if (errMsg === 'Error: The contract code couldn\'t be stored, please check your gas amount.') {
          errMsg = 'The contract code couldn\'t be stored, out of gas or constructor error';
        }
        self.logger.error(errMsg);
        contract.error = errMsg;
        callback(new Error(err));
      } else if (transaction.address !== undefined) {
        self.logger.info(contract.className + " deployed at " + transaction.address);
        contract.deployedAddress = transaction.address;
        contract.transactionHash = transaction.transactionHash;
        callback(null, transaction.address);
      }
    });

    contractObject["new"].apply(contractObject, contractParams);
  });
};

Deploy.prototype.deployAll = function(done) {
  var self = this;
  this.logger.info("deploying contracts");

  async.eachOfSeries(this.contractsManager.listContracts(),
                     function(contract, key, callback) {
                       self.logger.trace(arguments);
                       self.checkAndDeployContract(contract, null, callback);
                     },
                     function(err, results) {
                       self.logger.info("finished");
                       self.logger.trace(arguments);
                       done();
                     }
                    );

};

module.exports = Deploy;
<|endoftext|>


<commit_before>var Dialog = module.exports = function(message, options){
  this.options = (options || {});
  this.message = message;

  this.createElement();
};

Dialog.prototype.createElement = function(){
  this.element = document.createElement('div');
  this.element.className = "leapjs-dialog";
  this.element.style.position = "fixed";
  this.element.style.top = '8px';
  this.element.style.left = 0;
  this.element.style.right = 0;
  this.element.style.textAlign = 'center';
  this.element.style.zIndex = 1000;

  var dialog  = document.createElement('div');
  this.element.appendChild(dialog);
  dialog.style.display = "inline-block";
  dialog.style.margin = "auto";
  dialog.style.padding = "8px";
  dialog.style.color = "#222";
  dialog.style.background = "#eee";
  dialog.style.borderRadius = "4px";
  dialog.style.border = "1px solid #999";
  dialog.style.textAlign = "left";
  dialog.style.cursor = "pointer";
  dialog.style.whiteSpace = "nowrap";
  dialog.style.transition = "box-shadow 1s linear";
  dialog.innerHTML = this.message;

  if (this.options.onclick){
    dialog.addEventListener('click', this.options.onclick);
  }

  if (this.options.onmouseover){
    dialog.addEventListener('mouseover', this.options.onmouseover);
  }

  if (this.options.onmouseout){
    dialog.addEventListener('mouseout', this.options.onmouseout);
  }

  if (this.options.onmousemove){
    dialog.addEventListener('mousemove', this.options.onmousemove);
  }
};

Dialog.prototype.show = function(){
  document.body.appendChild(this.element);
  return this;
};

Dialog.prototype.hide = function(){
  document.body.removeChild(this.element);
  return this;
};

// Shows a DOM dialog box with links to developer.leapmotion.com to upgrade
// This will work whether or not the Leap is plugged in,
// As long as it is called after a call to .connect() and the 'ready' event has fired.
Dialog.warnOutOfDate = function(params){
  params || (params = {});

  var url = "http://developer.leapmotion.com?";

  params.returnTo = window.location.href;

  for (var key in params){
    url += key + '=' + encodeURIComponent(params[key]) + '&';
  }

  var dialog,
    onclick = function(event){

       if (event.target.id != 'leapjs-decline-upgrade'){

         var popup = window.open(url,
           '_blank',
           'height=800,width=1000,location=1,menubar=1,resizable=1,status=1,toolbar=1,scrollbars=1'
         );

         if (window.focus) {popup.focus()}

       }

       dialog.hide();

       return true;
    },

    message = "This site requires Leap Motion Tracking Beta, now available for developers." +
      "<button id='leapjs-accept-upgrade'  style='color: #444; transition: box-shadow 100ms linear; cursor: pointer; vertical-align: baseline; margin-left: 16px;'>Upgrade</button>" +
      "<button id='leapjs-decline-upgrade' style='color: #444; transition: box-shadow 100ms linear; cursor: pointer; vertical-align: baseline; margin-left: 8px; '>Not Now</button>";

  dialog = new Dialog(message, {
      onclick: onclick,
      onmousemove: function(e){
        if (e.target == document.getElementById('leapjs-decline-upgrade')){
          document.getElementById('leapjs-decline-upgrade').style.color = '#000';
          document.getElementById('leapjs-decline-upgrade').style.boxShadow = '0px 0px 2px #5daa00';

          document.getElementById('leapjs-accept-upgrade').style.color = '#444';
          document.getElementById('leapjs-accept-upgrade').style.boxShadow = 'none';
        }else{
          document.getElementById('leapjs-accept-upgrade').style.color = '#000';
          document.getElementById('leapjs-accept-upgrade').style.boxShadow = '0px 0px 2px #5daa00';

          document.getElementById('leapjs-decline-upgrade').style.color = '#444';
          document.getElementById('leapjs-decline-upgrade').style.boxShadow = 'none';
        }
      },
      onmouseout: function(){
        document.getElementById('leapjs-decline-upgrade').style.color = '#444';
        document.getElementById('leapjs-decline-upgrade').style.boxShadow = 'none';
        document.getElementById('leapjs-accept-upgrade').style.color = '#444';
        document.getElementById('leapjs-accept-upgrade').style.boxShadow = 'none';
      }
    }
  );

  return dialog.show();
};

// Tracks whether we've warned for lack of bones API.  This will be show only for early private-beta members.
Dialog.hasWarnedBones = false;

Dialog.warnBones = function(){
  if (this.hasWarnedBones) return;
  this.hasWarnedBones = true;

  console.warn("Your Leap Service is out of date");

  if ( !(typeof(process) !== 'undefined' && process.versions && process.versions.node) ){
    this.warnOutOfDate({reason: 'bones'});
  }

}<commit_msg>Add class name to warning dialog<commit_after>var Dialog = module.exports = function(message, options){
  this.options = (options || {});
  this.message = message;

  this.createElement();
};

Dialog.prototype.createElement = function(){
  this.element = document.createElement('div');
  this.element.className = "leapjs-dialog";
  this.element.style.position = "fixed";
  this.element.style.top = '8px';
  this.element.style.left = 0;
  this.element.style.right = 0;
  this.element.style.textAlign = 'center';
  this.element.style.zIndex = 1000;

  var dialog  = document.createElement('div');
  this.element.appendChild(dialog);
  dialog.style.className = "leapjs-dialog";
  dialog.style.display = "inline-block";
  dialog.style.margin = "auto";
  dialog.style.padding = "8px";
  dialog.style.color = "#222";
  dialog.style.background = "#eee";
  dialog.style.borderRadius = "4px";
  dialog.style.border = "1px solid #999";
  dialog.style.textAlign = "left";
  dialog.style.cursor = "pointer";
  dialog.style.whiteSpace = "nowrap";
  dialog.style.transition = "box-shadow 1s linear";
  dialog.innerHTML = this.message;

  if (this.options.onclick){
    dialog.addEventListener('click', this.options.onclick);
  }

  if (this.options.onmouseover){
    dialog.addEventListener('mouseover', this.options.onmouseover);
  }

  if (this.options.onmouseout){
    dialog.addEventListener('mouseout', this.options.onmouseout);
  }

  if (this.options.onmousemove){
    dialog.addEventListener('mousemove', this.options.onmousemove);
  }
};

Dialog.prototype.show = function(){
  document.body.appendChild(this.element);
  return this;
};

Dialog.prototype.hide = function(){
  document.body.removeChild(this.element);
  return this;
};

// Shows a DOM dialog box with links to developer.leapmotion.com to upgrade
// This will work whether or not the Leap is plugged in,
// As long as it is called after a call to .connect() and the 'ready' event has fired.
Dialog.warnOutOfDate = function(params){
  params || (params = {});

  var url = "http://developer.leapmotion.com?";

  params.returnTo = window.location.href;

  for (var key in params){
    url += key + '=' + encodeURIComponent(params[key]) + '&';
  }

  var dialog,
    onclick = function(event){

       if (event.target.id != 'leapjs-decline-upgrade'){

         var popup = window.open(url,
           '_blank',
           'height=800,width=1000,location=1,menubar=1,resizable=1,status=1,toolbar=1,scrollbars=1'
         );

         if (window.focus) {popup.focus()}

       }

       dialog.hide();

       return true;
    },

    message = "This site requires Leap Motion Tracking Beta, now available for developers." +
      "<button id='leapjs-accept-upgrade'  style='color: #444; transition: box-shadow 100ms linear; cursor: pointer; vertical-align: baseline; margin-left: 16px;'>Upgrade</button>" +
      "<button id='leapjs-decline-upgrade' style='color: #444; transition: box-shadow 100ms linear; cursor: pointer; vertical-align: baseline; margin-left: 8px; '>Not Now</button>";

  dialog = new Dialog(message, {
      onclick: onclick,
      onmousemove: function(e){
        if (e.target == document.getElementById('leapjs-decline-upgrade')){
          document.getElementById('leapjs-decline-upgrade').style.color = '#000';
          document.getElementById('leapjs-decline-upgrade').style.boxShadow = '0px 0px 2px #5daa00';

          document.getElementById('leapjs-accept-upgrade').style.color = '#444';
          document.getElementById('leapjs-accept-upgrade').style.boxShadow = 'none';
        }else{
          document.getElementById('leapjs-accept-upgrade').style.color = '#000';
          document.getElementById('leapjs-accept-upgrade').style.boxShadow = '0px 0px 2px #5daa00';

          document.getElementById('leapjs-decline-upgrade').style.color = '#444';
          document.getElementById('leapjs-decline-upgrade').style.boxShadow = 'none';
        }
      },
      onmouseout: function(){
        document.getElementById('leapjs-decline-upgrade').style.color = '#444';
        document.getElementById('leapjs-decline-upgrade').style.boxShadow = 'none';
        document.getElementById('leapjs-accept-upgrade').style.color = '#444';
        document.getElementById('leapjs-accept-upgrade').style.boxShadow = 'none';
      }
    }
  );

  return dialog.show();
};

// Tracks whether we've warned for lack of bones API.  This will be shown only for early private-beta members.
Dialog.hasWarnedBones = false;

Dialog.warnBones = function(){
  if (this.hasWarnedBones) return;
  this.hasWarnedBones = true;

  console.warn("Your Leap Service is out of date");

  if ( !(typeof(process) !== 'undefined' && process.versions && process.versions.node) ){
    this.warnOutOfDate({reason: 'bones'});
  }

}<|endoftext|>


<commit_before>'use strict'

const borderTypeId = 'border-type'

function saveOptions() {
	setWrapper({
		borderType: document.getElementById(borderTypeId).value
	})
}

function restoreOptions() {
	chrome.storage.sync.get({
		borderType: 'momentary',  // default value
	}, function(items) {
		document.getElementById(borderTypeId).value = items.borderType
	})
}

// Wrappers to simplify saving settings, and handle the status update.
function setWrapper(options) {
	const area = chrome.storage.sync || chrome.storage.local
	area.set(options, function() {
		const statusRegion = document.getElementById('status')
		statusRegion.textContent = chrome.i18n.getMessage('prefsSaved')
		setTimeout(function() {
			statusRegion.textContent = ''
		}, 750)
	})
}

// Translation
// Based on http://tumble.jeremyhubert.com/post/7076881720/translating-html-in-a-chrome-extension - HT http://stackoverflow.com/questions/25467009/
// TODO probably will need DRYing in future
// TODO would be nice to use the doForEach wrpper on this
function translateStuff() {
	const objects = document.getElementsByTagName('*')
	for(let i = 0; i < objects.length; i++) {
		if (objects[i].dataset && objects[i].dataset.message) {
			objects[i].innerText =
				chrome.i18n.getMessage(objects[i].dataset.message)
		}
	}
}

document.addEventListener('DOMContentLoaded', translateStuff)
document.addEventListener('DOMContentLoaded', restoreOptions)
document.getElementById('save').addEventListener('click', saveOptions)
<commit_msg>Fix typo<commit_after>'use strict'

const borderTypeId = 'border-type'

function saveOptions() {
	setWrapper({
		borderType: document.getElementById(borderTypeId).value
	})
}

function restoreOptions() {
	chrome.storage.sync.get({
		borderType: 'momentary',  // default value
	}, function(items) {
		document.getElementById(borderTypeId).value = items.borderType
	})
}

// Wrapper to simplify saving settings, and handle the status update.
function setWrapper(options) {
	const area = chrome.storage.sync || chrome.storage.local
	area.set(options, function() {
		const statusRegion = document.getElementById('status')
		statusRegion.textContent = chrome.i18n.getMessage('prefsSaved')
		setTimeout(function() {
			statusRegion.textContent = ''
		}, 750)
	})
}

// Translation
// Based on http://tumble.jeremyhubert.com/post/7076881720/translating-html-in-a-chrome-extension - HT http://stackoverflow.com/questions/25467009/
// TODO probably will need DRYing in future
// TODO would be nice to use the doForEach wrpper on this
function translateStuff() {
	const objects = document.getElementsByTagName('*')
	for(let i = 0; i < objects.length; i++) {
		if (objects[i].dataset && objects[i].dataset.message) {
			objects[i].innerText =
				chrome.i18n.getMessage(objects[i].dataset.message)
		}
	}
}

document.addEventListener('DOMContentLoaded', translateStuff)
document.addEventListener('DOMContentLoaded', restoreOptions)
document.getElementById('save').addEventListener('click', saveOptions)
<|endoftext|>