<commit_before>var tmDropdownString = '<option>  ↓ Mink has TimeMaps for... ↓</option>';
var tmDropdownNoTimemapsString = '<option>--- No TimeMaps available ---</option>';

function restore_options(){
    chrome.storage.local.get('blacklist', function(items) {
      $(items.blacklist).each(function(i, v){
        $("#options").append(getListItemHTML(v, 'glyphicon-remove'));
      });
      updateSaveButtonStatus();
      updateRemoveAllBlacklistButtonStatus();

      $(".remove").click(function(){
        if($(this).hasClass('glyphicon-remove')){
          var uriToStrike = $(this).parent().text();
          $(this).parent().addClass("strike");
          $(this).toggleClass('glyphicon-remove glyphicon-ok');
        }else {
          $(this).toggleClass('glyphicon-ok glyphicon-remove');
          $(this).parent().removeClass("strike");
        }
        updateSaveButtonStatus();
        updateRemoveAllBlacklistButtonStatus();

      });
    });
}

function getListItemHTML(uri, classIn, buttonText){
  if(!buttonText) {
    buttonText = '';
  }
  return '
<button class="btn btn-default btn-xs glyphicon ' + classIn + ' remove" type="button">' + buttonText + '</button>' + uri + '
';
}

function removeBlacklist() {
  chrome.storage.local.set({'blacklist': []});
}

function saveBlacklist(){
  var blacklistJSON = {};
  var uris = [];
  $('.newEntry span').each(function(){
    uris.push($(this).text());
  });
  blacklistJSON.blacklist = uris;
  chrome.storage.local.set(blacklistJSON);
  $('.newEntry').removeClass('newEntry'); // Disable indicator for unsaved data
  updateSaveButtonStatus();
}

function updateSaveButtonStatus(){
  var saveBlacklistButton = $('#saveBlacklist');
  if($('.glyphicon-ok').length > 0 || $('.newEntry').length > 0) {
    console.log('a');
    saveBlacklistButton.removeAttr('disabled').removeClass('disabled');
  }else {
    console.log('b');
    saveBlacklistButton.attr('disabled','disabled').addClass('disabled');
  }
}

function updateRemoveAllBlacklistButtonStatus() {
  var removeBlacklistButton = $('#removeBlacklist');
  console.log($('#options li').length);
  console.log($('#options li'));
  if($('#options li').length > 0) {
    removeBlacklistButton.removeAttr('disabled').removeClass('disabled');
  }else {
    removeBlacklistButton.attr('disabled','disabled').addClass('disabled');
  }
}

function createAddURIBinder(){
    $("#add").click(function(){
      addMinkBlacklistToBeSavedLI();
      bindAddBlacklistEntryUI();
    });
}

function bindAddBlacklistEntryUI() {
  $('.uriTextField').keyup(function() {
    var uriFieldValue = $(this).val();
    if(uriFieldValue.length == 0) {
      $(this).parent().find('button.addToBlacklist').attr('disabled',true);
    }else {
      $(this).parent().find('button.addToBlacklist').removeAttr('disabled');
    }
  });
  $('.addToBlacklist').click(addToBlacklistToBeSaved);
  $('.cancelAddToBlacklist').click(removeFromBlacklistToBeSaved);
}

function addMinkBlacklistToBeSavedLI(valIn) {
  if(!valIn) {
    valIn = '';
  }
  $("#options").prepend('
<input type="text" placeholder="http://"  class="uriTextField" id="newURI" "' + valIn + '"/><button class="addToBlacklist" disabled>Add to Blacklist</button><button class="cancelAddToBlacklist">Cancel</button>
');
}

function addToBlacklistToBeSaved() {
  var uri = $(this).parent().find('.uriTextField').val();
  if(uri.substr(0,4) !== 'http') {
    uri = 'http://' + uri;
  }

  $(this).parent().replaceWith(getListItemHTML(uri, 'glyphicon-remove newItem'));
  $('.newItem').click(removeEntry);
  $('.newItem').removeClass('newItem').parent().addClass('newEntry');
  // $('.newEntry').append('<button  class="btn btn-default btn-xs glyphicon glyphicon-chevron-left" style="font-size: 12px; margin-left: 1.0em;">Nevermind</button>');
  updateSaveButtonStatus();
}

function removeFromBlacklistToBeSaved() {
  $(this).parent().remove();
}

function removeEntry() {
  $(this).parent().remove();
  updateSaveButtonStatus();
}

function populatedCachedTimeMapsUI() {
  chrome.storage.local.get('timemaps',function(items) {
    console.log('items in the TM localstorage');
    console.log(items);

    var tms = items.timemaps;

    var keys = tms ? Object.keys(tms) : 0;
    var uriPluralityString = keys.length === 1 ? 'URI' : 'URIs';

    if(keys.length) {
		$('#cachedTimemaps').append(tmDropdownString);
		for(var tm = 0; tm < keys.length; tm++) {
		  var originalURI = tms[keys[tm]].original_uri;
		  $('#cachedTimemaps').append('<option>' + originalURI + '</option>');
		}
		enableRemoveButtons(false,'#removeAllTMsFromCache');
		$('#cachedTimemaps').change(enableRemoveButtonsBasedOnDropdown);
	}else {
	    $('#cachedTimemaps').append(tmDropdownNoTimemapsString);
	    enableRemoveButtons(true, '#cachedTimemaps, #removeAllTMsFromCache');
	}
	enableRemoveButtonsBasedOnDropdown();
  });
}

function updateMementoCount() {
  chrome.storage.local.get('timemaps',function(items) {
	$('#mementoCount').html(items.timemaps[$('#cachedTimemaps').val()].mementos.list.length + ' mementos available');
  });
}

function resetMementoCount() {
  $('#mementoCount').html('');
}

function enableRemoveButtons(disable, additionalIdsIn) {
  var additionalIds = '';
  if(additionalIdsIn) {
    additionalIds = ',' + additionalIdsIn;
  }
  var buttonIds = '#removeSelectedTMFromCache, #removeSelectedTMFromCacheAndBlacklist' + additionalIds;
  $(buttonIds).prop('disabled', disable);
}

function enableRemoveButtonsBasedOnDropdown() {
  var selectedIndex = $(this).find('option:selected').index();
  if(selectedIndex > 0) { // -1 would be valid with the verbose conditional
    enableRemoveButtons(false);
    updateMementoCount();
  }else { // selected index is 0, disable
    enableRemoveButtons(true);
    resetMementoCount();
  }
}

function removeTMFromCache(originalURI) {
  chrome.storage.local.get('timemaps', function(items) {
    var tms = items.timemaps;
    delete tms[originalURI];
    chrome.storage.local.set({'timemaps':tms},
      function() {
        console.log('Cache updated, updating UI');
        $('#cachedTimemaps').empty();
        populatedCachedTimeMapsUI();
      }
    );
  });
}

document.addEventListener('DOMContentLoaded', restore_options);
document.addEventListener('DOMContentLoaded', createAddURIBinder);
document.addEventListener('DOMContentLoaded', populatedCachedTimeMapsUI);

$('#removeSelectedTMFromCache').click(function() {
  var oURI = $('#cachedTimemaps option:selected').text();
  console.log(oURI);
  removeTMFromCache(oURI);
});

$('#removeAllTMsFromCache').click(function() {
    chrome.storage.local.set({'timemaps':{}},
      function() {
        console.log('Remove all cached TMs');
        $('#cachedTimemaps').empty();
        populatedCachedTimeMapsUI();
      }
    );
});

$('#saveBlacklist').click(saveBlacklist);
$('#removeBlacklist').click(removeBlacklist);
//document.getElementById('save').addEventListener('click',
//    save_options);
<commit_msg>Correctly populate cache TM options dropdown for TMs associated with a URI-M key. Closes #173.<commit_after>var tmDropdownString = '<option>  ↓ Mink has TimeMaps for... ↓</option>';
var tmDropdownNoTimemapsString = '<option>--- No TimeMaps available ---</option>';

function restore_options(){
    chrome.storage.local.get('blacklist', function(items) {
      $(items.blacklist).each(function(i, v){
        $("#options").append(getListItemHTML(v, 'glyphicon-remove'));
      });
      updateSaveButtonStatus();
      updateRemoveAllBlacklistButtonStatus();

      $(".remove").click(function(){
        if($(this).hasClass('glyphicon-remove')){
          var uriToStrike = $(this).parent().text();
          $(this).parent().addClass("strike");
          $(this).toggleClass('glyphicon-remove glyphicon-ok');
        }else {
          $(this).toggleClass('glyphicon-ok glyphicon-remove');
          $(this).parent().removeClass("strike");
        }
        updateSaveButtonStatus();
        updateRemoveAllBlacklistButtonStatus();

      });
    });
}

function getListItemHTML(uri, classIn, buttonText){
  if(!buttonText) {
    buttonText = '';
  }
  return '
<button class="btn btn-default btn-xs glyphicon ' + classIn + ' remove" type="button">' + buttonText + '</button>' + uri + '
';
}

function removeBlacklist() {
  chrome.storage.local.set({'blacklist': []});
}

function saveBlacklist(){
  var blacklistJSON = {};
  var uris = [];
  $('.newEntry span').each(function(){
    uris.push($(this).text());
  });
  blacklistJSON.blacklist = uris;
  chrome.storage.local.set(blacklistJSON);
  $('.newEntry').removeClass('newEntry'); // Disable indicator for unsaved data
  updateSaveButtonStatus();
}

function updateSaveButtonStatus(){
  var saveBlacklistButton = $('#saveBlacklist');
  if($('.glyphicon-ok').length > 0 || $('.newEntry').length > 0) {
    console.log('a');
    saveBlacklistButton.removeAttr('disabled').removeClass('disabled');
  }else {
    console.log('b');
    saveBlacklistButton.attr('disabled','disabled').addClass('disabled');
  }
}

function updateRemoveAllBlacklistButtonStatus() {
  var removeBlacklistButton = $('#removeBlacklist');
  console.log($('#options li').length);
  console.log($('#options li'));
  if($('#options li').length > 0) {
    removeBlacklistButton.removeAttr('disabled').removeClass('disabled');
  }else {
    removeBlacklistButton.attr('disabled','disabled').addClass('disabled');
  }
}

function createAddURIBinder(){
    $("#add").click(function(){
      addMinkBlacklistToBeSavedLI();
      bindAddBlacklistEntryUI();
    });
}

function bindAddBlacklistEntryUI() {
  $('.uriTextField').keyup(function() {
    var uriFieldValue = $(this).val();
    if(uriFieldValue.length == 0) {
      $(this).parent().find('button.addToBlacklist').attr('disabled',true);
    }else {
      $(this).parent().find('button.addToBlacklist').removeAttr('disabled');
    }
  });
  $('.addToBlacklist').click(addToBlacklistToBeSaved);
  $('.cancelAddToBlacklist').click(removeFromBlacklistToBeSaved);
}

function addMinkBlacklistToBeSavedLI(valIn) {
  if(!valIn) {
    valIn = '';
  }
  $("#options").prepend('
<input type="text" placeholder="http://"  class="uriTextField" id="newURI" "' + valIn + '"/><button class="addToBlacklist" disabled>Add to Blacklist</button><button class="cancelAddToBlacklist">Cancel</button>
');
}

function addToBlacklistToBeSaved() {
  var uri = $(this).parent().find('.uriTextField').val();
  if(uri.substr(0,4) !== 'http') {
    uri = 'http://' + uri;
  }

  $(this).parent().replaceWith(getListItemHTML(uri, 'glyphicon-remove newItem'));
  $('.newItem').click(removeEntry);
  $('.newItem').removeClass('newItem').parent().addClass('newEntry');
  // $('.newEntry').append('<button  class="btn btn-default btn-xs glyphicon glyphicon-chevron-left" style="font-size: 12px; margin-left: 1.0em;">Nevermind</button>');
  updateSaveButtonStatus();
}

function removeFromBlacklistToBeSaved() {
  $(this).parent().remove();
}

function removeEntry() {
  $(this).parent().remove();
  updateSaveButtonStatus();
}

function populatedCachedTimeMapsUI() {
  chrome.storage.local.get('timemaps',function(items) {
    console.log('items in the TM localstorage');
    console.log(items);

    var tms = items.timemaps;

    var keys = tms ? Object.keys(tms) : 0;
    var uriPluralityString = keys.length === 1 ? 'URI' : 'URIs';

    if(keys.length) {
		$('#cachedTimemaps').append(tmDropdownString);
		for(var tm = 0; tm < keys.length; tm++) {
		  var originalURI = tms[keys[tm]].original_uri;
		  if(!tms[keys[tm]].original_uri) {
		    originalURI = keys[tm];
		  }
		  $('#cachedTimemaps').append('<option>' + originalURI + '</option>');
		}
		enableRemoveButtons(false,'#removeAllTMsFromCache');
		$('#cachedTimemaps').change(enableRemoveButtonsBasedOnDropdown);
	}else {
	    $('#cachedTimemaps').append(tmDropdownNoTimemapsString);
	    enableRemoveButtons(true, '#cachedTimemaps, #removeAllTMsFromCache');
	}
	enableRemoveButtonsBasedOnDropdown();
  });
}

function updateMementoCount() {
  chrome.storage.local.get('timemaps',function(items) {
	$('#mementoCount').html(items.timemaps[$('#cachedTimemaps').val()].mementos.list.length + ' mementos available');
  });
}

function resetMementoCount() {
  $('#mementoCount').html('');
}

function enableRemoveButtons(disable, additionalIdsIn) {
  var additionalIds = '';
  if(additionalIdsIn) {
    additionalIds = ',' + additionalIdsIn;
  }
  var buttonIds = '#removeSelectedTMFromCache, #removeSelectedTMFromCacheAndBlacklist' + additionalIds;
  $(buttonIds).prop('disabled', disable);
}

function enableRemoveButtonsBasedOnDropdown() {
  var selectedIndex = $(this).find('option:selected').index();
  if(selectedIndex > 0) { // -1 would be valid with the verbose conditional
    enableRemoveButtons(false);
    updateMementoCount();
  }else { // selected index is 0, disable
    enableRemoveButtons(true);
    resetMementoCount();
  }
}

function removeTMFromCache(originalURI) {
  chrome.storage.local.get('timemaps', function(items) {
    var tms = items.timemaps;
    delete tms[originalURI];
    chrome.storage.local.set({'timemaps':tms},
      function() {
        console.log('Cache updated, updating UI');
        $('#cachedTimemaps').empty();
        populatedCachedTimeMapsUI();
      }
    );
  });
}

document.addEventListener('DOMContentLoaded', restore_options);
document.addEventListener('DOMContentLoaded', createAddURIBinder);
document.addEventListener('DOMContentLoaded', populatedCachedTimeMapsUI);

$('#removeSelectedTMFromCache').click(function() {
  var oURI = $('#cachedTimemaps option:selected').text();
  console.log(oURI);
  removeTMFromCache(oURI);
});

$('#removeAllTMsFromCache').click(function() {
    chrome.storage.local.set({'timemaps':{}},
      function() {
        console.log('Remove all cached TMs');
        $('#cachedTimemaps').empty();
        populatedCachedTimeMapsUI();
      }
    );
});

$('#saveBlacklist').click(saveBlacklist);
$('#removeBlacklist').click(removeBlacklist);
//document.getElementById('save').addEventListener('click',
//    save_options);
<|endoftext|>


<commit_before>'use strict';

var request = require('superagent');
var Q = require('q');
var Events = require('./../events');
var utils = require('./../utils');

/**
 * No-Op callback
 */
function noop() {}

var lastCookies = {};
var lastCookieString = '';

/**
 * HttpClient
 *
 * A HTTP request abstraction layer to be used in node.js / browsers environments.
 *
 * @class
 * @memberof CamSDK.client
 */
var HttpClient = function(config) {
  config = config || {};

  config.headers = config.headers || {};
  if (!config.headers.Accept) {
    config.headers.Accept = 'application/hal+json, application/json; q=0.5';
  }

  if (!config.baseUrl) {
    throw new Error('HttpClient needs a `baseUrl` configuration property.');
  }

  Events.attach(this);

  this.config = config;
};

function cookies() {
  if (document && document.cookie !== lastCookieString) {
    lastCookieString = document.cookie;
    lastCookies = {};

    var cookieArray = lastCookieString.split('; ');

    for (var i = 0; i < cookieArray.length; i++) {
      var cookie = cookieArray[i];
      var index = cookie.indexOf('=');

      if (index > 0) {
        var name = unescape(cookie.substring(0, index));
        if (lastCookies[name] === undefined) {
          lastCookies[name] = unescape(cookie.substring(index + 1));
        }
      }
    }
  }

  return lastCookies;
}

function prepareRequestHeaders(headers) {
  // creates a deep copy of the headers object
  var token = (cookies() || {})['XSRF-TOKEN'];

  headers = JSON.parse(JSON.stringify(headers));

  if (token) {
    headers['X-XSRF-TOKEN'] = token;
  }

  return headers;
}

function end(self, done, deferred) {
  done = done || noop;
  return function(err, response) {
    // TODO: investigate the possible problems related to response without content
    if (err || (!response.ok && !response.noContent)) {
      err = err || response.error || new Error('The '+ response.req.method +' request on '+ response.req.url +' failed');
      if (response && response.body) {
        if (response.body.message) {
          err.message = response.body.message;
        }
      }
      self.trigger('error', err);
      if(deferred) {deferred.reject(err);}
      return done(err);
    }

    // superagent puts the parsed data into a property named "body"
    // and the "raw" content in property named "text"
    // and.. it does not parse the response if it does not have
    // the "application/json" type.
    if (response.type === 'application/hal+json') {
      if (!response.body || Object.keys(response.body).length === 0) {
        response.body = JSON.parse(response.text);
      }

      // and process embedded resources
      response.body = utils.solveHALEmbedded(response.body);
    }

    if(deferred) {deferred.resolve(response.body ? response.body : (response.text ? response.text : ''));}
    done(null, response.body ? response.body : (response.text ? response.text : ''));
  };
}

/**
 * Performs a POST HTTP request
 */
HttpClient.prototype.post = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');
  var req = request.post(url);

  // Buffer object is only available in node.js environement
  if (typeof Buffer !== 'undefined') {
    Object.keys(options.fields || {}).forEach(function(field) {
      req.field(field, options.fields[field]);
    });
    (options.attachments || []).forEach(function(file, idx) {
      req.attach('data_'+idx, new Buffer(file.content), file.name);
    });
  }
  else if (!!options.fields || !!options.attachments) {
    var err = new Error('Multipart request is only supported in node.js environement.');
    done(err);
    return deferred.reject(err);
  }

  var headers = prepareRequestHeaders(this.config.headers);

  req
    .set(headers)
    .send(options.data || {})
    .query(options.query || {});

  req.end(end(self, done, deferred));
  return deferred.promise;
};

/**
 * Performs a GET HTTP request
 */
HttpClient.prototype.get = function(path, options) {
  var url = this.config.baseUrl + (path ? '/'+ path : '');
  return this.load(url, options);
};

/**
 * Loads a resource using http GET
 */
HttpClient.prototype.load = function(url, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();

  var accept = options.accept || this.config.headers.Accept;

  var headers = prepareRequestHeaders(options.headers || this.config.headers);

  var req = request
    .get(url)
    .set(headers)
    .set('Accept', accept)
    .query(options.data || {});

  req.end(end(self, done, deferred));
  return deferred.promise;
};

/**
 * Performs a PUT HTTP request
 */
HttpClient.prototype.put = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');

  var headers = prepareRequestHeaders(options.headers || this.config.headers);

  var req = request
    .put(url)
    .set(headers)
    .send(options.data || {});

  req.end(end(self, done,deferred));
  return deferred.promise;
};

/**
 * Performs a DELETE HTTP request
 */
HttpClient.prototype.del = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');

  var headers = prepareRequestHeaders(options.headers || this.config.headers);

  var req = request
    .del(url)
    .set(headers)
    .send(options.data || {});

  req.end(end(self, done, deferred));
  return deferred.promise;
};

/**
 * Performs a OPTIONS HTTP request
 */
HttpClient.prototype.options = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');

  var headers = prepareRequestHeaders(options.headers || this.config.headers);

  var req = request('OPTIONS', url)
    .set(headers);

  req.end(end(self, done, deferred));
  return deferred.promise;
};

module.exports = HttpClient;
<commit_msg>chore(csrf): get rid of csrf handling<commit_after>'use strict';

var request = require('superagent');
var Q = require('q');
var Events = require('./../events');
var utils = require('./../utils');

/**
 * No-Op callback
 */
function noop() {}

/**
 * HttpClient
 *
 * A HTTP request abstraction layer to be used in node.js / browsers environments.
 *
 * @class
 * @memberof CamSDK.client
 */
var HttpClient = function(config) {
  config = config || {};

  config.headers = config.headers || {};
  if (!config.headers.Accept) {
    config.headers.Accept = 'application/hal+json, application/json; q=0.5';
  }

  if (!config.baseUrl) {
    throw new Error('HttpClient needs a `baseUrl` configuration property.');
  }

  Events.attach(this);

  this.config = config;
};

function end(self, done, deferred) {
  done = done || noop;
  return function(err, response) {
    // TODO: investigate the possible problems related to response without content
    if (err || (!response.ok && !response.noContent)) {
      err = err || response.error || new Error('The '+ response.req.method +' request on '+ response.req.url +' failed');
      if (response && response.body) {
        if (response.body.message) {
          err.message = response.body.message;
        }
      }
      self.trigger('error', err);
      if(deferred) {deferred.reject(err);}
      return done(err);
    }

    // superagent puts the parsed data into a property named "body"
    // and the "raw" content in property named "text"
    // and.. it does not parse the response if it does not have
    // the "application/json" type.
    if (response.type === 'application/hal+json') {
      if (!response.body || Object.keys(response.body).length === 0) {
        response.body = JSON.parse(response.text);
      }

      // and process embedded resources
      response.body = utils.solveHALEmbedded(response.body);
    }

    if(deferred) {deferred.resolve(response.body ? response.body : (response.text ? response.text : ''));}
    done(null, response.body ? response.body : (response.text ? response.text : ''));
  };
}

/**
 * Performs a POST HTTP request
 */
HttpClient.prototype.post = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');
  var req = request.post(url);

  var headers = options.headers || this.config.headers;
  headers.Accept = headers.Accept || this.config.headers.Accept;

  // Buffer object is only available in node.js environement
  if (typeof Buffer !== 'undefined') {
    Object.keys(options.fields || {}).forEach(function(field) {
      req.field(field, options.fields[field]);
    });
    (options.attachments || []).forEach(function(file, idx) {
      req.attach('data_'+idx, new Buffer(file.content), file.name);
    });
  }
  else if (!!options.fields || !!options.attachments) {
    var err = new Error('Multipart request is only supported in node.js environement.');
    done(err);
    return deferred.reject(err);
  }

  req
    .set(headers)
    .send(options.data || {})
    .query(options.query || {});

  req.end(end(self, done, deferred));
  return deferred.promise;
};

/**
 * Performs a GET HTTP request
 */
HttpClient.prototype.get = function(path, options) {
  var url = this.config.baseUrl + (path ? '/'+ path : '');
  return this.load(url, options);
};

/**
 * Loads a resource using http GET
 */
HttpClient.prototype.load = function(url, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();

  var headers = options.headers || this.config.headers;
  var accept = options.accept || headers.Accept || this.config.headers.Accept;

  var req = request
    .get(url)
    .set(headers)
    .set('Accept', accept)
    .query(options.data || {});

  req.end(end(self, done, deferred));
  return deferred.promise;
};

/**
 * Performs a PUT HTTP request
 */
HttpClient.prototype.put = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');

  var headers = options.headers || this.config.headers;
  headers.Accept = headers.Accept || this.config.headers.Accept;

  var req = request
    .put(url)
    .set(headers)
    .send(options.data || {});

  req.end(end(self, done,deferred));
  return deferred.promise;
};

/**
 * Performs a DELETE HTTP request
 */
HttpClient.prototype.del = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');

  var headers = options.headers || this.config.headers;
  headers.Accept = headers.Accept || this.config.headers.Accept;

  var req = request
    .del(url)
    .set(headers)
    .send(options.data || {});

  req.end(end(self, done, deferred));
  return deferred.promise;
};

/**
 * Performs a OPTIONS HTTP request
 */
HttpClient.prototype.options = function(path, options) {
  options = options || {};
  var done = options.done || noop;
  var self = this;
  var deferred = Q.defer();
  var url = this.config.baseUrl + (path ? '/'+ path : '');

  var headers = options.headers || this.config.headers;
  headers.Accept = headers.Accept || this.config.headers.Accept;

  var req = request('OPTIONS', url)
    .set(headers);

  req.end(end(self, done, deferred));
  return deferred.promise;
};

module.exports = HttpClient;
<|endoftext|>


<commit_before>//fgnass.github.com/spin.js#v2.0.1
!function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define(b):a.Spinner=b()}(this,function(){"use strict";function a(a,b){var c,d=document.createElement(a||"div");for(c in b)d[c]=b[c];return d}function b(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function c(a,b,c,d){var e=["opacity",b,~~(100*a),c,d].join("-"),f=.01+c/d*100,g=Math.max(1-(1-a)/b*(100-f),a),h=j.substring(0,j.indexOf("Animation")).toLowerCase(),i=h&&"-"+h+"-"||"";return l[e]||(m.insertRule("@"+i+"keyframes "+e+"{0%{opacity:"+g+"}"+f+"%{opacity:"+a+"}"+(f+.01)+"%{opacity:1}"+(f+b)%100+"%{opacity:"+a+"}100%{opacity:"+g+"}}",m.cssRules.length),l[e]=1),e}function d(a,b){var c,d,e=a.style;for(b=b.charAt(0).toUpperCase()+b.slice(1),d=0;d<k.length;d++)if(c=k[d]+b,void 0!==e[c])return c;return void 0!==e[b]?b:void 0}function e(a,b){for(var c in b)a.style[d(a,c)||c]=b[c];return a}function f(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)void 0===a[d]&&(a[d]=c[d])}return a}function g(a,b){return"string"==typeof a?a:a[b%a.length]}function h(a){this.opts=f(a||{},h.defaults,n)}function i(){function c(b,c){return a("<"+b+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',c)}m.addRule(".spin-vml","behavior:url(#default#VML)"),h.prototype.lines=function(a,d){function f(){return e(c("group",{coordsize:k+" "+k,coordorigin:-j+" "+-j}),{width:k,height:k})}function h(a,h,i){b(m,b(e(f(),{rotation:360/d.lines*a+"deg",left:~~h}),b(e(c("roundrect",{arcsize:d.corners}),{width:j,height:d.width,left:d.radius,top:-d.width>>1,filter:i}),c("fill",{color:g(d.color,a),opacity:d.opacity}),c("stroke",{opacity:0}))))}var i,j=d.length+d.width,k=2*j,l=2*-(d.width+d.length)+"px",m=e(f(),{position:"absolute",top:l,left:l});if(d.shadow)for(i=1;i<=d.lines;i++)h(i,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(i=1;i<=d.lines;i++)h(i);return b(a,m)},h.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}var j,k=["webkit","Moz","ms","O"],l={},m=function(){var c=a("style",{type:"text/css"});return b(document.getElementsByTagName("head")[0],c),c.sheet||c.styleSheet}(),n={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"50%",left:"50%",position:"absolute"};h.defaults={},f(h.prototype,{spin:function(b){this.stop();{var c=this,d=c.opts,f=c.el=e(a(0,{className:d.className}),{position:d.position,width:0,zIndex:d.zIndex});d.radius+d.length+d.width}if(e(f,{left:d.left,top:d.top}),b&&b.insertBefore(f,b.firstChild||null),f.setAttribute("role","progressbar"),c.lines(f,c.opts),!j){var g,h=0,i=(d.lines-1)*(1-d.direction)/2,k=d.fps,l=k/d.speed,m=(1-d.opacity)/(l*d.trail/100),n=l/d.lines;!function o(){h++;for(var a=0;a<d.lines;a++)g=Math.max(1-(h+(d.lines-a)*n)%l*m,d.opacity),c.opacity(f,a*d.direction+i,g,d);c.timeout=c.el&&setTimeout(o,~~(1e3/k))}()}return c},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=void 0),this},lines:function(d,f){function h(b,c){return e(a(),{position:"absolute",width:f.length+f.width+"px",height:f.width+"px",background:b,boxShadow:c,transformOrigin:"left",transform:"rotate("+~~(360/f.lines*k+f.rotate)+"deg) translate("+f.radius+"px,0)",borderRadius:(f.corners*f.width>>1)+"px"})}for(var i,k=0,l=(f.lines-1)*(1-f.direction)/2;k<f.lines;k++)i=e(a(),{position:"absolute",top:1+~(f.width/2)+"px",transform:f.hwaccel?"translate3d(0,0,0)":"",opacity:f.opacity,animation:j&&c(f.opacity,f.trail,l+k*f.direction,f.lines)+" "+1/f.speed+"s linear infinite"}),f.shadow&&b(i,e(h("#000","0 0 4px #000"),{top:"2px"})),b(d,b(i,h(g(f.color,k),"0 0 1px rgba(0,0,0,.1)")));return d},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}});var o=e(a("group"),{behavior:"url(#default#VML)"});return!d(o,"transform")&&o.adj?i():j=d(o,"animation"),h});

$.fn.romoIndicator = function() {
  return $.map(this, function(element) {
    return new RomoIndicator(element);
  });
}

var RomoIndicator = function(element) {
  this.elem = $(element);
  this.spinnerOpts = {
    lines: 11, // The number of lines to draw
    width: 2, // The line thickness
    length: parseInt(this.elem.css('font-size')) / 2, // The length of each line
    radius: parseInt(this.elem.css('font-size')) / 3, // The radius of the inner circle
    corners: 1, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    direction: 1, // 1: clockwise, -1: counterclockwise
    color: this.elem.css('color'), // #rgb or #rrggbb or array of colors
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 1000, // The z-index (defaults to 2000000000)
    top: '50%', // Top position relative to parent
    left: '50%'// Left position relative to parent
  };

  this.doInit();
  this.spinner = new Spinner(this.spinnerOpts);

  this.elemHtml = this.elem.html();
  this.elem.css({
    'position': 'relative',
    'width':    this.elem.css('width'),
    'height':   this.elem.css('height'),
  });
  this.elem.on('indicator:triggerStart', $.proxy(this.onStart, this));
  this.elem.on('indicator:triggerStop', $.proxy(this.onStop, this));

  $(window).on("pageshow", $.proxy(function(e) {
    this.elem.trigger('indicator:triggerStop');
  }, this));

  this.elem.trigger('indicator:ready', [this]);
}

RomoIndicator.prototype.doInit = function() {
  // override as needed
}

RomoIndicator.prototype.onStart = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  this.doStart();
}

RomoIndicator.prototype.onStop = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  this.doStop();
}

RomoIndicator.prototype.doStart = function() {
  this.elem.html('');
  this.spinner.spin(this.elem[0]);
  this.elem.trigger('indicator:start', [this]);
}

RomoIndicator.prototype.doStop = function() {
  this.spinner.stop();
  this.elem.html(this.elemHtml);
  this.elem.trigger('indicator:stop', [this]);
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-indicator-auto="true"]').romoIndicator();
});
<commit_msg>indicator js: add option for disabling stop on pageshow<commit_after>//fgnass.github.com/spin.js#v2.0.1
!function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define(b):a.Spinner=b()}(this,function(){"use strict";function a(a,b){var c,d=document.createElement(a||"div");for(c in b)d[c]=b[c];return d}function b(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function c(a,b,c,d){var e=["opacity",b,~~(100*a),c,d].join("-"),f=.01+c/d*100,g=Math.max(1-(1-a)/b*(100-f),a),h=j.substring(0,j.indexOf("Animation")).toLowerCase(),i=h&&"-"+h+"-"||"";return l[e]||(m.insertRule("@"+i+"keyframes "+e+"{0%{opacity:"+g+"}"+f+"%{opacity:"+a+"}"+(f+.01)+"%{opacity:1}"+(f+b)%100+"%{opacity:"+a+"}100%{opacity:"+g+"}}",m.cssRules.length),l[e]=1),e}function d(a,b){var c,d,e=a.style;for(b=b.charAt(0).toUpperCase()+b.slice(1),d=0;d<k.length;d++)if(c=k[d]+b,void 0!==e[c])return c;return void 0!==e[b]?b:void 0}function e(a,b){for(var c in b)a.style[d(a,c)||c]=b[c];return a}function f(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)void 0===a[d]&&(a[d]=c[d])}return a}function g(a,b){return"string"==typeof a?a:a[b%a.length]}function h(a){this.opts=f(a||{},h.defaults,n)}function i(){function c(b,c){return a("<"+b+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',c)}m.addRule(".spin-vml","behavior:url(#default#VML)"),h.prototype.lines=function(a,d){function f(){return e(c("group",{coordsize:k+" "+k,coordorigin:-j+" "+-j}),{width:k,height:k})}function h(a,h,i){b(m,b(e(f(),{rotation:360/d.lines*a+"deg",left:~~h}),b(e(c("roundrect",{arcsize:d.corners}),{width:j,height:d.width,left:d.radius,top:-d.width>>1,filter:i}),c("fill",{color:g(d.color,a),opacity:d.opacity}),c("stroke",{opacity:0}))))}var i,j=d.length+d.width,k=2*j,l=2*-(d.width+d.length)+"px",m=e(f(),{position:"absolute",top:l,left:l});if(d.shadow)for(i=1;i<=d.lines;i++)h(i,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(i=1;i<=d.lines;i++)h(i);return b(a,m)},h.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}var j,k=["webkit","Moz","ms","O"],l={},m=function(){var c=a("style",{type:"text/css"});return b(document.getElementsByTagName("head")[0],c),c.sheet||c.styleSheet}(),n={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"50%",left:"50%",position:"absolute"};h.defaults={},f(h.prototype,{spin:function(b){this.stop();{var c=this,d=c.opts,f=c.el=e(a(0,{className:d.className}),{position:d.position,width:0,zIndex:d.zIndex});d.radius+d.length+d.width}if(e(f,{left:d.left,top:d.top}),b&&b.insertBefore(f,b.firstChild||null),f.setAttribute("role","progressbar"),c.lines(f,c.opts),!j){var g,h=0,i=(d.lines-1)*(1-d.direction)/2,k=d.fps,l=k/d.speed,m=(1-d.opacity)/(l*d.trail/100),n=l/d.lines;!function o(){h++;for(var a=0;a<d.lines;a++)g=Math.max(1-(h+(d.lines-a)*n)%l*m,d.opacity),c.opacity(f,a*d.direction+i,g,d);c.timeout=c.el&&setTimeout(o,~~(1e3/k))}()}return c},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=void 0),this},lines:function(d,f){function h(b,c){return e(a(),{position:"absolute",width:f.length+f.width+"px",height:f.width+"px",background:b,boxShadow:c,transformOrigin:"left",transform:"rotate("+~~(360/f.lines*k+f.rotate)+"deg) translate("+f.radius+"px,0)",borderRadius:(f.corners*f.width>>1)+"px"})}for(var i,k=0,l=(f.lines-1)*(1-f.direction)/2;k<f.lines;k++)i=e(a(),{position:"absolute",top:1+~(f.width/2)+"px",transform:f.hwaccel?"translate3d(0,0,0)":"",opacity:f.opacity,animation:j&&c(f.opacity,f.trail,l+k*f.direction,f.lines)+" "+1/f.speed+"s linear infinite"}),f.shadow&&b(i,e(h("#000","0 0 4px #000"),{top:"2px"})),b(d,b(i,h(g(f.color,k),"0 0 1px rgba(0,0,0,.1)")));return d},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}});var o=e(a("group"),{behavior:"url(#default#VML)"});return!d(o,"transform")&&o.adj?i():j=d(o,"animation"),h});

$.fn.romoIndicator = function() {
  return $.map(this, function(element) {
    return new RomoIndicator(element);
  });
}

var RomoIndicator = function(element) {
  this.elem = $(element);
  this.spinnerOpts = {
    lines: 11, // The number of lines to draw
    width: 2, // The line thickness
    length: parseInt(this.elem.css('font-size')) / 2, // The length of each line
    radius: parseInt(this.elem.css('font-size')) / 3, // The radius of the inner circle
    corners: 1, // Corner roundness (0..1)
    rotate: 0, // The rotation offset
    direction: 1, // 1: clockwise, -1: counterclockwise
    color: this.elem.css('color'), // #rgb or #rrggbb or array of colors
    speed: 1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 1000, // The z-index (defaults to 2000000000)
    top: '50%', // Top position relative to parent
    left: '50%'// Left position relative to parent
  };

  this.doInit();
  this.spinner = new Spinner(this.spinnerOpts);

  this.elemHtml = this.elem.html();
  this.elem.css({
    'position': 'relative',
    'width':    this.elem.css('width'),
    'height':   this.elem.css('height'),
  });
  this.elem.on('indicator:triggerStart', $.proxy(this.onStart, this));
  this.elem.on('indicator:triggerStop', $.proxy(this.onStop, this));

  if (this.elem.data('romo-indicator-stop-on-pageshow') !== false) {
    $(window).on("pageshow", $.proxy(function(e) {
      this.elem.trigger('indicator:triggerStop');
    }, this));
  }

  this.elem.trigger('indicator:ready', [this]);
}

RomoIndicator.prototype.doInit = function() {
  // override as needed
}

RomoIndicator.prototype.onStart = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  this.doStart();
}

RomoIndicator.prototype.onStop = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  this.doStop();
}

RomoIndicator.prototype.doStart = function() {
  this.elem.html('');
  this.spinner.spin(this.elem[0]);
  this.elem.trigger('indicator:start', [this]);
}

RomoIndicator.prototype.doStop = function() {
  this.spinner.stop();
  this.elem.html(this.elemHtml);
  this.elem.trigger('indicator:stop', [this]);
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-indicator-auto="true"]').romoIndicator();
});
<|endoftext|>


<commit_before>'use strict';

var consts = require('../../constants');

var ID_PATTERN = /^[a-f\d]{24}$/;

function isId(value) {
    //TODO: why did we need tht length check?
    return value && ID_PATTERN.test(value) && value.length === 24;
}

function configure (app, wares, ctx) {
  var express = require('express'),
    api = express.Router( );

  // invoke common middleware
  api.use(wares.sendJSONStatus);
  // text body types get handled as raw buffer stream
  api.use(wares.bodyParser.raw( ));
  // json body types get handled as parsed json
  api.use(wares.bodyParser.json( ));
  // also support url-encoded content-type
  api.use(wares.bodyParser.urlencoded({ extended: true }));

  api.use(ctx.authorization.isPermitted('api:devicestatus:read'));

  // List settings available
  api.get('/devicestatus/', function(req, res) {
    var q = req.query;
    if (!q.count) {
      q.count = 10;
    }
    ctx.devicestatus.list(q, function (err, results) {
      return res.json(results);
    });
  });

  function config_authed (app, api, wares, ctx) {

    function doPost (req, res) {
      var obj = req.body;
      ctx.devicestatus.create(obj, function (err, created) {
        if (err) {
          res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
        } else {
          res.json(created);
        }
      });
    }

    api.post('/devicestatus/', ctx.authorization.isPermitted('api:devicestatus:create'), doPost);

    /**
     * @function delete_records
     * Delete devicestatus.  The query logic works the same way as find/list.  This
     * endpoint uses same search logic to remove records from the database.
     */
    function delete_records(req, res, next) {
      var query = req.query;
      if (!query.count) {
        query.count = 10
      }

      console.log('Delete records with query: ', query);

      // remove using the query
      ctx.devicestatus.remove(query, function(err, stat) {
        if (err) {
          console.log('devicestatus delete error: ', err);
          return next(err);
        }
        // yield some information about success of operation
        res.json(stat);

        console.log('devicestatus records deleted');

        return next();
      });
    }

    api.delete('/devicestatus/:id', ctx.authorization.isPermitted('api:devicestatus:delete'), function(req, res, next) {
      if (!req.query.find) {
        req.query.find = {
          _id: req.params.id
        };
      } else {
        req.query.find._id = req.params.id;
      }

      if (req.query.find._id === '*') {
        // match any record id
        delete req.query.find._id;
      }
      next();
    }, delete_records);

    // delete record that match query
    api.delete('/devicestatus/', ctx.authorization.isPermitted('api:devicestatus:delete'), delete_records);
  }

  if (app.enabled('api') || true /*TODO: auth disabled for quick UI testing...*/) {
    config_authed(app, api, wares, ctx);
  }

  return api;
}

module.exports = configure;

<commit_msg>Removed unused function.<commit_after>'use strict';

var consts = require('../../constants');

function configure (app, wares, ctx) {
  var express = require('express'),
    api = express.Router( );

  // invoke common middleware
  api.use(wares.sendJSONStatus);
  // text body types get handled as raw buffer stream
  api.use(wares.bodyParser.raw( ));
  // json body types get handled as parsed json
  api.use(wares.bodyParser.json( ));
  // also support url-encoded content-type
  api.use(wares.bodyParser.urlencoded({ extended: true }));

  api.use(ctx.authorization.isPermitted('api:devicestatus:read'));

  // List settings available
  api.get('/devicestatus/', function(req, res) {
    var q = req.query;
    if (!q.count) {
      q.count = 10;
    }
    ctx.devicestatus.list(q, function (err, results) {
      return res.json(results);
    });
  });

  function config_authed (app, api, wares, ctx) {

    function doPost (req, res) {
      var obj = req.body;
      ctx.devicestatus.create(obj, function (err, created) {
        if (err) {
          res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err);
        } else {
          res.json(created);
        }
      });
    }

    api.post('/devicestatus/', ctx.authorization.isPermitted('api:devicestatus:create'), doPost);

    /**
     * @function delete_records
     * Delete devicestatus.  The query logic works the same way as find/list.  This
     * endpoint uses same search logic to remove records from the database.
     */
    function delete_records(req, res, next) {
      var query = req.query;
      if (!query.count) {
        query.count = 10
      }

      console.log('Delete records with query: ', query);

      // remove using the query
      ctx.devicestatus.remove(query, function(err, stat) {
        if (err) {
          console.log('devicestatus delete error: ', err);
          return next(err);
        }
        // yield some information about success of operation
        res.json(stat);

        console.log('devicestatus records deleted');

        return next();
      });
    }

    api.delete('/devicestatus/:id', ctx.authorization.isPermitted('api:devicestatus:delete'), function(req, res, next) {
      if (!req.query.find) {
        req.query.find = {
          _id: req.params.id
        };
      } else {
        req.query.find._id = req.params.id;
      }

      if (req.query.find._id === '*') {
        // match any record id
        delete req.query.find._id;
      }
      next();
    }, delete_records);

    // delete record that match query
    api.delete('/devicestatus/', ctx.authorization.isPermitted('api:devicestatus:delete'), delete_records);
  }

  if (app.enabled('api') || true /*TODO: auth disabled for quick UI testing...*/) {
    config_authed(app, api, wares, ctx);
  }

  return api;
}

module.exports = configure;

<|endoftext|>


<commit_before>var fs = require('fs');
var classes = require('bespoke-classes');
var insertCss = require('insert-css');

module.exports = function() {
    var css = fs.readFileSync(__dirname + '/tmp/theme.css', 'utf8');
    insertCss(css, { prepend: true });

    return function(deck) {
	classes()(deck);

	//wrap the slides in additional div that scrolls up
	var parent = deck.parent;
	var content = document.createElement('div');
        content.className = 'bespoke-theme-terminal-content';
	while(parent.hasChildNodes()) content.appendChild(parent.firstChild);
	parent.appendChild(content);
    };
};
<commit_msg>added newline<commit_after>var fs = require('fs');
var classes = require('bespoke-classes');
var insertCss = require('insert-css');

module.exports = function() {
    var css = fs.readFileSync(__dirname + '/tmp/theme.css', 'utf8');
    insertCss(css, { prepend: true });

    return function(deck) {
	classes()(deck);

	//wrap the slides in additional div that scrolls up
	var parent = deck.parent;
	var content = document.createElement('div');
        content.className = 'bespoke-theme-terminal-content';
	while(parent.hasChildNodes()) content.appendChild(parent.firstChild);
	parent.appendChild(content);
    };
};
<|endoftext|>


<commit_before>
var path = require('path');
var at = require('../../ast').js;
var html_at = require('../../ast').html;

module.exports = function(flow){

  var packages = flow.js.packages;
  var queue = flow.files.queue;
  var fconsole = flow.console;

  // create package files
  //["dot",["name","this"],"__resource__"]

  // build source map
  var basisFile = flow.js.basisScript && flow.files.get(flow.js.basisScript);

  if (basisFile)
  {
    // inject resources
    var inserted = false;
    var resourceToc = [];
    var resTypeByFirstChar = {
      '[': 'array',
      '{': 'object',
      '"': 'string',
      'f': 'function'
    };

    fconsole.start('Build resource map');
    basisFile.ast = at.walk(basisFile.ast, {
      "dot": function(token){
        var expr = token[1];
        var name = at.resolveName(token, true);

        if (!inserted && name == 'this.__resources__' || name == 'global.__resources__')
        {
          inserted = true;
          return at.parse('0,' + (function(){
            var res = [];
            var resourceTypeWeight = {
              'json': 1,
              'template': 2,
              'script': 100
            };
            var stat = {};

            for (var jsRef in flow.js.resourceMap)
            {
              var file = flow.js.resourceMap[jsRef];

              if (!file.jsRefCount && file.type == 'template')
              {
                fconsole.log('[i] Drop resource:', file.relpath);
                continue;
              }

              var content = file.jsResourceContent != null
                ? file.jsResourceContent
                : file.outputContent || file.content;

              if (typeof content == 'function')
                content = content.toString().replace(/function\s+anonymous/, 'function');
              else
                content = JSON.stringify(content);

              if (!stat[file.type])
                stat[file.type] = { count: 0, size: 0 };

              stat[file.type].count++;
              stat[file.type].size += content.length;

              res.push([file, file.jsRef, content]);
            }

            fconsole.start('Stat:');
            for (var type in stat)
              fconsole.log('[' + type + '] ' + stat[type].size + ' bytes in ' + stat[type].count + ' resource(s)');
            fconsole.end();

            return '{\n' +
              res.sort(function(a, b){
                var wa = resourceTypeWeight[a[0].type] || 0;
                var wb = resourceTypeWeight[b[0].type] || 0;
                return wa > wb ? 1 : (wa < wb ? -1 : 0);
              }).map(function(item){
                resourceToc.push('[' + (resTypeByFirstChar[item[2].charAt(0)] || 'unknown') + '] ' + item[0].relpath + ' -> ' + item[1]);
                return '"' + item[1] + '":' + item[2]
              }).join(',\n') +
            '\n}';
          })())[1][0][1][2];
        }
      }
    });
    fconsole.endl();

    if (flow.js.globalVars)
      basisFile.ast[1].unshift(['var', flow.js.globalVars]);
  }

  for (var name in packages)
  {
    var package = packages[name];

    // log package file list
    fconsole.start('Package ' + name + ':');
    package.forEach(function(f){
      fconsole.log(f.relpath);
    });
    fconsole.endl();

    switch (package.layout){
      case 'basis':
        var isCoreFile = basisFile && flow.js.rootNSFile[name] === basisFile; //(flow.options.jsSingleFile || name == 'basis');
        var throwCodes = package.reduce(function(res, file){
          res.push.apply(res, file.throwCodes);
          return res;
        }, []);

        var packageFile = flow.files.add({
          type: 'script',
          outputFilename: name + '.js',
          outputContent:
            (isCoreFile ? '// resources (' + resourceToc.length + '):\n//  ' + resourceToc.join('\n//  ') + '\n//\n' : '') +
            (throwCodes.length ? '// throw codes:\n//  ' + throwCodes.map(function(item){ return item[0] + ' -> ' + at.translate(item[1]) }).join('\n//  ') + '\n//\n' : '') +
            wrapPackage(package.filter(function(file){ return file != basisFile }), flow, isCoreFile ? at.translate(basisFile.ast) : '')
        });

        packages[name].file = packageFile;

        if (isCoreFile)
        {
          packageFile.htmlNode = basisFile.htmlNode;
          delete basisFile.htmlNode;
        }

        break;

      default:
        var htmlNode = null;
        var packageFile = flow.files.add({
          type: 'script',
          outputFilename: name + '.js',
          outputContent: package.map(function(file){
            if (file.htmlNode)
            {
              if (!htmlNode)
                htmlNode = file.htmlNode;
              else
                html_at.removeToken(file.htmlNode, true);

              delete file.htmlNode;
            }

            return '//' + file.relpath + '\n' + file.outputContent;
          }).join(';\n\n') + ';'
        });

        packageFile.htmlNode = htmlNode;
        packages[name].file = packageFile;
    }
  }
}
module.exports.handlerName = '[js] Build packages';

//
// wrap package
//

function extractBuildContent(file){
  return '// ' + file.relpath + '\n' +
    '[' +
      '"' + file.namespace + '", function(basis, module, exports, resource, global, __dirname, __filename){' +
        file.outputContent +
      '}' +
    ']';
}

function extractSourceContent(file){
  return '//\n// ' + file.relpath + '\n//\n' +
    '{\n' +
    '  ns: "' + file.namespace + '",\n' +
    '  path: "' + path.dirname(file.relpath) + '/",\n' +
    '  fn: "' + file.basename + '",\n' +
    '  body: function(){\n' +
         file.outputContent + '\n' +
    '  }\n' +
    '}';
}

var packageWrapper = [
  "(function(){\n" +
  "'use strict';\n\n",

  "\n}).call(this);"
];

function wrapPackage(package, flow, contentPrepend){
  return !flow.options.jsBuildMode
    // source mode
    ? [
        '// filelist (' + package.length + '): \n//   ' + package.map(function(file){
          return file.relpath;
        }).join('\n//   ') + '\n',

        packageWrapper[0],
        contentPrepend,

        ';[\n',
          package.map(extractSourceContent).join(',\n'),
        '\n].forEach(' + function(module){
           var path = module.path;
           var fn = path + module.fn;
           var ns = basis.namespace(module.ns);
           ns.source_ = module.body.toString().replace(/^\s*\(?\s*function[^(]*\([^\)]*\)[^{]*\{|\}\s*\)?\s*$/g, '');
           ns.filename_ = module.path + module.fn;
           new Function('module, exports, global, __filename, __dirname, basis, resource',
             '/** @namespace ' + ns.path + ' */\n' + ns.source_ + '//@ sourceURL=' + fn
           ).call(ns, ns, ns.exports, this, fn, path, basis, function(url){ return basis.resource(path + url) });
           for (var key in ns.exports)
             if (key in ns == false)
               ns[key] = ns.exports[key];
         } + ', this)',

        packageWrapper[1]
      ].join('')
    // build mode
    : [
        '// filelist (' + package.length + '): \n//   ' + package.map(function(file){
          return file.relpath;
        }).join('\n//   ') + '\n',

        packageWrapper[0],
        contentPrepend,

        ';[\n',
          package.map(extractBuildContent).join(',\n'),
        '].forEach(' + function(module){
           var fn = module[1];
           var ns = basis.namespace(module[0]);
           // basis, module, exports, resource, global, __dirname, __filename
           fn.call(ns, basis, ns, ns.exports, basis.resource, this, "", "");
           for (var key in ns.exports)
             if (key in ns == false)
               ns[key] = ns.exports[key];
         } + ', this)',

        packageWrapper[1]
      ].join('');
}
<commit_msg>beautify basis.js source code if no pack mode<commit_after>
var path = require('path');
var at = require('../../ast').js;
var html_at = require('../../ast').html;

module.exports = function(flow){

  var packages = flow.js.packages;
  var queue = flow.files.queue;
  var fconsole = flow.console;

  // create package files
  //["dot",["name","this"],"__resource__"]

  // build source map
  var basisFile = flow.js.basisScript && flow.files.get(flow.js.basisScript);

  if (basisFile)
  {
    // inject resources
    var inserted = false;
    var resourceToc = [];
    var resTypeByFirstChar = {
      '[': 'array',
      '{': 'object',
      '"': 'string',
      'f': 'function'
    };

    fconsole.start('Build resource map');
    basisFile.ast = at.walk(basisFile.ast, {
      "dot": function(token){
        var expr = token[1];
        var name = at.resolveName(token, true);

        if (!inserted && name == 'this.__resources__' || name == 'global.__resources__')
        {
          inserted = true;
          return at.parse('0,' + (function(){
            var res = [];
            var resourceTypeWeight = {
              'json': 1,
              'template': 2,
              'script': 100
            };
            var stat = {};

            for (var jsRef in flow.js.resourceMap)
            {
              var file = flow.js.resourceMap[jsRef];

              if (!file.jsRefCount && file.type == 'template')
              {
                fconsole.log('[i] Drop resource:', file.relpath);
                continue;
              }

              var content = file.jsResourceContent != null
                ? file.jsResourceContent
                : file.outputContent || file.content;

              if (typeof content == 'function')
                content = content.toString().replace(/function\s+anonymous/, 'function');
              else
                content = JSON.stringify(content);

              if (!stat[file.type])
                stat[file.type] = { count: 0, size: 0 };

              stat[file.type].count++;
              stat[file.type].size += content.length;

              res.push([file, file.jsRef, content]);
            }

            fconsole.start('Stat:');
            for (var type in stat)
              fconsole.log('[' + type + '] ' + stat[type].size + ' bytes in ' + stat[type].count + ' resource(s)');
            fconsole.end();

            return '{\n' +
              res.sort(function(a, b){
                var wa = resourceTypeWeight[a[0].type] || 0;
                var wb = resourceTypeWeight[b[0].type] || 0;
                return wa > wb ? 1 : (wa < wb ? -1 : 0);
              }).map(function(item){
                resourceToc.push('[' + (resTypeByFirstChar[item[2].charAt(0)] || 'unknown') + '] ' + item[0].relpath + ' -> ' + item[1]);
                return '"' + item[1] + '":' + item[2]
              }).join(',\n') +
            '\n}';
          })())[1][0][1][2];
        }
      }
    });
    fconsole.endl();

    if (flow.js.globalVars)
      basisFile.ast[1].unshift(['var', flow.js.globalVars]);
  }

  for (var name in packages)
  {
    var package = packages[name];

    // log package file list
    fconsole.start('Package ' + name + ':');
    package.forEach(function(f){
      fconsole.log(f.relpath);
    });
    fconsole.endl();

    switch (package.layout){
      case 'basis':
        var isCoreFile = basisFile && flow.js.rootNSFile[name] === basisFile; //(flow.options.jsSingleFile || name == 'basis');
        var throwCodes = package.reduce(function(res, file){
          res.push.apply(res, file.throwCodes);
          return res;
        }, []);

        var packageFile = flow.files.add({
          type: 'script',
          outputFilename: name + '.js',
          outputContent:
            (isCoreFile ? '// resources (' + resourceToc.length + '):\n//  ' + resourceToc.join('\n//  ') + '\n//\n' : '') +
            (throwCodes.length ? '// throw codes:\n//  ' + throwCodes.map(function(item){ return item[0] + ' -> ' + at.translate(item[1]) }).join('\n//  ') + '\n//\n' : '') +
            wrapPackage(
              package.filter(function(file){
                return file != basisFile;
              }),
              flow,
              isCoreFile
                ? at.translate(basisFile.ast, {
                    beautify: !flow.options.pack,
                    indent_level: 2
                  })
                : ''
            )
        });

        packages[name].file = packageFile;

        if (isCoreFile)
        {
          packageFile.htmlNode = basisFile.htmlNode;
          delete basisFile.htmlNode;
        }

        break;

      default:
        var htmlNode = null;
        var packageFile = flow.files.add({
          type: 'script',
          outputFilename: name + '.js',
          outputContent: package.map(function(file){
            if (file.htmlNode)
            {
              if (!htmlNode)
                htmlNode = file.htmlNode;
              else
                html_at.removeToken(file.htmlNode, true);

              delete file.htmlNode;
            }

            return '//' + file.relpath + '\n' + file.outputContent;
          }).join(';\n\n') + ';'
        });

        packageFile.htmlNode = htmlNode;
        packages[name].file = packageFile;
    }
  }
}
module.exports.handlerName = '[js] Build packages';

//
// wrap package
//

function extractBuildContent(file){
  return '// ' + file.relpath + '\n' +
    '[' +
      '"' + file.namespace + '", function(basis, module, exports, resource, global, __dirname, __filename){' +
        file.outputContent +
      '}' +
    ']';
}

function extractSourceContent(file){
  return '//\n// ' + file.relpath + '\n//\n' +
    '{\n' +
    '  ns: "' + file.namespace + '",\n' +
    '  path: "' + path.dirname(file.relpath) + '/",\n' +
    '  fn: "' + file.basename + '",\n' +
    '  body: function(){\n' +
         file.outputContent + '\n' +
    '  }\n' +
    '}';
}

var packageWrapper = [
  "(function(){\n" +
  "'use strict';\n\n",

  "\n}).call(this);"
];

function wrapPackage(package, flow, contentPrepend){
  return !flow.options.jsBuildMode
    // source mode
    ? [
        '// filelist (' + package.length + '): \n//   ' + package.map(function(file){
          return file.relpath;
        }).join('\n//   ') + '\n',

        packageWrapper[0],
        contentPrepend,

        ';[\n',
          package.map(extractSourceContent).join(',\n'),
        '\n].forEach(' + function(module){
           var path = module.path;
           var fn = path + module.fn;
           var ns = basis.namespace(module.ns);
           ns.source_ = module.body.toString().replace(/^\s*\(?\s*function[^(]*\([^\)]*\)[^{]*\{|\}\s*\)?\s*$/g, '');
           ns.filename_ = module.path + module.fn;
           new Function('module, exports, global, __filename, __dirname, basis, resource',
             '/** @namespace ' + ns.path + ' */\n' + ns.source_ + '//@ sourceURL=' + fn
           ).call(ns, ns, ns.exports, this, fn, path, basis, function(url){ return basis.resource(path + url) });
           for (var key in ns.exports)
             if (key in ns == false)
               ns[key] = ns.exports[key];
         } + ', this)',

        packageWrapper[1]
      ].join('')
    // build mode
    : [
        '// filelist (' + package.length + '): \n//   ' + package.map(function(file){
          return file.relpath;
        }).join('\n//   ') + '\n',

        packageWrapper[0],
        contentPrepend,

        ';[\n',
          package.map(extractBuildContent).join(',\n'),
        '].forEach(' + function(module){
           var fn = module[1];
           var ns = basis.namespace(module[0]);
           // basis, module, exports, resource, global, __dirname, __filename
           fn.call(ns, basis, ns, ns.exports, basis.resource, this, "", "");
           for (var key in ns.exports)
             if (key in ns == false)
               ns[key] = ns.exports[key];
         } + ', this)',

        packageWrapper[1]
      ].join('');
}
<|endoftext|>


<commit_before>var Tokenizer = require('./tokenizer')
var util = require('util')

var i = 55,
    TEXT = 0,
    BEFORE_ATTRIBUTE_NAME = 7,
    BEFORE_ATTRIBUTE_VALUE = 10,
    BEFORE_DIRECTIVE = i++,
    BEFORE_TEXT_DIRECTIVE = i++,
    BEFORE_HTML_DIRECTIVE = i++,
    AFTER_TEXT_DIRECTIVE_START = i++,
    IN_TEXT_DIRECTIVE = i++,

    IN_ATTRIBUTE_VALUE_EVAL = i++,

    IN_JAVASCRIPT_STRING = i++,
    IN_JAVASCRIPT_STRING_ESCAPE = i++

function whitespace (c) {
    return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}

function attribute (cbs, name, value) {
    cbs.onattribname(name)
    cbs.onattribdata(value)
    cbs.onattribend()
}

function send (cbs, directive) {
    cbs.onopentagname('div')
    attribute(cbs, 'data-stencil-directive', directive.name)
    for (var name in directive.attributes) {
        attribute(cbs, 'data-stencil-attribute-' + name, directive.attributes[name])
    }
    cbs.onopentagend()
    cbs.onclosetag('div');
}

function Stencilizer () {
    this._stencilizer = {
        text: [],
        attributes: {}
    }
    Tokenizer.call(this)
}
util.inherits(Stencilizer, Tokenizer)

Stencilizer.prototype._consume = function (c) {
    var directive = this._stencilizer
    switch (this._state) {
    case TEXT:
        switch (c) {
        case '[':
            if(this._index > this._sectionStart){
                this._cbs.ontext(this._getSection());
            }
            this._state = BEFORE_DIRECTIVE
            return true
        }
        return false
    case BEFORE_ATTRIBUTE_VALUE:
        switch (c) {
        case '(':
            this._cbs.onattribeval()
            this._sectionStart = this._index + 1
            this._state = IN_ATTRIBUTE_VALUE_EVAL
            return true
        }
        return false
    case IN_ATTRIBUTE_VALUE_EVAL:
        switch (c) {
        case '\'':
        case '"':
            directive.character = c
            directive.state = this._state
            this._state = IN_JAVASCRIPT_STRING
            break
        case ')':
            this._cbs.onattribdata(this._getSection())
            this._cbs.onattribend()
            this._state = BEFORE_ATTRIBUTE_NAME;
            break
        }
        return true
    case IN_JAVASCRIPT_STRING:
        if (c == '\\') {
            this._state = IN_JAVASCRIPT_STRING_ESCAPE
        } else if (c == directive.character) {
            this._state = directive.state
        }
        return true
    case IN_JAVASCRIPT_STRING_ESCAPE:
        this._state = IN_JAVASCRIPT_STRING
        return true
    case BEFORE_DIRECTIVE:
        if (c == '<') {
            this._state  = BEFORE_TEXT_DIRECTIVE
            directive.name = 'value'
            directive.attributes.type = 'html'
        } else {
            this._state = IN_TEXT_DIRECTIVE
        }
        return true
    case BEFORE_TEXT_DIRECTIVE:
        if (c == '<') {
            this._state  = BEFORE_HTML_DIRECTIVE
            directive.attributes.type = 'text'
        } else {
            this._state = IN_TEXT_DIRECTIVE
        }
        return true
    case BEFORE_HTML_DIRECTIVE:
        this._state = IN_TEXT_DIRECTIVE
        return true
    case IN_TEXT_DIRECTIVE:
        if (c == ']') {
            directive.attributes.select = directive.text.join('').trim()
            send(this._cbs, directive)
            this._state = TEXT
            this._sectionStart = this._index + 1;
        } else {
            directive.text.push(c)
        }
        return true
    }
    return false
}

Stencilizer.prototype._intercept = function (c) {
    if (this._consume(c)) {
        this._index++
        return true
    }
    return false
}

module.exports = Stencilizer
<commit_msg>Semi-colon tidy.<commit_after>var Tokenizer = require('./tokenizer')
var util = require('util')

var i = 55,
    TEXT = 0,
    BEFORE_ATTRIBUTE_NAME = 7,
    BEFORE_ATTRIBUTE_VALUE = 10,
    BEFORE_DIRECTIVE = i++,
    BEFORE_TEXT_DIRECTIVE = i++,
    BEFORE_HTML_DIRECTIVE = i++,
    AFTER_TEXT_DIRECTIVE_START = i++,
    IN_TEXT_DIRECTIVE = i++,

    IN_ATTRIBUTE_VALUE_EVAL = i++,

    IN_JAVASCRIPT_STRING = i++,
    IN_JAVASCRIPT_STRING_ESCAPE = i++

function whitespace (c) {
    return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r"
}

function attribute (cbs, name, value) {
    cbs.onattribname(name)
    cbs.onattribdata(value)
    cbs.onattribend()
}

function send (cbs, directive) {
    cbs.onopentagname('div')
    attribute(cbs, 'data-stencil-directive', directive.name)
    for (var name in directive.attributes) {
        attribute(cbs, 'data-stencil-attribute-' + name, directive.attributes[name])
    }
    cbs.onopentagend()
    cbs.onclosetag('div')
}

function Stencilizer () {
    this._stencilizer = {
        text: [],
        attributes: {}
    }
    Tokenizer.call(this)
}
util.inherits(Stencilizer, Tokenizer)

Stencilizer.prototype._consume = function (c) {
    var directive = this._stencilizer
    switch (this._state) {
    case TEXT:
        switch (c) {
        case '[':
            if(this._index > this._sectionStart){
                this._cbs.ontext(this._getSection())
            }
            this._state = BEFORE_DIRECTIVE
            return true
        }
        return false
    case BEFORE_ATTRIBUTE_VALUE:
        switch (c) {
        case '(':
            this._cbs.onattribeval()
            this._sectionStart = this._index + 1
            this._state = IN_ATTRIBUTE_VALUE_EVAL
            return true
        }
        return false
    case IN_ATTRIBUTE_VALUE_EVAL:
        switch (c) {
        case '\'':
        case '"':
            directive.character = c
            directive.state = this._state
            this._state = IN_JAVASCRIPT_STRING
            break
        case ')':
            this._cbs.onattribdata(this._getSection())
            this._cbs.onattribend()
            this._state = BEFORE_ATTRIBUTE_NAME
            break
        }
        return true
    case IN_JAVASCRIPT_STRING:
        if (c == '\\') {
            this._state = IN_JAVASCRIPT_STRING_ESCAPE
        } else if (c == directive.character) {
            this._state = directive.state
        }
        return true
    case IN_JAVASCRIPT_STRING_ESCAPE:
        this._state = IN_JAVASCRIPT_STRING
        return true
    case BEFORE_DIRECTIVE:
        if (c == '<') {
            this._state  = BEFORE_TEXT_DIRECTIVE
            directive.name = 'value'
            directive.attributes.type = 'html'
        } else {
            this._state = IN_TEXT_DIRECTIVE
        }
        return true
    case BEFORE_TEXT_DIRECTIVE:
        if (c == '<') {
            this._state  = BEFORE_HTML_DIRECTIVE
            directive.attributes.type = 'text'
        } else {
            this._state = IN_TEXT_DIRECTIVE
        }
        return true
    case BEFORE_HTML_DIRECTIVE:
        this._state = IN_TEXT_DIRECTIVE
        return true
    case IN_TEXT_DIRECTIVE:
        if (c == ']') {
            directive.attributes.select = directive.text.join('').trim()
            send(this._cbs, directive)
            this._state = TEXT
            this._sectionStart = this._index + 1
        } else {
            directive.text.push(c)
        }
        return true
    }
    return false
}

Stencilizer.prototype._intercept = function (c) {
    if (this._consume(c)) {
        this._index++
        return true
    }
    return false
}

module.exports = Stencilizer
<|endoftext|>


<commit_before>var timeout;

jQuery(function() {
        console.log("jQuery function");
        loadTop10();
    });

function loadTop10() {
    jQuery.ajax("./index.php", {
            success : function(htmlData) {
                jQuery("#infoAjax").html("");
                jQuery("#infoAjax").html(htmlData);
                var h = document.getElementById("engine-status").scrollHeight + 10;
                if(h){
                    parent.iResize(window.name, h);
                }else{
                    parent.iResize(window.name, 200);
                }
            }
        });
    if (autoRefresh) {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(loadTop10, (autoRefresh * 1000));
    }
}
<commit_msg>fix: scrollHeight<commit_after>var timeout;

jQuery(function() {
        console.log("jQuery function");
        loadTop10();
    });

function loadTop10() {
    jQuery.ajax("./index.php", {
            success : function(htmlData) {
                jQuery("#infoAjax").html("");
                jQuery("#infoAjax").html(htmlData);
                var h = jQuery("engine-status").prop("scrollHeight") + 10;
                if(h){
                    parent.iResize(window.name, h);
                }else{
                    parent.iResize(window.name, 200);
                }
            }
        });
    if (autoRefresh) {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(loadTop10, (autoRefresh * 1000));
    }
}
<|endoftext|>