<commit_before>
if (typeof jQuery === 'undefined') {
  var suggestedCDN = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js";
  throw new Error('Web Component\'s JavaScript requires jQuery, please include the following into your page: ' + suggestedCDN);
}

if (typeof Handlebars === 'undefined') {
  var suggestedCDN = "https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js";
  throw new Error('Web Component\'s JavaScript requires Handlebars, please include the following into your page: ' + suggestedCDN);
}

var Component = false;

// Component requires jQuery for AJAX calls to data-source-url's defined on components
$(function() {
  Component = (function() {

    var Class = function() { }

    Class.registeredComponents = {
      component: Class
    };

    Class.configure = function(tagName) {
      var ComponentClass = Class.registeredComponents[tagName] || false;
      if(ComponentClass) {
        return ComponentClass;
      }
      else {
        ComponentClass = Class.registerComponent(tagName);
      }
      return ComponentClass;
    }

    Class.registerComponent = function(tagName, template) {
      var ComponentClass = Component.create(tagName, template);
      Class.registeredComponents[tagName] = ComponentClass;
      return ComponentClass;
    }

    Class.create = function(elementName, templateElement) {

      var ComponentClass = function(element) {
        this.element = element;
        this.content = $(element).html().trim();
        this.templateKey = "template[tagname={{tagname}}]".replace('{{tagname}}', elementName);
        this.template = templateElement || $(this.templateKey)[0] || false;

        if(!this.template) {
        this.template = this.element.cloneNode(true);
          console.log("Could not find template for " + this.templateKey + ", using: " + $(this.template).html() + " instead.");
        }

        this.copyAttributesFrom(this.template);
        this.copyAttributesFrom(this.element);
        this.init();
        this.refresh();
      }

      ComponentClass.prototype.elementName = elementName;
      ComponentClass.prototype.templateName = elementName + '-template';

      ComponentClass.prototype.copyAttributesFrom = function(element) {
        if(element && element.attributes) {
          for(var i=0; i < element.attributes.length; i++) {
            var attribute = element.attributes[i];
            this[attribute.name] = attribute.value;
          }
        }
      }

      ComponentClass.prototype.init = function() {
        // Reload any data if applicable
        this.render();
      }

      ComponentClass.prototype.preRenderSteps = [];
      ComponentClass.prototype.preRenderStep = function(fn) {
        // Add your own using:
        // Component.register("tagName").preRenderStep(function() { ... });

        var steps = ComponentClass.prototype.preRenderSteps;
        if(fn) {
          steps.push(fn);
        }
        else {
          for(var i=0; i<steps.length; i++) {
            var step = steps[i];
            step.apply(this, []);
          }
        }
        return ComponentClass;
      }

      ComponentClass.prototype.requestDataFromSource = function() {
        var self = this;

        this.dataSourceTemplate = this["data-source-template"] || false;
        this.dataSourceUrl = this["data-source-url"] || ComponentClass.expandTemplate(this, this.dataSourceTemplate) || false;
        this.dataSourceDataType = this["data-source-type"] || false;
        this.dataSourceData = false;
        this.dataSourceError = false;

        if(!this.dataSourceUrl) {
          return false;
        }

        this.reportDataSourceStatus('Waiting for server response');

        $.ajax({
          url: this.dataSourceUrl,
          dataType: this.dataSourceDataType,
          success: function(data, textStatus) {
            self.data = data;
            self.dataSourceData = JSON.stringify(self.data);
            if(data !== null && typeof data === 'object') {
              for(var property in data) {
                self[property] = data[property];
              }
              if(data.error) {
                self.dataSourceError = data.error;
                self.reportDataSourceStatus("Error checking url: " + self.dataSourceUrl + " : " + JSON.stringify(data.error));
              }
              else {
                self.reportDataSourceStatus("Server responded OK.");
              }
            }
            else {
              self.reportDataSourceStatus(self.dataSourceUrl + " : Endpoint returned unexpected data : " + JSON.stringify(data));
            }
          }
        }).fail(function(jqXHR, textStatus) {
          self.dataSourceError = true;
          self.reportDataSourceStatus(self.dataSourceUrl + " : Endpoint failed to retrieve data, reason: " + textStatus);
        });
      }

      ComponentClass.prototype.reportDataSourceStatus = function(message) {
        this.dataSourceStatus = message;
        this.render();
      }

      ComponentClass.prototype.render = function() {
        this.preRenderStep();

        var expandedTemplate = ComponentClass.expandTemplate(this, $(this.template).html());

        $(this.element).html(expandedTemplate).attr('rendered', true);

        Class.scanForComponents(this.element);
      }

      ComponentClass.expandTemplate = function(data, template) {
        if(template) {

          // substitute element content into template
          if(data.content) {
            template = template.replace(/{{content}}/g, data.content);
          }

          // apply handlebar template based on context
          var handlebarsTemplate = Handlebars.compile(template);
          var expandedTemplate = handlebarsTemplate(data);
        }
        return expandedTemplate;
      }

      ComponentClass.expandProperty = function(property, value, template) {
        var expandedTemplate = template;

        if(expandedTemplate) {
          var matcher = new RegExp("{{x}}".replace("x", property), "g");
          expandedTemplate = expandedTemplate.replace(matcher, value);
        }

        return expandedTemplate;
      }

      ComponentClass.prototype.refresh = function() {
        // Prevent timeout leaks
        if(this.refreshTimeoutId) {
          clearTimeout(this.refreshTimeoutId);
        }

        // Loop
        var self = this;
        this.refreshTimeSeconds = this["refresh-time"] || 0;
        if(this.refreshTimeSeconds) {
          this.refreshTimeoutId = setTimeout(function() {
            self.refresh();
          }, this.refreshTimeSeconds * 1000 + Math.random() * 500);
        }

        // Re-load data for the component
        this.requestDataFromSource();
      }

      return ComponentClass;
    }

    Class.registerTemplates = function() {
      var templates = $('template[tagname]').each(function() {
        var template = $(this)[0];
        var tagName = $(this).attr('tagname');

        Class.registerComponent(tagName, template);
      });

      return this;
    }

    Class.scanForComponents = function(rootElement) {

      var items = rootElement.getElementsByTagName("*");
      // Walk the document looking for components to create
      for (var i = 0; i < items.length; i++) {
        var element = items[i];
        var tagName = element.tagName.toLowerCase();
        if(!element.attributes.rendered) {
          var ComponentClass = Class.registeredComponents[tagName] || false;
          if(ComponentClass) {
            new ComponentClass(element);
          }
        }
      }

      return this;
    }

    return Class;
  })();

  Component.registerTemplates().scanForComponents(document.body);
});
<commit_msg>Applied atom-beautify to web-component.js<commit_after>if (typeof jQuery === 'undefined') {
  var suggestedCDN = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js";
  throw new Error('Web Component\'s JavaScript requires jQuery, please include the following into your page: ' + suggestedCDN);
}

if (typeof Handlebars === 'undefined') {
  var suggestedCDN = "https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js";
  throw new Error('Web Component\'s JavaScript requires Handlebars, please include the following into your page: ' + suggestedCDN);
}

var Component = false;

// Component requires jQuery for AJAX calls to data-source-url's defined on components
$(function() {
  Component = (function() {

    var Class = function() {}

    Class.registeredComponents = {
      component: Class
    };

    Class.configure = function(tagName) {
      var ComponentClass = Class.registeredComponents[tagName] || false;
      if (ComponentClass) {
        return ComponentClass;
      } else {
        ComponentClass = Class.registerComponent(tagName);
      }
      return ComponentClass;
    }

    Class.registerComponent = function(tagName, template) {
      var ComponentClass = Component.create(tagName, template);
      Class.registeredComponents[tagName] = ComponentClass;
      return ComponentClass;
    }

    Class.create = function(elementName, templateElement) {

      var ComponentClass = function(element) {
        this.element = element;
        this.content = $(element).html().trim();
        this.templateKey = "template[tagname={{tagname}}]".replace('{{tagname}}', elementName);
        this.template = templateElement || $(this.templateKey)[0] || false;

        if (!this.template) {
          this.template = this.element.cloneNode(true);
          console.log("Could not find template for " + this.templateKey + ", using: " + $(this.template).html() + " instead.");
        }

        this.copyAttributesFrom(this.template);
        this.copyAttributesFrom(this.element);
        this.init();
        this.refresh();
      }

      ComponentClass.prototype.elementName = elementName;
      ComponentClass.prototype.templateName = elementName + '-template';

      ComponentClass.prototype.copyAttributesFrom = function(element) {
        if (element && element.attributes) {
          for (var i = 0; i < element.attributes.length; i++) {
            var attribute = element.attributes[i];
            this[attribute.name] = attribute.value;
          }
        }
      }

      ComponentClass.prototype.init = function() {
        // Reload any data if applicable
        this.render();
      }

      ComponentClass.prototype.preRenderSteps = [];
      ComponentClass.prototype.preRenderStep = function(fn) {
        // Add your own using:
        // Component.register("tagName").preRenderStep(function() { ... });

        var steps = ComponentClass.prototype.preRenderSteps;
        if (fn) {
          steps.push(fn);
        } else {
          for (var i = 0; i < steps.length; i++) {
            var step = steps[i];
            step.apply(this, []);
          }
        }
        return ComponentClass;
      }

      ComponentClass.prototype.requestDataFromSource = function() {
        var self = this;

        this.dataSourceTemplate = this["data-source-template"] || false;
        this.dataSourceUrl = this["data-source-url"] || ComponentClass.expandTemplate(this, this.dataSourceTemplate) || false;
        this.dataSourceDataType = this["data-source-type"] || false;
        this.dataSourceData = false;
        this.dataSourceError = false;

        if (!this.dataSourceUrl) {
          return false;
        }

        this.reportDataSourceStatus('Waiting for server response');

        $.ajax({
          url: this.dataSourceUrl,
          dataType: this.dataSourceDataType,
          success: function(data, textStatus) {
            self.data = data;
            self.dataSourceData = JSON.stringify(self.data);
            if (data !== null && typeof data === 'object') {
              for (var property in data) {
                self[property] = data[property];
              }
              if (data.error) {
                self.dataSourceError = data.error;
                self.reportDataSourceStatus("Error checking url: " + self.dataSourceUrl + " : " + JSON.stringify(data.error));
              } else {
                self.reportDataSourceStatus("Server responded OK.");
              }
            } else {
              self.reportDataSourceStatus(self.dataSourceUrl + " : Endpoint returned unexpected data : " + JSON.stringify(data));
            }
          }
        }).fail(function(jqXHR, textStatus) {
          self.dataSourceError = true;
          self.reportDataSourceStatus(self.dataSourceUrl + " : Endpoint failed to retrieve data, reason: " + textStatus);
        });
      }

      ComponentClass.prototype.reportDataSourceStatus = function(message) {
        this.dataSourceStatus = message;
        this.render();
      }

      ComponentClass.prototype.render = function() {
        this.preRenderStep();

        var expandedTemplate = ComponentClass.expandTemplate(this, $(this.template).html());

        $(this.element).html(expandedTemplate).attr('rendered', true);

        Class.scanForComponents(this.element);
      }

      ComponentClass.expandTemplate = function(data, template) {
        if (template) {

          // substitute element content into template
          if (data.content) {
            template = template.replace(/{{content}}/g, data.content);
          }

          // apply handlebar template based on context
          var handlebarsTemplate = Handlebars.compile(template);
          var expandedTemplate = handlebarsTemplate(data);
        }
        return expandedTemplate;
      }

      ComponentClass.expandProperty = function(property, value, template) {
        var expandedTemplate = template;

        if (expandedTemplate) {
          var matcher = new RegExp("{{x}}".replace("x", property), "g");
          expandedTemplate = expandedTemplate.replace(matcher, value);
        }

        return expandedTemplate;
      }

      ComponentClass.prototype.refresh = function() {
        // Prevent timeout leaks
        if (this.refreshTimeoutId) {
          clearTimeout(this.refreshTimeoutId);
        }

        // Loop
        var self = this;
        this.refreshTimeSeconds = this["refresh-time"] || 0;
        if (this.refreshTimeSeconds) {
          this.refreshTimeoutId = setTimeout(function() {
            self.refresh();
          }, this.refreshTimeSeconds * 1000 + Math.random() * 500);
        }

        // Re-load data for the component
        this.requestDataFromSource();
      }

      return ComponentClass;
    }

    Class.registerTemplates = function() {
      var templates = $('template[tagname]').each(function() {
        var template = $(this)[0];
        var tagName = $(this).attr('tagname');

        Class.registerComponent(tagName, template);
      });

      return this;
    }

    Class.scanForComponents = function(rootElement) {

      var items = rootElement.getElementsByTagName("*");
      // Walk the document looking for components to create
      for (var i = 0; i < items.length; i++) {
        var element = items[i];
        var tagName = element.tagName.toLowerCase();
        if (!element.attributes.rendered) {
          var ComponentClass = Class.registeredComponents[tagName] || false;
          if (ComponentClass) {
            new ComponentClass(element);
          }
        }
      }

      return this;
    }

    return Class;
  })();

  Component.registerTemplates().scanForComponents(document.body);
});
<|endoftext|>


<commit_before>(function($) {
	var setupTriangle = {};
	$.fn.setupTriangle = function(opt) {
		var res = _setupTheValues(this);
		setupTriangle[res[1]] = res[0];
		return this;
	};

	$.fn.whichTriangle = function(evt) {
		var $this = $(this);
		var $offset = $this.offset();
		var index = ""+$offset.left+$offset.top+$this.height()+$this.width();
		console.log(evt.clientX, evt.clientY);
		var res =  _whichTriangleIsPointIn(setupTriangle[index], [evt.clientX, evt.clientY]);
		console.log(res);
		return res;
	};

	$.fn.updateTriangle = function(opt) {
		this.setupTriangle();
	};

	function _setupTheValues(elem) {
		_setupTheValues.left = (elem.offset()).left,
		_setupTheValues.top = (elem.offset()).top,
		_setupTheValues.ht = elem.height(),
		_setupTheValues.wd = elem.width(),
		_setupTheValues.midX = _setupTheValues.left + (_setupTheValues.wd / 2),
		_setupTheValues.midY = _setupTheValues.top + (_setupTheValues.ht / 2),
		_setupTheValues.x1 = _setupTheValues.left,
		_setupTheValues.y1 = _setupTheValues.top, //x1 y1 are top left corner
		_setupTheValues.x2 = _setupTheValues.left + _setupTheValues.wd,
		_setupTheValues.y2 = _setupTheValues.top, //x2 y2 are top right corner
		_setupTheValues.x3 = _setupTheValues.left + _setupTheValues.wd,
		_setupTheValues.y3 = _setupTheValues.top + _setupTheValues.ht,
		_setupTheValues.x4 = _setupTheValues.left,
		_setupTheValues.y4 = _setupTheValues.top + _setupTheValues.ht,
		_setupTheValues.triangles = _getTrianglesArr(_setupTheValues.x1, _setupTheValues.y1, _setupTheValues.x2, _setupTheValues.y2, _setupTheValues.x3, _setupTheValues.y3, _setupTheValues.x4, _setupTheValues.y4, _setupTheValues.midX, _setupTheValues.midY);

		return [_setupTheValues.triangles, ""+_setupTheValues.left+_setupTheValues.top+_setupTheValues.ht+_setupTheValues.wd];
	}

	function _getTrianglesArr(x1, y1, x2, y2, x3, y3, x4, y4, midX, midY) {
		var arr = [],
			x1y1 = [x1, y1],
			x2y2 = [x2, y2],
			x3y3 = [x3, y3],
			x4y4 = [x4, y4],
			midXmidY = [midX, midY];

		//triangle 1 is (midX, midY) (x1,y1) (x2,y2)
		arr[0] = [];
		arr[0].push(midXmidY);
		arr[0].push(x1y1);
		arr[0].push(x2y2);

		//triangle 2 is (midX, midY) (x2,y2) (x3,y3)
		arr[1] = [];
		arr[1].push(midXmidY);
		arr[1].push(x2y2);
		arr[1].push(x3y3);

		//triangle 3 is (midX, midY) (x3,y3) (x4,y4)
		arr[2] = [];
		arr[2].push(midXmidY);
		arr[2].push(x3y3);
		arr[2].push(x4y4);

		//triangle 4 is (midX, midY) (x4,y4) (x1,y1)
		arr[3] = [];
		arr[3].push(midXmidY);
		arr[3].push(x4y4);
		arr[3].push(x1y1);

		return arr;
	}

	/*0 -> top triangle, 1-> right triangle, 2-> bottom triangle, 3-> left triangle*/

	function _whichTriangleIsPointIn(triangles, point) {
		for (var i = 0; i < triangles.length; i++) {
			var tr = triangles[i];
			var alpha = (((tr[1][1] - tr[2][1]) * (point[0] - tr[2][0])) + ((tr[2][0] - tr[1][0]) * (point[1] - tr[2][1]))) / (((tr[1][1] - tr[2][1]) * (tr[0][0] - tr[2][0])) + ((tr[2][0] - tr[1][0]) * (tr[0][1] - tr[2][1]))),

				beta = (((tr[2][1] - tr[0][1]) * (point[0] - tr[2][0])) + ((tr[0][0] - tr[2][0]) * (point[1] - tr[2][1]))) / (((tr[1][1] - tr[2][1]) * (tr[0][0] - tr[2][0])) + ((tr[2][0] - tr[1][0]) * (tr[0][1] - tr[2][1]))),

				gamma = 1 - alpha - beta;

			if (!(0 <= alpha && alpha <= 1))
				continue;

			if (!(0 <= beta && beta <= 1))
				continue;

			if (!(0 <= gamma && gamma <= 1))
				continue;

			/*break if 0<= alpha,beta,gamma <=1*/
			break;
		}
		if (i == triangles.length)
			i = -1;
		return i;
	}

})(jQuery);<commit_msg>Removed a few console.logs<commit_after>(function($) {
	var setupTriangle = {};
	$.fn.setupTriangle = function(opt) {
		var res = _setupTheValues(this);
		setupTriangle[res[1]] = res[0];
		return this;
	};

	$.fn.whichTriangle = function(evt) {
		var $this = $(this);
		var $offset = $this.offset();
		var index = ""+$offset.left+$offset.top+$this.height()+$this.width();
		var res =  _whichTriangleIsPointIn(setupTriangle[index], [evt.clientX, evt.clientY]);
		return res;
	};

	$.fn.updateTriangle = function(opt) {
		this.setupTriangle();
	};

	function _setupTheValues(elem) {
		_setupTheValues.left = (elem.offset()).left,
		_setupTheValues.top = (elem.offset()).top,
		_setupTheValues.ht = elem.height(),
		_setupTheValues.wd = elem.width(),
		_setupTheValues.midX = _setupTheValues.left + (_setupTheValues.wd / 2),
		_setupTheValues.midY = _setupTheValues.top + (_setupTheValues.ht / 2),
		_setupTheValues.x1 = _setupTheValues.left,
		_setupTheValues.y1 = _setupTheValues.top, //x1 y1 are top left corner
		_setupTheValues.x2 = _setupTheValues.left + _setupTheValues.wd,
		_setupTheValues.y2 = _setupTheValues.top, //x2 y2 are top right corner
		_setupTheValues.x3 = _setupTheValues.left + _setupTheValues.wd,
		_setupTheValues.y3 = _setupTheValues.top + _setupTheValues.ht,
		_setupTheValues.x4 = _setupTheValues.left,
		_setupTheValues.y4 = _setupTheValues.top + _setupTheValues.ht,
		_setupTheValues.triangles = _getTrianglesArr(_setupTheValues.x1, _setupTheValues.y1, _setupTheValues.x2, _setupTheValues.y2, _setupTheValues.x3, _setupTheValues.y3, _setupTheValues.x4, _setupTheValues.y4, _setupTheValues.midX, _setupTheValues.midY);

		return [_setupTheValues.triangles, ""+_setupTheValues.left+_setupTheValues.top+_setupTheValues.ht+_setupTheValues.wd];
	}

	function _getTrianglesArr(x1, y1, x2, y2, x3, y3, x4, y4, midX, midY) {
		var arr = [],
			x1y1 = [x1, y1],
			x2y2 = [x2, y2],
			x3y3 = [x3, y3],
			x4y4 = [x4, y4],
			midXmidY = [midX, midY];

		//triangle 1 is (midX, midY) (x1,y1) (x2,y2)
		arr[0] = [];
		arr[0].push(midXmidY);
		arr[0].push(x1y1);
		arr[0].push(x2y2);

		//triangle 2 is (midX, midY) (x2,y2) (x3,y3)
		arr[1] = [];
		arr[1].push(midXmidY);
		arr[1].push(x2y2);
		arr[1].push(x3y3);

		//triangle 3 is (midX, midY) (x3,y3) (x4,y4)
		arr[2] = [];
		arr[2].push(midXmidY);
		arr[2].push(x3y3);
		arr[2].push(x4y4);

		//triangle 4 is (midX, midY) (x4,y4) (x1,y1)
		arr[3] = [];
		arr[3].push(midXmidY);
		arr[3].push(x4y4);
		arr[3].push(x1y1);

		return arr;
	}

	/*0 -> top triangle, 1-> right triangle, 2-> bottom triangle, 3-> left triangle*/
	function _whichTriangleIsPointIn(triangles, point) {
		for (var i = 0; i < triangles.length; i++) {
			var tr = triangles[i];
			var alpha = (((tr[1][1] - tr[2][1]) * (point[0] - tr[2][0])) + ((tr[2][0] - tr[1][0]) * (point[1] - tr[2][1]))) / (((tr[1][1] - tr[2][1]) * (tr[0][0] - tr[2][0])) + ((tr[2][0] - tr[1][0]) * (tr[0][1] - tr[2][1]))),

				beta = (((tr[2][1] - tr[0][1]) * (point[0] - tr[2][0])) + ((tr[0][0] - tr[2][0]) * (point[1] - tr[2][1]))) / (((tr[1][1] - tr[2][1]) * (tr[0][0] - tr[2][0])) + ((tr[2][0] - tr[1][0]) * (tr[0][1] - tr[2][1]))),

				gamma = 1 - alpha - beta;

			if (!(0 <= alpha && alpha <= 1))
				continue;

			if (!(0 <= beta && beta <= 1))
				continue;

			if (!(0 <= gamma && gamma <= 1))
				continue;

			/*break if 0<= alpha,beta,gamma <=1*/
			break;
		}
		if (i == triangles.length)
			i = -1;
		return i;
	}

})(jQuery);<|endoftext|>


<commit_before>/* Copyright 2018 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// The code for XMLParserBase copied from
// https://github.com/mozilla/shumway/blob/16451d8836fa85f4b16eeda8b4bda2fa9e2b22b0/src/avm2/natives/xml.ts

const XMLParserErrorCode = {
  NoError: 0,
  EndOfDocument: -1,
  UnterminatedCdat: -2,
  UnterminatedXmlDeclaration: -3,
  UnterminatedDoctypeDeclaration: -4,
  UnterminatedComment: -5,
  MalformedElement: -6,
  OutOfMemory: -7,
  UnterminatedAttributeValue: -8,
  UnterminatedElement: -9,
  ElementNeverBegun: -10,
};

function isWhitespace(s, index) {
  const ch = s[index];
  return ch === ' ' || ch === '\n' || ch === '\r' || ch === '\t';
}

function isWhitespaceString(s) {
  for (let i = 0, ii = s.length; i < ii; i++) {
    if (!isWhitespace(s, i)) {
      return false;
    }
  }
  return true;
}

class XMLParserBase {
  _resolveEntities(s) {
    return s.replace(/&([^;]+);/g, function (all, entity) {
      if (entity.substring(0, 2) === '#x') {
        return String.fromCharCode(parseInt(entity.substring(2), 16));
      } else if (entity.substring(0, 1) === '#') {
        return String.fromCharCode(parseInt(entity.substring(1), 10));
      }
      switch (entity) {
        case 'lt':
          return '<';
        case 'gt':
          return '>';
        case 'amp':
          return '&';
        case 'quot':
          return '\"';
      }
      return this.onResolveEntity(entity);
    });
  }

  _parseContent(s, start) {
    let pos = start, name, attributes = [];

    function skipWs() {
      while (pos < s.length && isWhitespace(s, pos)) {
        ++pos;
      }
    }

    while (pos < s.length && !isWhitespace(s, pos) &&
           s[pos] !== '>' && s[pos] !== '/') {
      ++pos;
    }
    name = s.substring(start, pos);
    skipWs();
    while (pos < s.length && s[pos] !== '>' &&
           s[pos] !== '/' && s[pos] !== '?') {
      skipWs();
      let attrName = '', attrValue = '';
      while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== '=') {
        attrName += s[pos];
        ++pos;
      }
      skipWs();
      if (s[pos] !== '=') {
        return null;
      }
      ++pos;
      skipWs();
      const attrEndChar = s[pos];
      if (attrEndChar !== '\"' && attrEndChar !== '\'') {
        return null;
      }
      const attrEndIndex = s.indexOf(attrEndChar, ++pos);
      if (attrEndIndex < 0) {
        return null;
      }
      attrValue = s.substring(pos, attrEndIndex);
      attributes.push({
        name: attrName,
        value: this._resolveEntities(attrValue),
      });
      pos = attrEndIndex + 1;
      skipWs();
    }
    return {
      name,
      attributes,
      parsed: pos - start,
    };
  }

  _parseProcessingInstruction(s, start) {
    let pos = start, name, value;

    function skipWs() {
      while (pos < s.length && isWhitespace(s, pos)) {
        ++pos;
      }
    }

    while (pos < s.length && !isWhitespace(s, pos) &&
           s[pos] !== '>' && s[pos] !== '/') {
      ++pos;
    }
    name = s.substring(start, pos);
    skipWs();
    const attrStart = pos;
    while (pos < s.length && (s[pos] !== '?' || s[pos + 1] !== '>')) {
      ++pos;
    }
    value = s.substring(attrStart, pos);
    return {
      name,
      value,
      parsed: pos - start,
    };
  }

  parseXml(s) {
    let i = 0;
    while (i < s.length) {
      const ch = s[i];
      let j = i;
      if (ch === '<') {
        ++j;
        const ch2 = s[j];
        let q;
        switch (ch2) {
          case '/':
            ++j;
            q = s.indexOf('>', j);
            if (q < 0) {
              this.onError(XMLParserErrorCode.UnterminatedElement);
              return;
            }
            this.onEndElement(s.substring(j, q));
            j = q + 1;
            break;
          case '?':
            ++j;
            const pi = this._parseProcessingInstruction(s, j);
            if (s.substring(j + pi.parsed, j + pi.parsed + 2) !== '?>') {
              this.onError(XMLParserErrorCode.UnterminatedXmlDeclaration);
              return;
            }
            this.onPi(pi.name, pi.value);
            j += pi.parsed + 2;
            break;
          case '!':
            if (s.substring(j + 1, j + 3) === '--') {
              q = s.indexOf('-->', j + 3);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedComment);
                return;
              }
              this.onComment(s.substring(j + 3, q));
              j = q + 3;
            } else if (s.substring(j + 1, j + 8) === '[CDATA[') {
              q = s.indexOf(']]>', j + 8);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedCdat);
                return;
              }
              this.onCdata(s.substring(j + 8, q));
              j = q + 3;
            } else if (s.substring(j + 1, j + 8) === 'DOCTYPE') {
              const q2 = s.indexOf('[', j + 8);
              let complexDoctype = false;
              q = s.indexOf('>', j + 8);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);
                return;
              }
              if (q2 > 0 && q > q2) {
                q = s.indexOf(']>', j + 8);
                if (q < 0) {
                  this.onError(
                    XMLParserErrorCode.UnterminatedDoctypeDeclaration);
                  return;
                }
                complexDoctype = true;
              }
              const doctypeContent =
                s.substring(j + 8, q + (complexDoctype ? 1 : 0));
              this.onDoctype(doctypeContent);
              j = q + (complexDoctype ? 2 : 1);
            } else {
              this.onError(XMLParserErrorCode.MalformedElement);
              return;
            }
            break;
          default:
            const content = this._parseContent(s, j);
            if (content === null) {
              this.onError(XMLParserErrorCode.MalformedElement);
              return;
            }
            let isClosed = false;
            if (s.substring(j + content.parsed,
                            j + content.parsed + 2) === '/>') {
              isClosed = true;
            } else if (s.substring(j + content.parsed,
                       j + content.parsed + 1) !== '>') {
              this.onError(XMLParserErrorCode.UnterminatedElement);
              return;
            }
            this.onBeginElement(content.name, content.attributes, isClosed);
            j += content.parsed + (isClosed ? 2 : 1);
            break;
        }
      } else {
        while (j < s.length && s[j] !== '<') {
          j++;
        }
        const text = s.substring(i, j);
        this.onText(this._resolveEntities(text));
      }
      i = j;
    }
  }

  onResolveEntity(name) {
    return `&${name};`;
  }

  onPi(name, value) { }

  onComment(text) { }

  onCdata(text) { }

  onDoctype(doctypeContent) { }

  onText(text) { }

  onBeginElement(name, attributes, isEmpty) { }

  onEndElement(name) { }

  onError(code) { }
}

class SimpleDOMNode {
  constructor(nodeName, nodeValue) {
    this.nodeName = nodeName;
    this.nodeValue = nodeValue;

    Object.defineProperty(this, 'parentNode', { value: null, writable: true, });
  }

  get firstChild() {
    return this.childNodes[0];
  }

  get nextSibling() {
    let index = this.parentNode.childNodes.indexOf(this);
    return this.parentNode.childNodes[index + 1];
  }

  get textContent() {
    if (!this.childNodes) {
      return this.nodeValue || '';
    }
    return this.childNodes.map(function(child) {
      return child.textContent;
    }).join('');
  }

  hasChildNodes() {
    return this.childNodes && this.childNodes.length > 0;
  }
}

class SimpleXMLParser extends XMLParserBase {
  constructor() {
    super();
    this._currentFragment = null;
    this._stack = null;
    this._errorCode = XMLParserErrorCode.NoError;
  }

  parseFromString(data) {
    this._currentFragment = [];
    this._stack = [];
    this._errorCode = XMLParserErrorCode.NoError;

    this.parseXml(data);

    if (this._errorCode !== XMLParserErrorCode.NoError) {
      return undefined; // return undefined on error
    }

    // We should only have one root.
    const [documentElement] = this._currentFragment;
    if (!documentElement) {
      return undefined; // Return undefined if no root was found.
    }
    return { documentElement, };
  }

  onResolveEntity(name) {
    switch (name) {
      case 'apos':
        return '\'';
    }
    return super.onResolveEntity(name);
  }

  onText(text) {
    if (isWhitespaceString(text)) {
      return;
    }
    const node = new SimpleDOMNode('#text', text);
    this._currentFragment.push(node);
  }

  onCdata(text) {
    const node = new SimpleDOMNode('#text', text);
    this._currentFragment.push(node);
  }

  onBeginElement(name, attributes, isEmpty) {
    const node = new SimpleDOMNode(name);
    node.childNodes = [];
    this._currentFragment.push(node);
    if (isEmpty) {
      return;
    }
    this._stack.push(this._currentFragment);
    this._currentFragment = node.childNodes;
  }

  onEndElement(name) {
    this._currentFragment = this._stack.pop();
    const lastElement = this._currentFragment[this._currentFragment.length - 1];
    for (let i = 0, ii = lastElement.childNodes.length; i < ii; i++) {
      lastElement.childNodes[i].parentNode = lastElement;
    }
  }

  onError(code) {
    this._errorCode = code;
  }
}

export {
  SimpleXMLParser,
};
<commit_msg>Prevent errors in various methods in `SimpleDOMNode` when the `childNodes` property is not defined (issue 10395)<commit_after>/* Copyright 2018 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// The code for XMLParserBase copied from
// https://github.com/mozilla/shumway/blob/16451d8836fa85f4b16eeda8b4bda2fa9e2b22b0/src/avm2/natives/xml.ts

const XMLParserErrorCode = {
  NoError: 0,
  EndOfDocument: -1,
  UnterminatedCdat: -2,
  UnterminatedXmlDeclaration: -3,
  UnterminatedDoctypeDeclaration: -4,
  UnterminatedComment: -5,
  MalformedElement: -6,
  OutOfMemory: -7,
  UnterminatedAttributeValue: -8,
  UnterminatedElement: -9,
  ElementNeverBegun: -10,
};

function isWhitespace(s, index) {
  const ch = s[index];
  return ch === ' ' || ch === '\n' || ch === '\r' || ch === '\t';
}

function isWhitespaceString(s) {
  for (let i = 0, ii = s.length; i < ii; i++) {
    if (!isWhitespace(s, i)) {
      return false;
    }
  }
  return true;
}

class XMLParserBase {
  _resolveEntities(s) {
    return s.replace(/&([^;]+);/g, function (all, entity) {
      if (entity.substring(0, 2) === '#x') {
        return String.fromCharCode(parseInt(entity.substring(2), 16));
      } else if (entity.substring(0, 1) === '#') {
        return String.fromCharCode(parseInt(entity.substring(1), 10));
      }
      switch (entity) {
        case 'lt':
          return '<';
        case 'gt':
          return '>';
        case 'amp':
          return '&';
        case 'quot':
          return '\"';
      }
      return this.onResolveEntity(entity);
    });
  }

  _parseContent(s, start) {
    let pos = start, name, attributes = [];

    function skipWs() {
      while (pos < s.length && isWhitespace(s, pos)) {
        ++pos;
      }
    }

    while (pos < s.length && !isWhitespace(s, pos) &&
           s[pos] !== '>' && s[pos] !== '/') {
      ++pos;
    }
    name = s.substring(start, pos);
    skipWs();
    while (pos < s.length && s[pos] !== '>' &&
           s[pos] !== '/' && s[pos] !== '?') {
      skipWs();
      let attrName = '', attrValue = '';
      while (pos < s.length && !isWhitespace(s, pos) && s[pos] !== '=') {
        attrName += s[pos];
        ++pos;
      }
      skipWs();
      if (s[pos] !== '=') {
        return null;
      }
      ++pos;
      skipWs();
      const attrEndChar = s[pos];
      if (attrEndChar !== '\"' && attrEndChar !== '\'') {
        return null;
      }
      const attrEndIndex = s.indexOf(attrEndChar, ++pos);
      if (attrEndIndex < 0) {
        return null;
      }
      attrValue = s.substring(pos, attrEndIndex);
      attributes.push({
        name: attrName,
        value: this._resolveEntities(attrValue),
      });
      pos = attrEndIndex + 1;
      skipWs();
    }
    return {
      name,
      attributes,
      parsed: pos - start,
    };
  }

  _parseProcessingInstruction(s, start) {
    let pos = start, name, value;

    function skipWs() {
      while (pos < s.length && isWhitespace(s, pos)) {
        ++pos;
      }
    }

    while (pos < s.length && !isWhitespace(s, pos) &&
           s[pos] !== '>' && s[pos] !== '/') {
      ++pos;
    }
    name = s.substring(start, pos);
    skipWs();
    const attrStart = pos;
    while (pos < s.length && (s[pos] !== '?' || s[pos + 1] !== '>')) {
      ++pos;
    }
    value = s.substring(attrStart, pos);
    return {
      name,
      value,
      parsed: pos - start,
    };
  }

  parseXml(s) {
    let i = 0;
    while (i < s.length) {
      const ch = s[i];
      let j = i;
      if (ch === '<') {
        ++j;
        const ch2 = s[j];
        let q;
        switch (ch2) {
          case '/':
            ++j;
            q = s.indexOf('>', j);
            if (q < 0) {
              this.onError(XMLParserErrorCode.UnterminatedElement);
              return;
            }
            this.onEndElement(s.substring(j, q));
            j = q + 1;
            break;
          case '?':
            ++j;
            const pi = this._parseProcessingInstruction(s, j);
            if (s.substring(j + pi.parsed, j + pi.parsed + 2) !== '?>') {
              this.onError(XMLParserErrorCode.UnterminatedXmlDeclaration);
              return;
            }
            this.onPi(pi.name, pi.value);
            j += pi.parsed + 2;
            break;
          case '!':
            if (s.substring(j + 1, j + 3) === '--') {
              q = s.indexOf('-->', j + 3);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedComment);
                return;
              }
              this.onComment(s.substring(j + 3, q));
              j = q + 3;
            } else if (s.substring(j + 1, j + 8) === '[CDATA[') {
              q = s.indexOf(']]>', j + 8);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedCdat);
                return;
              }
              this.onCdata(s.substring(j + 8, q));
              j = q + 3;
            } else if (s.substring(j + 1, j + 8) === 'DOCTYPE') {
              const q2 = s.indexOf('[', j + 8);
              let complexDoctype = false;
              q = s.indexOf('>', j + 8);
              if (q < 0) {
                this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);
                return;
              }
              if (q2 > 0 && q > q2) {
                q = s.indexOf(']>', j + 8);
                if (q < 0) {
                  this.onError(
                    XMLParserErrorCode.UnterminatedDoctypeDeclaration);
                  return;
                }
                complexDoctype = true;
              }
              const doctypeContent =
                s.substring(j + 8, q + (complexDoctype ? 1 : 0));
              this.onDoctype(doctypeContent);
              j = q + (complexDoctype ? 2 : 1);
            } else {
              this.onError(XMLParserErrorCode.MalformedElement);
              return;
            }
            break;
          default:
            const content = this._parseContent(s, j);
            if (content === null) {
              this.onError(XMLParserErrorCode.MalformedElement);
              return;
            }
            let isClosed = false;
            if (s.substring(j + content.parsed,
                            j + content.parsed + 2) === '/>') {
              isClosed = true;
            } else if (s.substring(j + content.parsed,
                       j + content.parsed + 1) !== '>') {
              this.onError(XMLParserErrorCode.UnterminatedElement);
              return;
            }
            this.onBeginElement(content.name, content.attributes, isClosed);
            j += content.parsed + (isClosed ? 2 : 1);
            break;
        }
      } else {
        while (j < s.length && s[j] !== '<') {
          j++;
        }
        const text = s.substring(i, j);
        this.onText(this._resolveEntities(text));
      }
      i = j;
    }
  }

  onResolveEntity(name) {
    return `&${name};`;
  }

  onPi(name, value) { }

  onComment(text) { }

  onCdata(text) { }

  onDoctype(doctypeContent) { }

  onText(text) { }

  onBeginElement(name, attributes, isEmpty) { }

  onEndElement(name) { }

  onError(code) { }
}

class SimpleDOMNode {
  constructor(nodeName, nodeValue) {
    this.nodeName = nodeName;
    this.nodeValue = nodeValue;

    Object.defineProperty(this, 'parentNode', { value: null, writable: true, });
  }

  get firstChild() {
    return this.childNodes && this.childNodes[0];
  }

  get nextSibling() {
    const childNodes = this.parentNode.childNodes;
    if (!childNodes) {
      return undefined;
    }
    const index = childNodes.indexOf(this);
    return childNodes[index + 1];
  }

  get textContent() {
    if (!this.childNodes) {
      return this.nodeValue || '';
    }
    return this.childNodes.map(function(child) {
      return child.textContent;
    }).join('');
  }

  hasChildNodes() {
    return this.childNodes && this.childNodes.length > 0;
  }
}

class SimpleXMLParser extends XMLParserBase {
  constructor() {
    super();
    this._currentFragment = null;
    this._stack = null;
    this._errorCode = XMLParserErrorCode.NoError;
  }

  parseFromString(data) {
    this._currentFragment = [];
    this._stack = [];
    this._errorCode = XMLParserErrorCode.NoError;

    this.parseXml(data);

    if (this._errorCode !== XMLParserErrorCode.NoError) {
      return undefined; // return undefined on error
    }

    // We should only have one root.
    const [documentElement] = this._currentFragment;
    if (!documentElement) {
      return undefined; // Return undefined if no root was found.
    }
    return { documentElement, };
  }

  onResolveEntity(name) {
    switch (name) {
      case 'apos':
        return '\'';
    }
    return super.onResolveEntity(name);
  }

  onText(text) {
    if (isWhitespaceString(text)) {
      return;
    }
    const node = new SimpleDOMNode('#text', text);
    this._currentFragment.push(node);
  }

  onCdata(text) {
    const node = new SimpleDOMNode('#text', text);
    this._currentFragment.push(node);
  }

  onBeginElement(name, attributes, isEmpty) {
    const node = new SimpleDOMNode(name);
    node.childNodes = [];
    this._currentFragment.push(node);
    if (isEmpty) {
      return;
    }
    this._stack.push(this._currentFragment);
    this._currentFragment = node.childNodes;
  }

  onEndElement(name) {
    this._currentFragment = this._stack.pop();
    const lastElement = this._currentFragment[this._currentFragment.length - 1];
    for (let i = 0, ii = lastElement.childNodes.length; i < ii; i++) {
      lastElement.childNodes[i].parentNode = lastElement;
    }
  }

  onError(code) {
    this._errorCode = code;
  }
}

export {
  SimpleXMLParser,
};
<|endoftext|>


<commit_before>import {Strategy as JwtStrategy} from 'passport-jwt';
import jwt from 'jsonwebtoken';
import passport from 'passport';

import createDebug from 'debug';
let debug = createDebug('dhm:token'); // eslint-disable-line no-unused-vars

import {User} from './model';

const SECRETS = new WeakMap();
const $passport = Symbol('passport');

export class TokenHandler {

	constructor({secret, passport}) {
		if (!secret) { throw new Error('secret must be defined'); }
		SECRETS[this] = secret;

		if (passport) {
			this[$passport] = passport;
			passport.use('jwt', new JwtStrategy({
				secretOrKey: SECRETS[this],
				authScheme: 'Bearer'
			}, function(jwt, done) {
				let user = {
					id: jwt.sub
				};
				return done(null, user);
			}));

			passport.use('reset', new JwtStrategy({
				secretOrKey: SECRETS[this],
				authScheme: 'Bearer',
				audience: 'reset',
			}, async function(jwt, done) {
				try {
					let user = await User.findById(jwt.sub);
					done(null, user || false);
				} catch (err) {
					done(err);
				}
			}));
		}
	}

	get auth() { return this[$passport].authenticate('jwt', {session: false}); }

	issueForUser(userId) {
		return jwt.sign({}, SECRETS[this], {subject: userId, audience: 'access'});
	}

	issueForLoginToken(loginToken) {
		let decoded = jwt.verify(loginToken, SECRETS[this], {audience: 'login', maxAge: '15m'});
		return this.issueForUser(decoded.sub);
	}

	issueLoginToken(userId) {
		return jwt.sign({}, SECRETS[this], {subject: userId, audience: 'login', expiresIn: '15m'});
	}

	issuePasswordResetToken(userId) {
		return jwt.sign({}, SECRETS[this], {subject: userId, audience: 'reset', expiresIn: '15m'});
	}

	verifyAccessToken(accessToken) {
		let decoded = jwt.verify(accessToken, SECRETS[this], {audience: 'access'});
		return decoded.sub;
	}
}

export default new TokenHandler({passport, secret: process.env.SECRET});
<commit_msg>Checking if user exists during authentication<commit_after>import {Strategy as JwtStrategy} from 'passport-jwt';
import jwt from 'jsonwebtoken';
import passport from 'passport';

import createDebug from 'debug';
let debug = createDebug('dhm:token'); // eslint-disable-line no-unused-vars

import {User} from './model';

const SECRETS = new WeakMap();
const $passport = Symbol('passport');

export class TokenHandler {

	constructor({secret, passport}) {
		if (!secret) { throw new Error('secret must be defined'); }
		SECRETS[this] = secret;

		if (passport) {
			this[$passport] = passport;
			passport.use('jwt', new JwtStrategy({
				secretOrKey: SECRETS[this],
				authScheme: 'Bearer'
			}, async function(jwt, done) {
				try {
					let user = await User.findById(jwt.sub);
					done(null, user);
				} catch (err) {
					done(err);
				}
			}));

			passport.use('reset', new JwtStrategy({
				secretOrKey: SECRETS[this],
				authScheme: 'Bearer',
				audience: 'reset',
			}, async function(jwt, done) {
				try {
					let user = await User.findById(jwt.sub);
					done(null, user || false);
				} catch (err) {
					done(err);
				}
			}));
		}
	}

	get auth() { return this[$passport].authenticate('jwt', {session: false}); }

	issueForUser(userId) {
		return jwt.sign({}, SECRETS[this], {subject: userId, audience: 'access'});
	}

	issueForLoginToken(loginToken) {
		let decoded = jwt.verify(loginToken, SECRETS[this], {audience: 'login', maxAge: '15m'});
		return this.issueForUser(decoded.sub);
	}

	issueLoginToken(userId) {
		return jwt.sign({}, SECRETS[this], {subject: userId, audience: 'login', expiresIn: '15m'});
	}

	issuePasswordResetToken(userId) {
		return jwt.sign({}, SECRETS[this], {subject: userId, audience: 'reset', expiresIn: '15m'});
	}

	verifyAccessToken(accessToken) {
		let decoded = jwt.verify(accessToken, SECRETS[this], {audience: 'access'});
		return decoded.sub;
	}
}

export default new TokenHandler({passport, secret: process.env.SECRET});
<|endoftext|>


<commit_before>/**
 * Schema form service.
 * This service is not that useful outside of schema form directive
 * but makes the code more testable.
 */
angular.module('schemaForm').provider('schemaForm',
['sfPathProvider', function(sfPathProvider) {

  //Creates an default titleMap list from an enum, i.e. a list of strings.
  var enumToTitleMap = function(enm) {
    var titleMap = []; //canonical titleMap format is a list.
    enm.forEach(function(name) {
      titleMap.push({name: name, value: name});
    });
    return titleMap;
  };

  // Takes a titleMap in either object or list format and returns one in
  // in the list format.
  var canonicalTitleMap = function(titleMap) {
    if (!angular.isArray(titleMap)) {
      var canonical = [];
      angular.forEach(titleMap, function(name, value) {
        canonical.push({name: name, value: value});
      });
      return canonical;
    }
    return titleMap;
  };

  var defaultFormDefinition = function(name, schema, options) {
    var rules = defaults[schema.type];
    if (rules) {
      var def;
      for (var i = 0; i < rules.length; i++) {
        def = rules[i](name, schema, options);
        //first handler in list that actually returns something is our handler!
        if (def) {
          return def;
        }
      }
    }
  };

  //Creates a form object with all common properties
  var stdFormObj = function(name, schema, options) {
    options = options || {};
    var f = options.global && options.global.formDefaults ?
            angular.copy(options.global.formDefaults) : {};
    if (options.global && options.global.supressPropertyTitles === true) {
      f.title = schema.title;
    } else {
      f.title = schema.title || name;
    }

    if (schema.description) { f.description = schema.description; }
    if (options.required === true || schema.required === true) { f.required = true; }
    if (schema.maxLength) { f.maxlength = schema.maxLength; }
    if (schema.minLength) { f.minlength = schema.maxLength; }
    if (schema.readOnly || schema.readonly) { f.readonly  = true; }
    if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
    if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }

    //Non standard attributes
    if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
    if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames); }
    f.schema = schema;

    // Ng model options doesn't play nice with undefined, might be defined
    // globally though
    f.ngModelOptions = f.ngModelOptions || {};
    return f;
  };

  var text = function(name, schema, options) {
    if (schema.type === 'string' && !schema.enum) {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'text';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  //default in json form for number and integer is a text field
  //input type="number" would be more suitable don't ya think?
  var number = function(name, schema, options) {
    if (schema.type === 'number') {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'number';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var integer = function(name, schema, options) {
    if (schema.type === 'integer') {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'number';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var checkbox = function(name, schema, options) {
    if (schema.type === 'boolean') {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'checkbox';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var select = function(name, schema, options) {
    if (schema.type === 'string' && schema.enum) {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'select';
      if (!f.titleMap) {
        f.titleMap = enumToTitleMap(schema.enum);
      }
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var checkboxes = function(name, schema, options) {
    if (schema.type === 'array' && schema.items && schema.items.enum) {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'checkboxes';
      if (!f.titleMap) {
        f.titleMap = enumToTitleMap(schema.items.enum);
      }
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var fieldset = function(name, schema, options) {

    if (schema.type === 'object') {
      var f   = stdFormObj(name, schema, options);
      f.type  = 'fieldset';
      f.items = [];
      options.lookup[sfPathProvider.stringify(options.path)] = f;

      //recurse down into properties
      angular.forEach(schema.properties, function(v, k) {
        var path = options.path.slice();
        path.push(k);
        if (options.ignore[sfPathProvider.stringify(path)] !== true) {
          var required = schema.required && schema.required.indexOf(k) !== -1;

          var def = defaultFormDefinition(k, v, {
            path: path,
            required: required || false,
            lookup: options.lookup,
            ignore: options.ignore
          });
          if (def) {
            f.items.push(def);
          }
        }
      });

      return f;
    }

  };

  var array = function(name, schema, options) {

    if (schema.type === 'array') {
      var f   = stdFormObj(name, schema, options);
      f.type  = 'array';
      f.key   = options.path;
      options.lookup[sfPathProvider.stringify(options.path)] = f;

      var required = schema.required &&
                     schema.required.indexOf(options.path(options.path.length - 1)) !== -1;

      // The default is to always just create one child. This works since if the
      // schemas items declaration is of type: "object" then we get a fieldset.
      // We also follow json form notatation, adding empty brackets "[]" to
      // signify arrays.

      var arrPath = options.path.slice();
      arrPath.push('');

      f.items = [defaultFormDefinition(name, schema.items, {
        path: arrPath,
        required: required || false,
        lookup: options.lookup,
        ignore: options.ignore
      })];

      return f;
    }

  };

  //First sorted by schema type then a list.
  //Order has importance. First handler returning an form snippet will be used.
  var defaults = {
    string:  [select, text],
    object:  [fieldset],
    number:  [number],
    integer: [integer],
    boolean: [checkbox],
    array:   [checkboxes, array]
  };

  var postProcessFn = function(form) { return form; };

  /**
   * Provider API
   */
  this.defaults    = defaults;
  this.stdFormObj  = stdFormObj;

  /**
   * Register a post process function.
   * This function is called with the fully merged
   * form definition (i.e. after merging with schema)
   * and whatever it returns is used as form.
   */
  this.postProcess = function(fn) {
    postProcessFn = fn;
  };

  /**
   * Append default form rule
   * @param {string}   type json schema type
   * @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
   *                        definition or undefined
   */
  this.appendRule = function(type, rule) {
    if (!defaults[type]) {
      defaults[type] = [];
    }
    defaults[type].push(rule);
  };

  /**
   * Prepend default form rule
   * @param {string}   type json schema type
   * @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
   *                        definition or undefined
   */
  this.prependRule = function(type, rule) {
    if (!defaults[type]) {
      defaults[type] = [];
    }
    defaults[type].unshift(rule);
  };

  /**
   * Utility function to create a standard form object.
   * This does *not* set the type of the form but rather all shared attributes.
   * You probably want to start your rule with creating the form with this method
   * then setting type and any other values you need.
   * @param {Object} schema
   * @param {Object} options
   * @return {Object} a form field defintion
   */
  this.createStandardForm = stdFormObj;
  /* End Provider API */

  this.$get = function() {

    var service = {};

    service.merge = function(schema, form, ignore, options) {
      form  = form || ['*'];
      options = options || {};

      var stdForm = service.defaults(schema, ignore, options);

      //simple case, we have a "*", just put the stdForm there
      var idx = form.indexOf('*');
      if (idx !== -1) {
        form  = form.slice(0, idx)
                    .concat(stdForm.form)
                    .concat(form.slice(idx + 1));
        return form;
      }

      //ok let's merge!
      //We look at the supplied form and extend it with schema standards
      var lookup = stdForm.lookup;
      return postProcessFn(form.map(function(obj) {

        //handle the shortcut with just a name
        if (typeof obj === 'string') {
          obj = {key: obj};
        }

        //If it has a titleMap make sure it's a list
        if (obj.titleMap) {
          obj.titleMap = canonicalTitleMap(obj.titleMap);
        }

        //if it's a type with items, merge 'em!
        if (obj.items) {
          obj.items = service.merge(schema, obj.items, ignore);
        }

        //if its has tabs, merge them also!
        if (obj.tabs) {
          angular.forEach(obj.tabs, function(tab) {
            tab.items = service.merge(schema, tab.items, ignore);
          });
        }

        //extend with std form from schema.
        if (obj.key) {
          if (typeof obj.key === 'string') {
            obj.key = sfPathProvider.parse(obj.key);
          }

          var str = sfPathProvider.stringify(obj.key);
          if (lookup[str]) {
            obj = angular.extend(lookup[str], obj);
          }
        }

        // Special case: checkbox
        // Since have to ternary state we need a default
        if (obj.type === 'checkbox' && angular.isUndefined(obj.schema['default'])) {
          obj.schema['default'] = false;
        }

        return obj;
      }));
    };

    /**
     * Create form defaults from schema
     */
    service.defaults = function(schema, ignore, globalOptions) {
      var form   = [];
      var lookup = {}; //Map path => form obj for fast lookup in merging
      ignore = ignore || {};
      globalOptions = globalOptions || {};

      if (schema.type === 'object') {
        angular.forEach(schema.properties, function(v, k) {
          if (ignore[k] !== true) {
            var required = schema.required && schema.required.indexOf(k[k.length - 1]) !== -1;
            var def = defaultFormDefinition(k, v, {
              path: [k],         // Path to this property in bracket notation.
              lookup: lookup,    // Extra map to register with. Optimization for merger.
              ignore: ignore,    // The ignore list of paths (sans root level name)
              required: required, // Is it required? (v4 json schema style)
              global: globalOptions // Global options, including form defaults
            });
            if (def) {
              form.push(def);
            }
          }
        });

      } else {
        throw new Error('Not implemented. Only type "object" allowed at root level of schema.');
      }
      return {form: form, lookup: lookup};
    };

    //Utility functions
    /**
     * Traverse a schema, applying a function(schema,path) on every sub schema
     * i.e. every property of an object.
     */
    service.traverseSchema = function(schema, fn, path, ignoreArrays) {
      ignoreArrays = angular.isDefined(ignoreArrays) ? ignoreArrays : true;

      path = path || [];

      var traverse = function(schema, fn, path) {
        fn(schema, path);
        angular.forEach(schema.properties, function(prop, name) {
          var currentPath = path.slice();
          currentPath.push(name);
          traverse(prop, fn, currentPath);
        });

        //Only support type "array" which have a schema as "items".
        if (!ignoreArrays && schema.items) {
          var arrPath = path.slice(); arrPath.push('');
          traverse(schema.items, fn, arrPath);
        }
      };

      traverse(schema, fn, path || []);
    };

    service.traverseForm = function(form, fn) {
      fn(form);
      angular.forEach(form.items, function(f) {
        service.traverseForm(f, fn);
      });

      if (form.tabs) {
        angular.forEach(form.tabs, function(tab) {
          angular.forEach(tab.items, function(f) {
            service.traverseForm(f, fn);
          });
        });
      }
    };

    return service;
  };

}]);
<commit_msg>Maintain enum order in select options https://github.com/Textalk/angular-schema-form/issues/82<commit_after>/**
 * Schema form service.
 * This service is not that useful outside of schema form directive
 * but makes the code more testable.
 */
angular.module('schemaForm').provider('schemaForm',
['sfPathProvider', function(sfPathProvider) {

  //Creates an default titleMap list from an enum, i.e. a list of strings.
  var enumToTitleMap = function(enm) {
    var titleMap = []; //canonical titleMap format is a list.
    enm.forEach(function(name) {
      titleMap.push({name: name, value: name});
    });
    return titleMap;
  };

  // Takes a titleMap in either object or list format and returns one in
  // in the list format.
  var canonicalTitleMap = function(titleMap, originalEnum) {
    if (!angular.isArray(titleMap)) {
      var canonical = [];
      if (originalEnum) {
        angular.forEach(originalEnum, function(value, index) {
          canonical.push({name: titleMap[value], value: value});
        });
      } else {
        angular.forEach(titleMap, function(name, value) {
          canonical.push({name: name, value: value});
        });
      }
      return canonical;
    }
    return titleMap;
  };

  var defaultFormDefinition = function(name, schema, options) {
    var rules = defaults[schema.type];
    if (rules) {
      var def;
      for (var i = 0; i < rules.length; i++) {
        def = rules[i](name, schema, options);
        //first handler in list that actually returns something is our handler!
        if (def) {
          return def;
        }
      }
    }
  };

  //Creates a form object with all common properties
  var stdFormObj = function(name, schema, options) {
    options = options || {};
    var f = options.global && options.global.formDefaults ?
            angular.copy(options.global.formDefaults) : {};
    if (options.global && options.global.supressPropertyTitles === true) {
      f.title = schema.title;
    } else {
      f.title = schema.title || name;
    }

    if (schema.description) { f.description = schema.description; }
    if (options.required === true || schema.required === true) { f.required = true; }
    if (schema.maxLength) { f.maxlength = schema.maxLength; }
    if (schema.minLength) { f.minlength = schema.maxLength; }
    if (schema.readOnly || schema.readonly) { f.readonly  = true; }
    if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
    if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }

    //Non standard attributes
    if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
    if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema.enum); }
    f.schema = schema;

    // Ng model options doesn't play nice with undefined, might be defined
    // globally though
    f.ngModelOptions = f.ngModelOptions || {};
    return f;
  };

  var text = function(name, schema, options) {
    if (schema.type === 'string' && !schema.enum) {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'text';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  //default in json form for number and integer is a text field
  //input type="number" would be more suitable don't ya think?
  var number = function(name, schema, options) {
    if (schema.type === 'number') {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'number';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var integer = function(name, schema, options) {
    if (schema.type === 'integer') {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'number';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var checkbox = function(name, schema, options) {
    if (schema.type === 'boolean') {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'checkbox';
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var select = function(name, schema, options) {
    if (schema.type === 'string' && schema.enum) {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'select';
      if (!f.titleMap) {
        f.titleMap = enumToTitleMap(schema.enum);
      }
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var checkboxes = function(name, schema, options) {
    if (schema.type === 'array' && schema.items && schema.items.enum) {
      var f = stdFormObj(name, schema, options);
      f.key  = options.path;
      f.type = 'checkboxes';
      if (!f.titleMap) {
        f.titleMap = enumToTitleMap(schema.items.enum);
      }
      options.lookup[sfPathProvider.stringify(options.path)] = f;
      return f;
    }
  };

  var fieldset = function(name, schema, options) {

    if (schema.type === 'object') {
      var f   = stdFormObj(name, schema, options);
      f.type  = 'fieldset';
      f.items = [];
      options.lookup[sfPathProvider.stringify(options.path)] = f;

      //recurse down into properties
      angular.forEach(schema.properties, function(v, k) {
        var path = options.path.slice();
        path.push(k);
        if (options.ignore[sfPathProvider.stringify(path)] !== true) {
          var required = schema.required && schema.required.indexOf(k) !== -1;

          var def = defaultFormDefinition(k, v, {
            path: path,
            required: required || false,
            lookup: options.lookup,
            ignore: options.ignore
          });
          if (def) {
            f.items.push(def);
          }
        }
      });

      return f;
    }

  };

  var array = function(name, schema, options) {

    if (schema.type === 'array') {
      var f   = stdFormObj(name, schema, options);
      f.type  = 'array';
      f.key   = options.path;
      options.lookup[sfPathProvider.stringify(options.path)] = f;

      var required = schema.required &&
                     schema.required.indexOf(options.path(options.path.length - 1)) !== -1;

      // The default is to always just create one child. This works since if the
      // schemas items declaration is of type: "object" then we get a fieldset.
      // We also follow json form notatation, adding empty brackets "[]" to
      // signify arrays.

      var arrPath = options.path.slice();
      arrPath.push('');

      f.items = [defaultFormDefinition(name, schema.items, {
        path: arrPath,
        required: required || false,
        lookup: options.lookup,
        ignore: options.ignore
      })];

      return f;
    }

  };

  //First sorted by schema type then a list.
  //Order has importance. First handler returning an form snippet will be used.
  var defaults = {
    string:  [select, text],
    object:  [fieldset],
    number:  [number],
    integer: [integer],
    boolean: [checkbox],
    array:   [checkboxes, array]
  };

  var postProcessFn = function(form) { return form; };

  /**
   * Provider API
   */
  this.defaults    = defaults;
  this.stdFormObj  = stdFormObj;

  /**
   * Register a post process function.
   * This function is called with the fully merged
   * form definition (i.e. after merging with schema)
   * and whatever it returns is used as form.
   */
  this.postProcess = function(fn) {
    postProcessFn = fn;
  };

  /**
   * Append default form rule
   * @param {string}   type json schema type
   * @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
   *                        definition or undefined
   */
  this.appendRule = function(type, rule) {
    if (!defaults[type]) {
      defaults[type] = [];
    }
    defaults[type].push(rule);
  };

  /**
   * Prepend default form rule
   * @param {string}   type json schema type
   * @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
   *                        definition or undefined
   */
  this.prependRule = function(type, rule) {
    if (!defaults[type]) {
      defaults[type] = [];
    }
    defaults[type].unshift(rule);
  };

  /**
   * Utility function to create a standard form object.
   * This does *not* set the type of the form but rather all shared attributes.
   * You probably want to start your rule with creating the form with this method
   * then setting type and any other values you need.
   * @param {Object} schema
   * @param {Object} options
   * @return {Object} a form field defintion
   */
  this.createStandardForm = stdFormObj;
  /* End Provider API */

  this.$get = function() {

    var service = {};

    service.merge = function(schema, form, ignore, options) {
      form  = form || ['*'];
      options = options || {};

      var stdForm = service.defaults(schema, ignore, options);

      //simple case, we have a "*", just put the stdForm there
      var idx = form.indexOf('*');
      if (idx !== -1) {
        form  = form.slice(0, idx)
                    .concat(stdForm.form)
                    .concat(form.slice(idx + 1));
        return form;
      }

      //ok let's merge!
      //We look at the supplied form and extend it with schema standards
      var lookup = stdForm.lookup;
      return postProcessFn(form.map(function(obj) {

        //handle the shortcut with just a name
        if (typeof obj === 'string') {
          obj = {key: obj};
        }

        //If it has a titleMap make sure it's a list
        if (obj.titleMap) {
          obj.titleMap = canonicalTitleMap(obj.titleMap);
        }

        //if it's a type with items, merge 'em!
        if (obj.items) {
          obj.items = service.merge(schema, obj.items, ignore);
        }

        //if its has tabs, merge them also!
        if (obj.tabs) {
          angular.forEach(obj.tabs, function(tab) {
            tab.items = service.merge(schema, tab.items, ignore);
          });
        }

        //extend with std form from schema.
        if (obj.key) {
          if (typeof obj.key === 'string') {
            obj.key = sfPathProvider.parse(obj.key);
          }

          var str = sfPathProvider.stringify(obj.key);
          if (lookup[str]) {
            obj = angular.extend(lookup[str], obj);
          }
        }

        // Special case: checkbox
        // Since have to ternary state we need a default
        if (obj.type === 'checkbox' && angular.isUndefined(obj.schema['default'])) {
          obj.schema['default'] = false;
        }

        return obj;
      }));
    };

    /**
     * Create form defaults from schema
     */
    service.defaults = function(schema, ignore, globalOptions) {
      var form   = [];
      var lookup = {}; //Map path => form obj for fast lookup in merging
      ignore = ignore || {};
      globalOptions = globalOptions || {};

      if (schema.type === 'object') {
        angular.forEach(schema.properties, function(v, k) {
          if (ignore[k] !== true) {
            var required = schema.required && schema.required.indexOf(k[k.length - 1]) !== -1;
            var def = defaultFormDefinition(k, v, {
              path: [k],         // Path to this property in bracket notation.
              lookup: lookup,    // Extra map to register with. Optimization for merger.
              ignore: ignore,    // The ignore list of paths (sans root level name)
              required: required, // Is it required? (v4 json schema style)
              global: globalOptions // Global options, including form defaults
            });
            if (def) {
              form.push(def);
            }
          }
        });

      } else {
        throw new Error('Not implemented. Only type "object" allowed at root level of schema.');
      }
      return {form: form, lookup: lookup};
    };

    //Utility functions
    /**
     * Traverse a schema, applying a function(schema,path) on every sub schema
     * i.e. every property of an object.
     */
    service.traverseSchema = function(schema, fn, path, ignoreArrays) {
      ignoreArrays = angular.isDefined(ignoreArrays) ? ignoreArrays : true;

      path = path || [];

      var traverse = function(schema, fn, path) {
        fn(schema, path);
        angular.forEach(schema.properties, function(prop, name) {
          var currentPath = path.slice();
          currentPath.push(name);
          traverse(prop, fn, currentPath);
        });

        //Only support type "array" which have a schema as "items".
        if (!ignoreArrays && schema.items) {
          var arrPath = path.slice(); arrPath.push('');
          traverse(schema.items, fn, arrPath);
        }
      };

      traverse(schema, fn, path || []);
    };

    service.traverseForm = function(form, fn) {
      fn(form);
      angular.forEach(form.items, function(f) {
        service.traverseForm(f, fn);
      });

      if (form.tabs) {
        angular.forEach(form.tabs, function(tab) {
          angular.forEach(tab.items, function(f) {
            service.traverseForm(f, fn);
          });
        });
      }
    };

    return service;
  };

}]);
<|endoftext|>


<commit_before>$.register({
  rule: {
    host: /^([\w]{8}|www)\.(allanalpass|a[mn]y|cash4files|deb|drstickyfingers|dyo|fapoff|filesonthe|free(an|gaysitepass)|galleries|goneviral|hornywood|link(babes|bucks|galleries|seer)|megaline|miniurls|picbucks|picturesetc|poontown|qqc|qvvo|realfiles|rqq|serious(deals|files|urls)|sexpalace|these(blogs|files|forums)|(these|those|u)galleries|tiny(bucks|links)|tnabucks|tubeviral|uber(picz|vidz)|ubucks|ultrafiles|url(beat|pulse)|whackyvidz|youfap|yyv|zff|zxxo)\.(com?|net|gs|me|tv|bz|us)/,
  },
  ready: function () {
    'use strict';

    $.removeAllTimer();
    $.resetCookies();

    if (window.location.pathname.indexOf('verify') >= 0) {
      $.openLink('/');
      return;
    }

    var token = null;
    $.$$('script').find(function (n) {
      var m = n.innerHTML.match(/Token : '([\w\d]+)'/);
      if (m) {
        token = m[1];
      }
      return !!m;
    });
    if (!token) {
      _.warn('pattern changed');
      return;
    }

    var i = setInterval(function () {
      $.get('/intermission/loadTargetUrl', {
        t: token,
      }, function (text) {
        var data = JSON.parse(text);
        if (data.Success && !data.AdBlockSpotted && data.Url) {
          clearInterval(i);
          $.openLink(data.Url);
        }
      });
    }, 1000);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>linkbucks.com<commit_after>$.register({
  rule: {
    host: /^([\w]{8}|www)\.(allanalpass|a[mn]y|cash4files|deb|drstickyfingers|dyo|fapoff|filesonthe|free(an|gaysitepass)|galleries|goneviral|hornywood|link(babes|bucks|galleries|seer)|megaline|miniurls|picbucks|picturesetc|poontown|qqc|qvvo|realfiles|rqq|serious(deals|files|urls)|sexpalace|these(blogs|files|forums)|(these|those|u)galleries|tiny(bucks|links)|tnabucks|tubeviral|uber(picz|vidz)|ubucks|ultrafiles|url(beat|pulse)|whackyvidz|youfap|yyv|zff|zxxo)\.(com?|net|gs|me|tv|bz|us)/,
  },
  ready: function () {
    'use strict';

    $.removeAllTimer();
    $.resetCookies();

    if (window.location.pathname.indexOf('verify') >= 0) {
      $.openLink('/');
      return;
    }

    var token = null;
    $.$$('script').find(function (n) {
      var m = n.innerHTML.match(/AdPopUrl : '.+\?ref=([\w\d]+)'/);
      if (m) {
        token = m[1];
      }
      return !!m;
    });
    if (!token) {
      _.warn('pattern changed');
      return;
    }

    var i = setInterval(function () {
      $.get('/intermission/loadTargetUrl', {
        t: token,
      }, function (text) {
        var data = JSON.parse(text);
        if (data.Success && !data.AdBlockSpotted && data.Url) {
          clearInterval(i);
          $.openLink(data.Url);
        }
      });
    }, 1000);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>(function() {

  // copy from Lbjs, can not retrive by unsafeWindow
  function ConvertFromHex (str) {
    var result = [];
    while (str.length >= 2) {
      result.push(String.fromCharCode(parseInt(str.substring(0, 2), 16)));
      str = str.substring(2, str.length);
    }
    return result.join("");
  }
  // function name MATTERS, do not change this function
  // arguments.callee does not exists in strict mode
  var Encode = function (str) {
    var s = [], j = 0, x, res = '', k = arguments.callee.toString().replace(/\s+/g, "");
    for (var i = 0; i < 256; i++) {
      s[i] = i;
    }
    for (i = 0; i < 256; i++) {
      j = (j + s[i] + k.charCodeAt(i % k.length)) % 256;
      x = s[i];
      s[i] = s[j];
      s[j] = x;
    }
    i = 0;
    j = 0;
    for (var y = 0; y < str.length; y++) {
      i = (i + 1) % 256;
      j = (j + s[i]) % 256;
      x = s[i];
      s[i] = s[j];
      s[j] = x;
      res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
    }
    return res;
  };

  var hostRules = [
    /^(([\w]{8}|www)\.)?(allanalpass|cash4files|drstickyfingers|fapoff|freegaysitepass|(gone|tube)viral|(pic|tna)bucks|whackyvidz)\.com$/,
    /^(([\w]{8}|www)\.)?(a[mn]y|deb|dyo|sexpalace)\.gs$/,
    /^(([\w]{8}|www)\.)?(filesonthe|poontown|seriousdeals|ultrafiles|urlbeat)\.net$/,
    /^(([\w]{8}|www)\.)?freean\.us$/,
    /^(([\w]{8}|www)\.)?galleries\.bz$/,
    /^(([\w]{8}|www)\.)?hornywood\.tv$/,
    /^(([\w]{8}|www)\.)?link(babes|bucks)\.com$/,
    /^(([\w]{8}|www)\.)?(megaline|miniurls|qqc|rqq|tinylinks|yyv|zff)\.co$/,
    /^(([\w]{8}|www)\.)?(these(blog|forum)s)\.com$/,
    /^(([\w]{8}|www)\.)?youfap\.me$/,
    /^warning-this-linkcode-will-cease-working-soon\.www\.linkbucksdns\.com$/,
  ];

  (function () {
    'use strict';

    function findToken (context) {
      var script = $.$$('script', context).find(function (n) {
        if (n.innerHTML.indexOf('window[\'init\' + \'Lb\' + \'js\' + \'\']') < 0) {
          return _.nop;
        }
        return n.innerHTML;
      });
      if (!script) {
        _.warn('pattern changed');
        return null;
      }
      script = script.payload;

      var m = script.match(/AdPopUrl\s*:\s*'.+\?ref=([\w\d]+)'/);
      var token = m[1];
      m = script.match(/=\s*(\d+);/);
      var ak = parseInt(m[1], 10);
      var re = /\+\s*(\d+);/g;
      var tmp = null;
      // get second (i.e. the real) salt
      while((m = re.exec(script)) !== null) {
        tmp = m[1];
      }
      ak += parseInt(tmp, 10);

      return {
        t: token,
        aK: ak,
      };
    }

    function sendRequest (token) {
      _.info('sending token: %o', token);

      var i = setInterval(function () {
        $.get('/intermission/loadTargetUrl', token, function (text) {
          var data = JSON.parse(text);

          _.info('response: %o', data);

          if (!data.Success && data.Errors[0] === 'Invalid token') {
            // somehow this token is invalid, reload to get new one
            _.info('got invalid token');
            clearInterval(i);
            $.get(window.location.toString(), {}, function (text) {
              var d = $.toDOM(text);
              var t = findToken(d);
              sendRequest(t);
            });
            return;
          }
          if (data.Success && !data.AdBlockSpotted && data.Url) {
            clearInterval(i);
            $.openLinkWithReferer(data.Url);
            return;
          }
        });
      }, 1000);
    }

    $.register({
      rule: {
        host: hostRules,
        path: /^\/\w+\/url\/(.*)$/,
      },
      ready: function(m) {
        $.removeAllTimer();
        $.resetCookies();
        $.removeNodes('iframe');

        if (!m.path[1]) {
          throw _.AdsBypasserError('wrong url pattern');
        }
        var url = m.path[1] + window.location.search;

        var match = $.searchScripts(/UrlEncoded: ([^,]+)/);
        _.info(match);
        if (match && match[1] === 'true') {
          // encrypted url
          _.info('??');
          try {
          url = Encode(ConvertFromHex(url));
          _.info('!!');
        } catch (e) {_.info(e);}
        }
        _.info(url);

        $.openLinkWithReferer(url);
      }
    });

    $.register({
      rule: {
        host: hostRules,
      },
      ready: function () {
        $.removeAllTimer();
        $.resetCookies();
        $.removeNodes('iframe');

        if (window.location.pathname.indexOf('verify') >= 0) {
          // NOTE dirty fix
          $.openLink('../');
          return;
        }

        var token = findToken(document);
        sendRequest(token);
      },
    });

    // for entry script
    // this is stupid, but inpecting script on every page is too heavy
    $.register({
      rule: {
        query: /^\?_lbGate=\d+$/,
      },
      start: function () {
        $.setCookie('_lbGatePassed', 'true');
        $.openLink(window.location.pathname);
      },
    });

  })();

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Update comment.<commit_after>(function() {

  // copy from Lbjs, can not get from unsafeWindow
  function ConvertFromHex (str) {
    var result = [];
    while (str.length >= 2) {
      result.push(String.fromCharCode(parseInt(str.substring(0, 2), 16)));
      str = str.substring(2, str.length);
    }
    return result.join("");
  }
  // function name MATTERS, do not change this function
  // arguments.callee does not exists in strict mode
  var Encode = function (str) {
    var s = [], j = 0, x, res = '', k = arguments.callee.toString().replace(/\s+/g, "");
    for (var i = 0; i < 256; i++) {
      s[i] = i;
    }
    for (i = 0; i < 256; i++) {
      j = (j + s[i] + k.charCodeAt(i % k.length)) % 256;
      x = s[i];
      s[i] = s[j];
      s[j] = x;
    }
    i = 0;
    j = 0;
    for (var y = 0; y < str.length; y++) {
      i = (i + 1) % 256;
      j = (j + s[i]) % 256;
      x = s[i];
      s[i] = s[j];
      s[j] = x;
      res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
    }
    return res;
  };

  var hostRules = [
    /^(([\w]{8}|www)\.)?(allanalpass|cash4files|drstickyfingers|fapoff|freegaysitepass|(gone|tube)viral|(pic|tna)bucks|whackyvidz)\.com$/,
    /^(([\w]{8}|www)\.)?(a[mn]y|deb|dyo|sexpalace)\.gs$/,
    /^(([\w]{8}|www)\.)?(filesonthe|poontown|seriousdeals|ultrafiles|urlbeat)\.net$/,
    /^(([\w]{8}|www)\.)?freean\.us$/,
    /^(([\w]{8}|www)\.)?galleries\.bz$/,
    /^(([\w]{8}|www)\.)?hornywood\.tv$/,
    /^(([\w]{8}|www)\.)?link(babes|bucks)\.com$/,
    /^(([\w]{8}|www)\.)?(megaline|miniurls|qqc|rqq|tinylinks|yyv|zff)\.co$/,
    /^(([\w]{8}|www)\.)?(these(blog|forum)s)\.com$/,
    /^(([\w]{8}|www)\.)?youfap\.me$/,
    /^warning-this-linkcode-will-cease-working-soon\.www\.linkbucksdns\.com$/,
  ];

  (function () {
    'use strict';

    function findToken (context) {
      var script = $.$$('script', context).find(function (n) {
        if (n.innerHTML.indexOf('window[\'init\' + \'Lb\' + \'js\' + \'\']') < 0) {
          return _.nop;
        }
        return n.innerHTML;
      });
      if (!script) {
        _.warn('pattern changed');
        return null;
      }
      script = script.payload;

      var m = script.match(/AdPopUrl\s*:\s*'.+\?ref=([\w\d]+)'/);
      var token = m[1];
      m = script.match(/=\s*(\d+);/);
      var ak = parseInt(m[1], 10);
      var re = /\+\s*(\d+);/g;
      var tmp = null;
      // get second (i.e. the real) salt
      while((m = re.exec(script)) !== null) {
        tmp = m[1];
      }
      ak += parseInt(tmp, 10);

      return {
        t: token,
        aK: ak,
      };
    }

    function sendRequest (token) {
      _.info('sending token: %o', token);

      var i = setInterval(function () {
        $.get('/intermission/loadTargetUrl', token, function (text) {
          var data = JSON.parse(text);

          _.info('response: %o', data);

          if (!data.Success && data.Errors[0] === 'Invalid token') {
            // somehow this token is invalid, reload to get new one
            _.info('got invalid token');
            clearInterval(i);
            $.get(window.location.toString(), {}, function (text) {
              var d = $.toDOM(text);
              var t = findToken(d);
              sendRequest(t);
            });
            return;
          }
          if (data.Success && !data.AdBlockSpotted && data.Url) {
            clearInterval(i);
            $.openLinkWithReferer(data.Url);
            return;
          }
        });
      }, 1000);
    }

    $.register({
      rule: {
        host: hostRules,
        path: /^\/\w+\/url\/(.*)$/,
      },
      ready: function(m) {
        $.removeAllTimer();
        $.resetCookies();
        $.removeNodes('iframe');

        if (!m.path[1]) {
          throw _.AdsBypasserError('wrong url pattern');
        }
        var url = m.path[1] + window.location.search;

        var match = $.searchScripts(/UrlEncoded: ([^,]+)/);
        _.info(match);
        if (match && match[1] === 'true') {
          // encrypted url
          _.info('??');
          try {
          url = Encode(ConvertFromHex(url));
          _.info('!!');
        } catch (e) {_.info(e);}
        }
        _.info(url);

        $.openLinkWithReferer(url);
      }
    });

    $.register({
      rule: {
        host: hostRules,
      },
      ready: function () {
        $.removeAllTimer();
        $.resetCookies();
        $.removeNodes('iframe');

        if (window.location.pathname.indexOf('verify') >= 0) {
          // NOTE dirty fix
          $.openLink('../');
          return;
        }

        var token = findToken(document);
        sendRequest(token);
      },
    });

    // for entry script
    // this is stupid, but inspecting script on every page is too heavy
    $.register({
      rule: {
        query: /^\?_lbGate=\d+$/,
      },
      start: function () {
        $.setCookie('_lbGatePassed', 'true');
        $.openLink(window.location.pathname);
      },
    });

  })();

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>///
// Dependencies
///

import React, { Component } from 'react';
import classNames from 'classnames';

///
// View
///

class CardsListView extends Component {
	render() {
		const className = classNames(
			'cards-list',
			{'theme-dark': this.props.theme === 'dark'},
			this.props.className
		);

		return (

				{this.props.children}

		);
	}
}

export default CardsListView;

<commit_msg>Preparing for light theme in CardsList<commit_after>///
// Dependencies
///

import React, { Component } from 'react';
import classNames from 'classnames';

///
// View
///

class CardsListView extends Component {
	render() {
		const className = classNames(
			'cards-list',
			{
				'theme-dark': this.props.theme === 'dark',
				'theme-light': this.props.theme !== 'dark',
			},
			this.props.className
		);

		return (

				{this.props.children}

		);
	}
}

export default CardsListView;

<|endoftext|>