<commit_before>;(function() {

	// Based on jQuery.extend
	var extend = function() {
		// copy reference to target object
		var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, toString = Object.prototype.toString;

		var isFunction = function( obj ) {
			return toString.call(obj) === "[object Function]";
		};

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !isFunction(target) ) {
			target = {};
		}

		// extend Object itself if only one argument is passed
		if ( length == i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( var name in options ) {
					var src = target[ name ], copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging object values
					if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
						target[ name ] = extend( deep,
							// Never move original objects, clone them
							src || ( copy.length != null ? [ ] : { } )
						, copy );
					}
					// Don't bring in undefined values
					else if ( copy !== undefined ) {
						target[ name ] = copy;
					}

				}
			}
		}

		// Return the modified object
		return target;
	};

	// temporary crappy method to get the base path
	var getBasePath = function () {
		var nodes = document.getElementsByTagName('script'), i, base;

		for (i = 0; i < nodes.length; i = i + 1) {
			var src = nodes[i].src;
			var match = src.match(/^(.*)yui[\.-].*js(\?.*)?$/);

			if (match && (base = match[1])) {
				base = base.substring(0, base.length - 4);
				break;
			}
		}

		return base;
	};

	/*!
	 * Alloy JavaScript Library v@VERSION
	 * http://alloyui.com/
	 *
	 * Copyright (c) 2009 Liferay Inc.
	 * Licensed under the MIT license.
	 * http://alloyui.com/License
	 *
	 * Nate Cavanaugh (nate.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Date: @DATE
	 * Revision: @REVISION
	 */

	window.Alloy = window.Alloy || {};

	var defaults = {};
	var defaultModules = [ 'event', 'oop', 'widget' ];

	var errorCallback = function(instance, result) {
		if (!result.success) {
			throw result.msg;
		}
	};

	if ('defaults' in Alloy) {
		defaults = Alloy.defaults;
	}

	// get the base path in case the user has not specified
	if (!('base' in defaults)) {
		defaults.base = getBasePath();
	}

	var ALLOY = YUI( extend({}, defaults) );

	var originalConfig = ALLOY.config;

	// adding callback for .use()
	defaultModules.push(errorCallback);

	// loading default modules
	ALLOY.use.apply(ALLOY, defaultModules);

	Alloy = function(o) {
		var instance = this;

		ALLOY.config = ALLOY.merge(originalConfig, Alloy.defaults);

		if (o || instance instanceof Alloy) {
			// new Alloy() creates a new YUI sandbox
			return YUI( ALLOY.merge(ALLOY.config, o) );
		}

		// returns the cached YUI sandbox
		return ALLOY;
	};

	extend(Alloy, YUI, {
		__version: '@VERSION',

		extend: extend,

		defaults: defaults
	});

	Alloy.extend(Alloy.prototype, {
		ready: function() {
			var instance = this;
			var slice = Array.prototype.slice;
			var args = slice.call(arguments, 0), index = args.length - 1;

			// user callback
			var fn = args[index];

			// array with YUI modules to be loaded
			var modules = slice.call(arguments, 0, index);

			if (!modules.length) {
				modules.push('event');
			}

			// adding Alloy().use() callback
			modules.push(
				function(instance) {
					var args = arguments;
					instance.on('domready', function() {
					   fn.apply(this, args);
					});
				}
			);

			instance.use.apply(instance, modules);
		}
	});

})();<commit_msg>Change the getBasePath method to remove the last path level instead of calculate the substring<commit_after>;(function() {

	// Based on jQuery.extend
	var extend = function() {
		// copy reference to target object
		var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, toString = Object.prototype.toString;

		var isFunction = function( obj ) {
			return toString.call(obj) === "[object Function]";
		};

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !isFunction(target) ) {
			target = {};
		}

		// extend Object itself if only one argument is passed
		if ( length == i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( var name in options ) {
					var src = target[ name ], copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging object values
					if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
						target[ name ] = extend( deep,
							// Never move original objects, clone them
							src || ( copy.length != null ? [ ] : { } )
						, copy );
					}
					// Don't bring in undefined values
					else if ( copy !== undefined ) {
						target[ name ] = copy;
					}

				}
			}
		}

		// Return the modified object
		return target;
	};

	// temporary crappy method to get the base path
	var getBasePath = function () {
		var nodes = document.getElementsByTagName('script'), i, base;

		for (i = 0; i < nodes.length; i = i + 1) {
			var src = nodes[i].src;
			var match = src.match(/^(.*)yui[\.-].*js(\?.*)?$/);

			if (match && (base = match[1])) {
				base = base.split(/[\/\\]/);

				// removing the last path level /yui/../
				base = base.splice(0, base.length - 2).concat(
					base.splice(base.length - 1, base.length)
				);

				break;
			}
		}

		return base.join('/');
	};

	/*!
	 * Alloy JavaScript Library v@VERSION
	 * http://alloyui.com/
	 *
	 * Copyright (c) 2009 Liferay Inc.
	 * Licensed under the MIT license.
	 * http://alloyui.com/License
	 *
	 * Nate Cavanaugh (nate.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Date: @DATE
	 * Revision: @REVISION
	 */

	window.Alloy = window.Alloy || {};

	var defaults = {};
	var defaultModules = [ 'event', 'oop', 'widget' ];

	var errorCallback = function(instance, result) {
		if (!result.success) {
			throw result.msg;
		}
	};

	if ('defaults' in Alloy) {
		defaults = Alloy.defaults;
	}

	// get the base path in case the user has not specified
	if (!('base' in defaults)) {
		defaults.base = getBasePath();
	}

	var ALLOY = YUI( extend({}, defaults) );

	var originalConfig = ALLOY.config;

	// adding callback for .use()
	defaultModules.push(errorCallback);

	// loading default modules
	ALLOY.use.apply(ALLOY, defaultModules);

	Alloy = function(o) {
		var instance = this;

		ALLOY.config = ALLOY.merge(originalConfig, Alloy.defaults);

		if (o || instance instanceof Alloy) {
			// new Alloy() creates a new YUI sandbox
			return YUI( ALLOY.merge(ALLOY.config, o) );
		}

		// returns the cached YUI sandbox
		return ALLOY;
	};

	extend(Alloy, YUI, {
		__version: '@VERSION',

		extend: extend,

		defaults: defaults
	});

	Alloy.extend(Alloy.prototype, {
		ready: function() {
			var instance = this;
			var slice = Array.prototype.slice;
			var args = slice.call(arguments, 0), index = args.length - 1;

			// user callback
			var fn = args[index];

			// array with YUI modules to be loaded
			var modules = slice.call(arguments, 0, index);

			if (!modules.length) {
				modules.push('event');
			}

			// adding Alloy().use() callback
			modules.push(
				function(instance) {
					var args = arguments;
					instance.on('domready', function() {
					   fn.apply(this, args);
					});
				}
			);

			instance.use.apply(instance, modules);
		}
	});

})();<|endoftext|>


<commit_before>(function () {

    var log = {
            msg: function (msg) {
                if (console && console.log) {
                    console.log(msg);
                }
            },

            err: function (msg) {
                if (console && console.error) {
                    console.error(msg);
                }
            }
        },

        norne = function (opts, callback) {
            callback.apply(norne, norne.world(opts));
        };

    /**
     *  basic functionality
     */
    _(norne).extend({

        /**
         * Used to extend norne itself.
         *
         * @param {String} name Name of the extension
         * @param {Object} opts Optional object whos properties
         *                      are getting mapped to fn
         * @param {Function} fn Optional function that gets appended
         *
         */
        register: function (name, opts, fn) {

            if (norne[name]) {
                log.err('Module with this name already exists (' + name + ')');
                return
            }

            if (!_(name).isString()) {
                log.err('First parameter must be a string').
                return
            }

            if (norne[name] !== undefined) {
                log.err('An extension called "'+ name +'" already exists');
                return;
            }

            if (_(opts).isFunction()) {
                fn = opts
                opts = {}
            }

            opts = opts || {};
            fn = fn || function () {};

            /*
             *  bind opts context to the function
             *  and extend the returned proxy
             */
            fn = _(fn).bind(opts);
            _(fn).extend(opts);

            norne[name] = fn;
            return norne[name];
        }
    });

    norne.register('log', log, log.msg);
    window.norne = norne;
}());<commit_msg>fixed wrong property encapsulation in norne.register; Optimized norne.log<commit_after>(function () {
    'use strict';

    var log = {
            __out: function (channel, context, args) {
                channel.apply(context, args);
            },

            msg: function () {
                if (console && console.log) {
                    var args = Array.prototype.slice.call(arguments);
                    this.__out(console.log, console, args);
                }
            },

            err: function () {
                if (console && console.error) {
                    var args = Array.prototype.slice.call(arguments);
                    this.__out(console.error, console, args);
                }
            },

            trace: function() {
                if (norne.debug) {
                    this.msg(arguments);
                }
            }
        },

        norne = function (opts, callback) {
            log.trace('core: norne called as fn with', { opts: opts, callback: callback });
            callback.call(norne, norne.world(opts));
        },

        exc = { toString: function () { return this.name } };

    /**
     *  basic functionality
     */
    _(norne).extend({

        debug: true,
        version: 0.1,

        /**
         * Used to extend norne itself.
         *
         * @param {String} name Name of the extension
         * @param {Object} opts Optional object whos properties
         *                      are getting mapped to fn
         * @param {Function} fn Optional function that gets appended
         *
         */
        register: function (name, opts, fn) {
            var registerExc = _(exc).extend({ name: 'norne.registerException' }),
                proxy;

            if (!_(name).isString()) {
                throw _(exc).extend({
                    message: 'First parameter must be a string.'
                });
            }

            if (norne[name]) {
                throw _(exc).extend({
                    message: 'Module with this name already exists (' + name + ')'
                });
            }

            if (_(opts).isFunction()) {
                fn = opts
                opts = {}
            }

            opts = opts || {};
            fn = fn || function () {};

            proxy = function () {
                var args = Array.prototype.slice.call(arguments);
                args.unshift(norne);
                return fn.apply(norne[name], args);
            }

            _(proxy).extend(opts);
            norne[name] = proxy;
        },

        toString: function () {
            return 'Norne Engine Version ' + this.version;
        }
    });

    norne.register('log', log, log.msg);
    window.norne = norne;
}());<|endoftext|>


<commit_before>"use strict";
(function(window) {
    var config = {
      silent: false
    }
    var directives = {};
    var components = {};

    /**
    * Converts attributes into key-value pairs
    * @param {Node} node
    * @return {Object} Key-Value pairs of Attributes
    */
    var extractAttrs = function(node) {
      var attrs = {};
      if(!node.attributes) return attrs;
      var rawAttrs = node.attributes;
      for(var i = 0; i < rawAttrs.length; i++) {
        attrs[rawAttrs[i].name] = rawAttrs[i].value
      }

      return attrs;
    }

    /**
    * Compiles a template with given data
    * @param {String} template
    * @param {Object} data
    * @return {String} Template with data rendered
    */
    var compileTemplate = function(template, data) {
      var code = template,
          re = /{{([A-Za-z0-9_.\[\]]+)}}/gi;
      code.replace(re, function(match, p) {
        code = code.replace(match, "` + data." + p + " + `");
      });
      var compile = new Function("data", "var out = `" + code + "`; return out");
      var output = compile(data);
      return output;
    }

    /**
    * Gets Root Element
    * @param {String} html
    * @return {Node} Root Element
    */
    var getRootElement = function(html) {
      var dummy = document.createElement('div');
      dummy.innerHTML = html;
      return dummy.firstChild;
    }

    /**
    * Merges two Objects
    * @param {Object} obj
    * @param {Object} obj2
    * @return {Object} Merged Objects
    */
    function merge(obj, obj2) {
      for (var key in obj2) {
        if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
      }
      return obj;
    }

    function Moon(opts) {
        var _el = opts.el;
        var _data = opts.data;
        var _methods = opts.methods;
        var _hooks = opts.hooks || {created: function() {}, mounted: function() {}, updated: function() {}, destroyed: function() {}};
        var _destroyed = false;
        var self = this;
        this.$el = document.querySelector(_el);
        this.$components = merge(opts.components || {}, components);
        this.$dom = {type: this.$el.nodeName, children: [], node: this.$el};

        // Change state when $data is changed
        Object.defineProperty(this, '$data', {
            get: function() {
                return _data;
            },
            set: function(value) {
                _data = value;
                this.build(this.$dom.children);
            },
            configurable: true
        });

        /**
        * Logs a Message
        * @param {String} msg
        */
        this.log = function(msg) {
          if(!config.silent) console.log(msg);
        }

        /**
        * Throws an Error
        * @param {String} msg
        */
        this.error = function(msg) {
          console.log("Moon ERR: " + msg);
        }

        /**
        * Creates an object to be used in a Virtual DOM
        * @param {String} type
        * @param {Array} children
        * @param {String} val
        * @param {Object} props
        * @param {Node} node
        * @return {Object} Object usable in Virtual DOM
        */
        this.createElement = function(type, children, val, props, node) {
          return {type: type, children: children, val: val, props: props, node: node};
        }

        /**
        * Create Elements Recursively For all Children
        * @param {Array} children
        * @return {Array} Array of elements usable in Virtual DOM
        */
        this.recursiveChildren = function(children) {
          var recursiveChildrenArr = [];
          for(var i = 0; i < children.length; i++) {
            var child = children[i];
            recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
          }
          return recursiveChildrenArr;
        }

        /**
        * Creates Virtual DOM
        * @param {Node} node
        */
        this.createVirtualDOM = function(node) {
          var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
          this.$dom = vdom;
        }

        /**
        * Compiles a Component
        * @param {Node} node
        */
        this.compileComponent = function(name, component) {
          var dummy = document.createElement('div');
          dummy.innerHTML = getRootElement(component);
          component.outerHTML = dummy.outerHTML;
        }

        /**
        * Sets Value in Data
        * @param {String} key
        * @param {String} val
        */
        this.set = function(key, val) {
          this.$data[key] = val;
          if(!_destroyed) this.build(this.$dom.children);
          if(_hooks.updated) {
            _hooks.updated();
          }
        }

        /**
        * Gets Value in Data
        * @param {String} key
        * @return {String} Value of key in data
        */
        this.get = function(key) {
          return this.$data[key];
        }

        /**
        * Calls a method
        * @param {String} method
        */
        this.method = function(method) {
          _methods[method]();
        }

        this.destroy = function() {
          Object.defineProperty(this, '$data', {
            set: function(value) {
              _data = value;
            }
          });
          _destroyed = true;
          if(_hooks.destroyed) _hooks.destroyed();
        }

        // Default Directives
        directives["m-if"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.textContent = "";
          } else {
            el.textContent = compileTemplate(vdom.val, self.$data);
          }
        }

        directives["m-show"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.style.display = 'none';
          } else {
            el.style.display = 'block';
          }
        }

        directives["m-on"] = function(el, val, vdom) {
          var splitVal = val.split(":");
          var eventToCall = splitVal[0];
          var methodToCall = splitVal[1];
          el.addEventListener(eventToCall, function() {
            self.method(methodToCall);
          });
          el.removeAttribute("m-on");
          delete vdom.props["m-on"];
        }

        directives["m-model"] = function(el, val, vdom) {
          el.value = self.get(val);
          el.addEventListener("input", function() {
            self.set(val, el.value);
          });
          el.removeAttribute("m-model");
          delete vdom.props["m-model"];
        }

        directives["m-once"] = function(el, val, vdom) {
          vdom.val = el.textContent;
          for(var child in vdom.children) {
            vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data);
          }
        }

        directives["m-text"] = function(el, val, vdom) {
          el.textContent = val;
        }

        directives["m-html"] = function(el, val, vdom) {
          el.innerHTML = val;
        }

        directives["m-mask"] = function(el, val, vdom) {

        }

        // directives["m-for"] = function(el, val, vdom) {
        //   var splitVal = val.split(" in ");
        //   var alias = splitVal[0];
        //   var arr = self.get(splitVal[1]);
        //   var clone = el.cloneNode(true);
        //   var oldVal = vdom.val;
        //   var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]');
        //   el.innerHTML = compileTemplate(compilable, self.$data);
        //   for(var i = 1; i < arr.length; i++) {
        //     var newClone = clone.cloneNode(true);
        //     var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']');
        //     newClone.innerHTML = compileTemplate(compilable, self.$data);
        //     var parent = el.parentNode;
        //     parent.appendChild(newClone);
        //   }
        //   vdom.val = el.textContent;
        //   delete vdom.props["m-for"];
        // }

        /**
        * Builds the DOM With Data
        * @param {Array} children
        */
        this.build = function(children) {
          for(var i = 0; i < children.length; i++) {
            var el = children[i];

            if(el.type === "#text") {
              el.node.textContent = compileTemplate(el.val, this.$data);
            } else if(el.props) {
              for(var prop in el.props) {
                var propVal = el.props[prop];
                var compiledProperty = compileTemplate(propVal, this.$data);
                var directive = directives[prop];
                if(directive) {
                  el.node.removeAttribute(prop);
                  directive(el.node, compiledProperty, el);
                }

                if(!directive) el.node.setAttribute(prop, compiledProperty);
              }
            }

            if(this.$components[el.type.toLowerCase()]) {
              this.compileComponent(el.type.toLowerCase(), el.node);
            }

            this.build(el.children);
          }
        }

        /**
        * Initializes Moon
        */
        this.init = function() {
          this.log("======= Moon =======");
          if(_hooks.created) {
            _hooks.created();
          }
          this.createVirtualDOM(this.$el);
          this.build(this.$dom.children);
          if(_hooks.mounted) {
            _hooks.mounted();
          }
        }

        // Initialize 🎉
        this.init();
    }

    /**
    * Sets the Configuration of Moon
    * @param {Object} opts
    */
    Moon.config = function(opts) {
      if(opts.silent) {
        config.silent = opts.silent;
      }
    }

    /**
    * Runs an external Plugin
    * @param {Object} plugin
    */
    Moon.use = function(plugin) {
      plugin.init(Moon);
    }

    /**
    * Creates a Directive
    * @param {String} name
    * @param {Function} action
    */
    Moon.directive = function(name, action) {
      directives["m-" + name] = action;
    }

    /**
    * Creates a Component
    * @param {String} name
    * @param {Function} action
    */
    Moon.component = function(name, action) {
      components[name] = action;
    }

    /**
    * Makes an AJAX Request
    * @param {String} method
    * @param {String} url
    * @param {Object} params
    * @param {Function} cb
    */
    Moon.ajax = function(method, url, params, cb) {
      var xmlHttp = new XMLHttpRequest();
      method = method.toUpperCase();
      if(typeof params === "function") {
        cb = params;
      }
      var urlParams = "?";
      if(method === "POST") {
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        for(var param in params) {
          urlParams += param + "=" + params[param] + "&";
        }
      }
      xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        cb(JSON.parse(xmlHttp.responseText));
      }
      xmlHttp.open(method, url, true);
      xmlHttp.send(method === "POST" ? urlParams : null);
    }

    window.Moon = Moon;
    window.$ = function(el) {
      el = document.querySelectorAll(el);
      return el.length === 1 ? el[0] : el;
    }

})(window);
<commit_msg>set it correctly<commit_after>"use strict";
(function(window) {
    var config = {
      silent: false
    }
    var directives = {};
    var components = {};

    /**
    * Converts attributes into key-value pairs
    * @param {Node} node
    * @return {Object} Key-Value pairs of Attributes
    */
    var extractAttrs = function(node) {
      var attrs = {};
      if(!node.attributes) return attrs;
      var rawAttrs = node.attributes;
      for(var i = 0; i < rawAttrs.length; i++) {
        attrs[rawAttrs[i].name] = rawAttrs[i].value
      }

      return attrs;
    }

    /**
    * Compiles a template with given data
    * @param {String} template
    * @param {Object} data
    * @return {String} Template with data rendered
    */
    var compileTemplate = function(template, data) {
      var code = template,
          re = /{{([A-Za-z0-9_.\[\]]+)}}/gi;
      code.replace(re, function(match, p) {
        code = code.replace(match, "` + data." + p + " + `");
      });
      var compile = new Function("data", "var out = `" + code + "`; return out");
      var output = compile(data);
      return output;
    }

    /**
    * Gets Root Element
    * @param {String} html
    * @return {Node} Root Element
    */
    var getRootElement = function(html) {
      var dummy = document.createElement('div');
      dummy.innerHTML = html;
      return dummy.firstChild;
    }

    /**
    * Merges two Objects
    * @param {Object} obj
    * @param {Object} obj2
    * @return {Object} Merged Objects
    */
    function merge(obj, obj2) {
      for (var key in obj2) {
        if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
      }
      return obj;
    }

    function Moon(opts) {
        var _el = opts.el;
        var _data = opts.data;
        var _methods = opts.methods;
        var _hooks = opts.hooks || {created: function() {}, mounted: function() {}, updated: function() {}, destroyed: function() {}};
        var _destroyed = false;
        var self = this;
        this.$el = document.querySelector(_el);
        this.$components = merge(opts.components || {}, components);
        this.$dom = {type: this.$el.nodeName, children: [], node: this.$el};

        // Change state when $data is changed
        Object.defineProperty(this, '$data', {
            get: function() {
                return _data;
            },
            set: function(value) {
                _data = value;
                this.build(this.$dom.children);
            },
            configurable: true
        });

        /**
        * Logs a Message
        * @param {String} msg
        */
        this.log = function(msg) {
          if(!config.silent) console.log(msg);
        }

        /**
        * Throws an Error
        * @param {String} msg
        */
        this.error = function(msg) {
          console.log("Moon ERR: " + msg);
        }

        /**
        * Creates an object to be used in a Virtual DOM
        * @param {String} type
        * @param {Array} children
        * @param {String} val
        * @param {Object} props
        * @param {Node} node
        * @return {Object} Object usable in Virtual DOM
        */
        this.createElement = function(type, children, val, props, node) {
          return {type: type, children: children, val: val, props: props, node: node};
        }

        /**
        * Create Elements Recursively For all Children
        * @param {Array} children
        * @return {Array} Array of elements usable in Virtual DOM
        */
        this.recursiveChildren = function(children) {
          var recursiveChildrenArr = [];
          for(var i = 0; i < children.length; i++) {
            var child = children[i];
            recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
          }
          return recursiveChildrenArr;
        }

        /**
        * Creates Virtual DOM
        * @param {Node} node
        */
        this.createVirtualDOM = function(node) {
          var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
          this.$dom = vdom;
        }

        /**
        * Compiles a Component
        * @param {Node} node
        */
        this.compileComponent = function(name, component) {
          var dummy = document.createElement('div');
          dummy.innerHTML = getRootElement(this.$components[name].template).outerHTML;
          component.outerHTML = dummy.outerHTML;
        }

        /**
        * Sets Value in Data
        * @param {String} key
        * @param {String} val
        */
        this.set = function(key, val) {
          this.$data[key] = val;
          if(!_destroyed) this.build(this.$dom.children);
          if(_hooks.updated) {
            _hooks.updated();
          }
        }

        /**
        * Gets Value in Data
        * @param {String} key
        * @return {String} Value of key in data
        */
        this.get = function(key) {
          return this.$data[key];
        }

        /**
        * Calls a method
        * @param {String} method
        */
        this.method = function(method) {
          _methods[method]();
        }

        this.destroy = function() {
          Object.defineProperty(this, '$data', {
            set: function(value) {
              _data = value;
            }
          });
          _destroyed = true;
          if(_hooks.destroyed) _hooks.destroyed();
        }

        // Default Directives
        directives["m-if"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.textContent = "";
          } else {
            el.textContent = compileTemplate(vdom.val, self.$data);
          }
        }

        directives["m-show"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.style.display = 'none';
          } else {
            el.style.display = 'block';
          }
        }

        directives["m-on"] = function(el, val, vdom) {
          var splitVal = val.split(":");
          var eventToCall = splitVal[0];
          var methodToCall = splitVal[1];
          el.addEventListener(eventToCall, function() {
            self.method(methodToCall);
          });
          el.removeAttribute("m-on");
          delete vdom.props["m-on"];
        }

        directives["m-model"] = function(el, val, vdom) {
          el.value = self.get(val);
          el.addEventListener("input", function() {
            self.set(val, el.value);
          });
          el.removeAttribute("m-model");
          delete vdom.props["m-model"];
        }

        directives["m-once"] = function(el, val, vdom) {
          vdom.val = el.textContent;
          for(var child in vdom.children) {
            vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data);
          }
        }

        directives["m-text"] = function(el, val, vdom) {
          el.textContent = val;
        }

        directives["m-html"] = function(el, val, vdom) {
          el.innerHTML = val;
        }

        directives["m-mask"] = function(el, val, vdom) {

        }

        // directives["m-for"] = function(el, val, vdom) {
        //   var splitVal = val.split(" in ");
        //   var alias = splitVal[0];
        //   var arr = self.get(splitVal[1]);
        //   var clone = el.cloneNode(true);
        //   var oldVal = vdom.val;
        //   var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]');
        //   el.innerHTML = compileTemplate(compilable, self.$data);
        //   for(var i = 1; i < arr.length; i++) {
        //     var newClone = clone.cloneNode(true);
        //     var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']');
        //     newClone.innerHTML = compileTemplate(compilable, self.$data);
        //     var parent = el.parentNode;
        //     parent.appendChild(newClone);
        //   }
        //   vdom.val = el.textContent;
        //   delete vdom.props["m-for"];
        // }

        /**
        * Builds the DOM With Data
        * @param {Array} children
        */
        this.build = function(children) {
          for(var i = 0; i < children.length; i++) {
            var el = children[i];

            if(el.type === "#text") {
              el.node.textContent = compileTemplate(el.val, this.$data);
            } else if(el.props) {
              for(var prop in el.props) {
                var propVal = el.props[prop];
                var compiledProperty = compileTemplate(propVal, this.$data);
                var directive = directives[prop];
                if(directive) {
                  el.node.removeAttribute(prop);
                  directive(el.node, compiledProperty, el);
                }

                if(!directive) el.node.setAttribute(prop, compiledProperty);
              }
            }

            if(this.$components[el.type.toLowerCase()]) {
              this.compileComponent(el.type.toLowerCase(), el.node);
            }

            this.build(el.children);
          }
        }

        /**
        * Initializes Moon
        */
        this.init = function() {
          this.log("======= Moon =======");
          if(_hooks.created) {
            _hooks.created();
          }
          this.createVirtualDOM(this.$el);
          this.build(this.$dom.children);
          if(_hooks.mounted) {
            _hooks.mounted();
          }
        }

        // Initialize 🎉
        this.init();
    }

    /**
    * Sets the Configuration of Moon
    * @param {Object} opts
    */
    Moon.config = function(opts) {
      if(opts.silent) {
        config.silent = opts.silent;
      }
    }

    /**
    * Runs an external Plugin
    * @param {Object} plugin
    */
    Moon.use = function(plugin) {
      plugin.init(Moon);
    }

    /**
    * Creates a Directive
    * @param {String} name
    * @param {Function} action
    */
    Moon.directive = function(name, action) {
      directives["m-" + name] = action;
    }

    /**
    * Creates a Component
    * @param {String} name
    * @param {Function} action
    */
    Moon.component = function(name, action) {
      components[name] = action;
    }

    /**
    * Makes an AJAX Request
    * @param {String} method
    * @param {String} url
    * @param {Object} params
    * @param {Function} cb
    */
    Moon.ajax = function(method, url, params, cb) {
      var xmlHttp = new XMLHttpRequest();
      method = method.toUpperCase();
      if(typeof params === "function") {
        cb = params;
      }
      var urlParams = "?";
      if(method === "POST") {
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        for(var param in params) {
          urlParams += param + "=" + params[param] + "&";
        }
      }
      xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        cb(JSON.parse(xmlHttp.responseText));
      }
      xmlHttp.open(method, url, true);
      xmlHttp.send(method === "POST" ? urlParams : null);
    }

    window.Moon = Moon;
    window.$ = function(el) {
      el = document.querySelectorAll(el);
      return el.length === 1 ? el[0] : el;
    }

})(window);
<|endoftext|>


<commit_before>var document   = window.document
  , _tire      = window.tire
  , _$         = window.$
  , idExp      = /^#/
  , simpleExp  = /^#?([\w-]+)$/
  , classExp   = /^\./
  , tagExp     = /<([\w:]+)/
  , slice      = [].slice
  , trim       = String.prototype.trim;

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function (array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};

// If slice is not available, provide a backup, Internet Explorer 8 (and older) will need this.
try {
  slice.call(document.documentElement.childNodes, 0)[0].nodeType
} catch(e) {
  slice = function (i) {
    var elem, results = [];
    for (; (elem = this[i]); i++ ) {
      results.push( elem );
    }
    return results;
  }
}

var tire = function (selector, context) {
  return new tire.fn.find(selector, context);
}

tire.fn = tire.prototype = {

  constructor: tire,

  /**
   * Default length is zero
   */

  length: 0,

  /**
   * Extend `tire.fn`
   *
   * @param {Object} o
   */

  extend: function (o) {
    for (var k in o) {
      this[k] = o[k];
    }
  },

  /**
   * Find elements by selector
   *
   * @param {String|Object|Function} selector
   * @param {Object} context
   *
   * @return {Object}
   */

  find: function (selector, context) {
    var elms = [];

    if (!selector) {
      return this;
    }

    // if (tire.isFun(selector)) {
    //  tire.ready(selector);
    // }

    if (selector.nodeType) {
      this.selector = '';
      this.context = selector;
      return this.set([selector]);
    }

    if (selector.length === 1 && selector[0].nodeType) {
      this.selector = selector.selector;
      this.context = selector[0];
      return this.set(selector);
    }

    this.context = context = (context || document);

    if (tire.isStr(selector)) {
      this.selector = selector;
      if (simpleExp.test(selector)) {
        elms = slice.call(idExp.test(selector) ? [document.getElementById(selector.substr(1))] : document.getElementsByTagName(selector), 0);
        if (elms[0] === null) {
          elms = [];
        }
      } else if (classExp.test(selector) && document.getElementsByClassName !== undefined) {
        elms = slice.call(document.getElementsByClassName(selector.substr(1)), 0);
        if (elms[0] === null) {
          elms = [];
        }
      } else if (tagExp.test(selector)) {
        var tmp = document.createElement('div');
        tmp.innerHTML = selector;
        this.each.call(slice.call(tmp.childNodes, 0), function () {
          elms.push(this);
        });
      } else {
        if (window.Sizzle !== undefined) {
          elms = Sizzle(selector, context);
        } else {
          elms = document.querySelectorAll(selector);
        }
      }
    } else  if (selector.nodeName || selector === window) {
      elms = [selector];
    }

    return this.set(elms);
  },

  /**
   * Reduce the set of matched elements to a subset specified by a range of indices.
   *
   * @return {Object}
   */

  slice: function () {
    return this.set(slice.apply(this, arguments));
  },

  /**
   * Run callback for each element in the collection
   *
   * @param {Function} callback
   * @return {Object}
   */

  each: function(callback) {
    for (var i = 0, len = this.length; i < len; ++i) {
        if (callback.call(this[i], this[i], i, this) === false)
        break;
    }
    return this;
  },

  /**
   * Set elements to tire object before returning `this`
   *
   * @param {Array} elements
   * @return {Object}
   */

  set: function (elements) {
    var i = 0;
    for (; i < elements.length; i++) {
      this[i] = elements[i];
    }
    this.length = i;
    return this;
  }
}

/**
 * Extend `tire` with arguments, if the arguments length is one the extend target is `tire`
 */

tire.extend = function () {
  var options
    , i = 1
    , target = arguments[0] || {};

  if (typeof target !== 'object' && typeof target !== 'function') {
    target = {};
  }

  if (arguments.length === 1) {
    target = this;
    i = 0;
  }

  for (; i < arguments.length; i++) {
    if ((options = arguments[i]) !== null) {
      for (var key in options) {
        if (target[key] === options[key]) {
          continue;
        } else {
          target[key] = options[key];
        }
      }
    }
  }

  return target;
}

tire.fn.find.prototype = tire.fn;

tire.extend({

  /**
   * Trim string. Use `String.prototype.trim` for trim or use the regex to trim
   *
   * @param {String} str
   * @return {String}
   */

  trim: function (str) {
    return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  },

  /**
   * Check if the element matches the selector
   *
   * @param {Object} element
   * @param {String} selector
   * @return {Boolean}
   */

  matches: function (element, selector) {
    if (!element || element.nodeType !== 1) return;

    // Trying to use matchesSelector if it is available
    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector;
    if (matchesSelector) {
      return matchesSelector.call(element, selector);
    }

    // Trying to use Sizzle's matchesSelector if it is available
    if (window.Sizzle !== undefined) {
      return window.Sizzle.matchesSelector(element, selector);
    }

    // querySelectorAll fallback
    if (document.querySelectorAll !== undefined) {
      var nodes = element.parentNode.querySelectorAll(selector);

      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i] === element) return true;
      }

      return false;
    }
  },

  /**
   * Check if the object is a function
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isFun: function (obj) {
    return typeof obj === 'function';
  },

  /**
   * Check if the object is a array
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isArr: function (obj) {
    return obj instanceof Array;
  },

  /**
   * Check if the object is a string
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isStr: function (obj) {
    return typeof obj === 'string';
  },

  /**
   * Check if the object is a boolean
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isBool: function (obj) {
    return (obj === true) || (obj === false);
  },

  /**
   * Check if the object is a number
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isNum: function (obj) {
    return typeof obj === 'number';
  },

  /**
   * Check if the object is a object
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isObj: function (obj) {
    return obj instanceof Object;
  },

  /**
   * Parse JSON string to object.
   *
   * @param {String} str
   * @return {Object|null)
   */

  parseJSON: function (str) {
    if (!this.isStr || !str) {
      return null;
    }

    str = this.trim(str);

    if (window.JSON && window.JSON.parse) {
      return window.JSON.parse(str);
    }
  },

  /**
   * Calling .noConflict will restore the window.$` to its previous value.
   *
   * @param {Boolean} name Restore `tire` to it's previous value.
   * @return {Object}
   */

  noConflict: function (name) {
    if (name) {
      window.tire = _old;
    }

    window.$ = old$;
    return tire;
  }
});<commit_msg>fixing typo old$ to _$<commit_after>var document   = window.document
  , _tire      = window.tire
  , _$         = window.$
  , idExp      = /^#/
  , simpleExp  = /^#?([\w-]+)$/
  , classExp   = /^\./
  , tagExp     = /<([\w:]+)/
  , slice      = [].slice
  , trim       = String.prototype.trim;

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function (array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};

// If slice is not available, provide a backup, Internet Explorer 8 (and older) will need this.
try {
  slice.call(document.documentElement.childNodes, 0)[0].nodeType
} catch(e) {
  slice = function (i) {
    var elem, results = [];
    for (; (elem = this[i]); i++ ) {
      results.push( elem );
    }
    return results;
  }
}

var tire = function (selector, context) {
  return new tire.fn.find(selector, context);
}

tire.fn = tire.prototype = {

  constructor: tire,

  /**
   * Default length is zero
   */

  length: 0,

  /**
   * Extend `tire.fn`
   *
   * @param {Object} o
   */

  extend: function (o) {
    for (var k in o) {
      this[k] = o[k];
    }
  },

  /**
   * Find elements by selector
   *
   * @param {String|Object|Function} selector
   * @param {Object} context
   *
   * @return {Object}
   */

  find: function (selector, context) {
    var elms = [];

    if (!selector) {
      return this;
    }

    // if (tire.isFun(selector)) {
    //  tire.ready(selector);
    // }

    if (selector.nodeType) {
      this.selector = '';
      this.context = selector;
      return this.set([selector]);
    }

    if (selector.length === 1 && selector[0].nodeType) {
      this.selector = selector.selector;
      this.context = selector[0];
      return this.set(selector);
    }

    this.context = context = (context || document);

    if (tire.isStr(selector)) {
      this.selector = selector;
      if (simpleExp.test(selector)) {
        elms = slice.call(idExp.test(selector) ? [document.getElementById(selector.substr(1))] : document.getElementsByTagName(selector), 0);
        if (elms[0] === null) {
          elms = [];
        }
      } else if (classExp.test(selector) && document.getElementsByClassName !== undefined) {
        elms = slice.call(document.getElementsByClassName(selector.substr(1)), 0);
        if (elms[0] === null) {
          elms = [];
        }
      } else if (tagExp.test(selector)) {
        var tmp = document.createElement('div');
        tmp.innerHTML = selector;
        this.each.call(slice.call(tmp.childNodes, 0), function () {
          elms.push(this);
        });
      } else {
        if (window.Sizzle !== undefined) {
          elms = Sizzle(selector, context);
        } else {
          elms = document.querySelectorAll(selector);
        }
      }
    } else  if (selector.nodeName || selector === window) {
      elms = [selector];
    }

    return this.set(elms);
  },

  /**
   * Reduce the set of matched elements to a subset specified by a range of indices.
   *
   * @return {Object}
   */

  slice: function () {
    return this.set(slice.apply(this, arguments));
  },

  /**
   * Run callback for each element in the collection
   *
   * @param {Function} callback
   * @return {Object}
   */

  each: function(callback) {
    for (var i = 0, len = this.length; i < len; ++i) {
        if (callback.call(this[i], this[i], i, this) === false)
        break;
    }
    return this;
  },

  /**
   * Set elements to tire object before returning `this`
   *
   * @param {Array} elements
   * @return {Object}
   */

  set: function (elements) {
    var i = 0;
    for (; i < elements.length; i++) {
      this[i] = elements[i];
    }
    this.length = i;
    return this;
  }
}

/**
 * Extend `tire` with arguments, if the arguments length is one the extend target is `tire`
 */

tire.extend = function () {
  var options
    , i = 1
    , target = arguments[0] || {};

  if (typeof target !== 'object' && typeof target !== 'function') {
    target = {};
  }

  if (arguments.length === 1) {
    target = this;
    i = 0;
  }

  for (; i < arguments.length; i++) {
    if ((options = arguments[i]) !== null) {
      for (var key in options) {
        if (target[key] === options[key]) {
          continue;
        } else {
          target[key] = options[key];
        }
      }
    }
  }

  return target;
}

tire.fn.find.prototype = tire.fn;

tire.extend({

  /**
   * Trim string. Use `String.prototype.trim` for trim or use the regex to trim
   *
   * @param {String} str
   * @return {String}
   */

  trim: function (str) {
    return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  },

  /**
   * Check if the element matches the selector
   *
   * @param {Object} element
   * @param {String} selector
   * @return {Boolean}
   */

  matches: function (element, selector) {
    if (!element || element.nodeType !== 1) return;

    // Trying to use matchesSelector if it is available
    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector;
    if (matchesSelector) {
      return matchesSelector.call(element, selector);
    }

    // Trying to use Sizzle's matchesSelector if it is available
    if (window.Sizzle !== undefined) {
      return window.Sizzle.matchesSelector(element, selector);
    }

    // querySelectorAll fallback
    if (document.querySelectorAll !== undefined) {
      var nodes = element.parentNode.querySelectorAll(selector);

      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i] === element) return true;
      }

      return false;
    }
  },

  /**
   * Check if the object is a function
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isFun: function (obj) {
    return typeof obj === 'function';
  },

  /**
   * Check if the object is a array
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isArr: function (obj) {
    return obj instanceof Array;
  },

  /**
   * Check if the object is a string
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isStr: function (obj) {
    return typeof obj === 'string';
  },

  /**
   * Check if the object is a boolean
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isBool: function (obj) {
    return (obj === true) || (obj === false);
  },

  /**
   * Check if the object is a number
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isNum: function (obj) {
    return typeof obj === 'number';
  },

  /**
   * Check if the object is a object
   *
   * @param {Object} obj
   * @return {Boolean}
   */

  isObj: function (obj) {
    return obj instanceof Object;
  },

  /**
   * Parse JSON string to object.
   *
   * @param {String} str
   * @return {Object|null)
   */

  parseJSON: function (str) {
    if (!this.isStr || !str) {
      return null;
    }

    str = this.trim(str);

    if (window.JSON && window.JSON.parse) {
      return window.JSON.parse(str);
    }
  },

  /**
   * Calling .noConflict will restore the window.$` to its previous value.
   *
   * @param {Boolean} name Restore `tire` to it's previous value.
   * @return {Object}
   */

  noConflict: function (name) {
    if (name) {
      window.tire = _old;
    }

    window.$ = _$;
    return tire;
  }
});<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

var globalScope = (typeof window === 'undefined') ? this : window;

var isWorker = (typeof window == 'undefined');

var ERRORS = 0, WARNINGS = 1, TODOS = 5;
var verbosity = WARNINGS;

// The global PDFJS object exposes the API
// In production, it will be declared outside a global wrapper
// In development, it will be declared here
if (!globalScope.PDFJS) {
  globalScope.PDFJS = {};
}

// getPdf()
// Convenience function to perform binary Ajax GET
// Usage: getPdf('http://...', callback)
//        getPdf({
//                 url:String ,
//                 [,progress:Function, error:Function]
//               },
//               callback)
function getPdf(arg, callback) {
  var params = arg;
  if (typeof arg === 'string')
    params = { url: arg };

  var xhr = new XMLHttpRequest();

  xhr.open('GET', params.url);

  var headers = params.headers;
  if (headers) {
    for (var property in headers) {
      if (typeof headers[property] === 'undefined')
        continue;

      xhr.setRequestHeader(property, params.headers[property]);
    }
  }

  xhr.mozResponseType = xhr.responseType = 'arraybuffer';
  var protocol = params.url.indexOf(':') < 0 ? window.location.protocol :
    params.url.substring(0, params.url.indexOf(':') + 1);
  xhr.expected = (protocol === 'http:' || protocol === 'https:') ? 200 : 0;

  if ('progress' in params)
    xhr.onprogress = params.progress || undefined;

  if ('error' in params)
    xhr.onerror = params.error || undefined;

  xhr.onreadystatechange = function getPdfOnreadystatechange(e) {
    if (xhr.readyState === 4) {
      if (xhr.status === xhr.expected) {
        var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||
                    xhr.responseArrayBuffer || xhr.response);
        callback(data);
      } else if (params.error) {
        params.error(e);
      }
    }
  };
  xhr.send(null);
}
globalScope.PDFJS.getPdf = getPdf;
globalScope.PDFJS.pdfBug = false;

var Page = (function PageClosure() {
  function Page(xref, pageNumber, pageDict, ref) {
    this.pageNumber = pageNumber;
    this.pageDict = pageDict;
    this.xref = xref;
    this.ref = ref;

    this.displayReadyPromise = null;
  }

  Page.prototype = {
    getPageProp: function Page_getPageProp(key) {
      return this.pageDict.get(key);
    },
    inheritPageProp: function Page_inheritPageProp(key) {
      var dict = this.pageDict;
      var obj = dict.get(key);
      while (obj === undefined) {
        dict = dict.get('Parent');
        if (!dict)
          break;
        obj = dict.get(key);
      }
      return obj;
    },
    get content() {
      return shadow(this, 'content', this.getPageProp('Contents'));
    },
    get resources() {
      return shadow(this, 'resources', this.inheritPageProp('Resources'));
    },
    get mediaBox() {
      var obj = this.inheritPageProp('MediaBox');
      // Reset invalid media box to letter size.
      if (!isArray(obj) || obj.length !== 4)
        obj = [0, 0, 612, 792];
      return shadow(this, 'mediaBox', obj);
    },
    get view() {
      var mediaBox = this.mediaBox;
      var cropBox = this.inheritPageProp('CropBox');
      if (!isArray(cropBox) || cropBox.length !== 4)
        return shadow(this, 'view', mediaBox);

      // From the spec, 6th ed., p.963:
      // "The crop, bleed, trim, and art boxes should not ordinarily
      // extend beyond the boundaries of the media box. If they do, they are
      // effectively reduced to their intersection with the media box."
      cropBox = Util.intersect(cropBox, mediaBox);
      if (!cropBox)
        return shadow(this, 'view', mediaBox);

      return shadow(this, 'view', cropBox);
    },
    get annotations() {
      return shadow(this, 'annotations', this.inheritPageProp('Annots'));
    },
    get rotate() {
      var rotate = this.inheritPageProp('Rotate') || 0;
      // Normalize rotation so it's a multiple of 90 and between 0 and 270
      if (rotate % 90 != 0) {
        rotate = 0;
      } else if (rotate >= 360) {
        rotate = rotate % 360;
      } else if (rotate < 0) {
        // The spec doesn't cover negatives, assume its counterclockwise
        // rotation. The following is the other implementation of modulo.
        rotate = ((rotate % 360) + 360) % 360;
      }
      return shadow(this, 'rotate', rotate);
    },

    getOperatorList: function Page_getOperatorList(handler, dependency) {
      var xref = this.xref;
      var content = this.content;
      var resources = this.resources;
      if (isArray(content)) {
        // fetching items
        var streams = [];
        var i, n = content.length;
        for (i = 0; i < n; ++i)
          streams.push(xref.fetchIfRef(content[i]));
        content = new StreamsSequenceStream(streams);
      } else if (isStream(content)) {
        content.reset();
      } else if (!content) {
        // replacing non-existent page content with empty one
        content = new Stream(new Uint8Array(0));
      }

      var pe = this.pe = new PartialEvaluator(
                                xref, handler, 'p' + this.pageNumber + '_');

      return pe.getOperatorList(content, resources, dependency);
    },

    getLinks: function Page_getLinks() {
      var links = [];
      var annotations = pageGetAnnotations();
      var i, n = annotations.length;
      for (i = 0; i < n; ++i) {
        if (annotations[i].type != 'Link')
          continue;
        links.push(annotations[i]);
      }
      return links;
    },
    getAnnotations: function Page_getAnnotations() {
      var xref = this.xref;
      function getInheritableProperty(annotation, name) {
        var item = annotation;
        while (item && !item.has(name)) {
          item = item.get('Parent');
        }
        if (!item)
          return null;
        return item.get(name);
      }
      function isValidUrl(url) {
        if (!url)
          return false;
        var colon = url.indexOf(':');
        if (colon < 0)
          return false;
        var protocol = url.substr(0, colon);
        switch (protocol) {
          case 'http':
          case 'https':
          case 'ftp':
          case 'mailto':
            return true;
          default:
            return false;
        }
      }

      var annotations = this.annotations || [];
      var i, n = annotations.length;
      var items = [];
      for (i = 0; i < n; ++i) {
        var annotationRef = annotations[i];
        var annotation = xref.fetch(annotationRef);
        if (!isDict(annotation))
          continue;
        var subtype = annotation.get('Subtype');
        if (!isName(subtype))
          continue;
        var rect = annotation.get('Rect');

        var item = {};
        item.type = subtype.name;
        item.rect = rect;
        switch (subtype.name) {
          case 'Link':
            var a = annotation.get('A');
            if (a) {
              switch (a.get('S').name) {
                case 'URI':
                  var url = a.get('URI');
                  // TODO: pdf spec mentions urls can be relative to a Base
                  // entry in the dictionary.
                  if (!isValidUrl(url))
                    url = '';
                  item.url = url;
                  break;
                case 'GoTo':
                  item.dest = a.get('D');
                  break;
                default:
                  TODO('other link types');
              }
            } else if (annotation.has('Dest')) {
              // simple destination link
              var dest = annotation.get('Dest');
              item.dest = isName(dest) ? dest.name : dest;
            }
            break;
          case 'Widget':
            var fieldType = getInheritableProperty(annotation, 'FT');
            if (!isName(fieldType))
              break;
            item.fieldType = fieldType.name;
            // Building the full field name by collecting the field and
            // its ancestors 'T' properties and joining them using '.'.
            var fieldName = [];
            var namedItem = annotation, ref = annotationRef;
            while (namedItem) {
              var parent = namedItem.get('Parent');
              var parentRef = namedItem.getRaw('Parent');
              var name = namedItem.get('T');
              if (name) {
                fieldName.unshift(stringToPDFString(name));
              } else {
                // The field name is absent, that means more than one field
                // with the same name may exist. Replacing the empty name
                // with the '`' plus index in the parent's 'Kids' array.
                // This is not in the PDF spec but necessary to id the
                // the input controls.
                var kids = parent.get('Kids');
                var j, jj;
                for (j = 0, jj = kids.length; j < jj; j++) {
                  var kidRef = kids[j];
                  if (kidRef.num == ref.num && kidRef.gen == ref.gen)
                    break;
                }
                fieldName.unshift('`' + j);
              }
              namedItem = parent;
              ref = parentRef;
            }
            item.fullName = fieldName.join('.');
            var alternativeText = stringToPDFString(annotation.get('TU') || '');
            item.alternativeText = alternativeText;
            var da = getInheritableProperty(annotation, 'DA') || '';
            var m = /([\d\.]+)\sTf/.exec(da);
            if (m)
              item.fontSize = parseFloat(m[1]);
            item.textAlignment = getInheritableProperty(annotation, 'Q');
            item.flags = getInheritableProperty(annotation, 'Ff') || 0;
            break;
          case 'Text':
            var content = annotation.get('Contents');
            var title = annotation.get('T');
            item.content = stringToPDFString(content || '');
            item.title = stringToPDFString(title || '');
            item.name = !annotation.has('Name') ? 'Note' :
              annotation.get('Name').name;
            break;
          default:
            TODO('unimplemented annotation type: ' + subtype.name);
            break;
        }
        items.push(item);
      }
      return items;
    }
  };

  return Page;
})();

/**
 * The `PDFDocument` holds all the data of the PDF file. Compared to the
 * `PDFDoc`, this one doesn't have any job management code.
 * Right now there exists one PDFDocument on the main thread + one object
 * for each worker. If there is no worker support enabled, there are two
 * `PDFDocument` objects on the main thread created.
 */
var PDFDocument = (function PDFDocumentClosure() {
  function PDFDocument(arg, callback) {
    if (isStream(arg))
      init.call(this, arg);
    else if (isArrayBuffer(arg))
      init.call(this, new Stream(arg));
    else
      error('PDFDocument: Unknown argument type');
  }

  function init(stream) {
    assertWellFormed(stream.length > 0, 'stream must have data');
    this.stream = stream;
    this.setup();
    this.acroForm = this.catalog.catDict.get('AcroForm');
  }

  function find(stream, needle, limit, backwards) {
    var pos = stream.pos;
    var end = stream.end;
    var str = '';
    if (pos + limit > end)
      limit = end - pos;
    for (var n = 0; n < limit; ++n)
      str += stream.getChar();
    stream.pos = pos;
    var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
    if (index == -1)
      return false; /* not found */
    stream.pos += index;
    return true; /* found */
  }

  PDFDocument.prototype = {
    get linearization() {
      var length = this.stream.length;
      var linearization = false;
      if (length) {
        linearization = new Linearization(this.stream);
        if (linearization.length != length)
          linearization = false;
      }
      // shadow the prototype getter with a data property
      return shadow(this, 'linearization', linearization);
    },
    get startXRef() {
      var stream = this.stream;
      var startXRef = 0;
      var linearization = this.linearization;
      if (linearization) {
        // Find end of first obj.
        stream.reset();
        if (find(stream, 'endobj', 1024))
          startXRef = stream.pos + 6;
      } else {
        // Find startxref by jumping backward from the end of the file.
        var step = 1024;
        var found = false, pos = stream.end;
        while (!found && pos > 0) {
          pos -= step - 'startxref'.length;
          if (pos < 0)
            pos = 0;
          stream.pos = pos;
          found = find(stream, 'startxref', step, true);
        }
        if (found) {
          stream.skip(9);
          var ch;
          do {
            ch = stream.getChar();
          } while (Lexer.isSpace(ch));
          var str = '';
          while ((ch - '0') <= 9) {
            str += ch;
            ch = stream.getChar();
          }
          startXRef = parseInt(str, 10);
          if (isNaN(startXRef))
            startXRef = 0;
        }
      }
      // shadow the prototype getter with a data property
      return shadow(this, 'startXRef', startXRef);
    },
    get mainXRefEntriesOffset() {
      var mainXRefEntriesOffset = 0;
      var linearization = this.linearization;
      if (linearization)
        mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
      // shadow the prototype getter with a data property
      return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
    },
    // Find the header, remove leading garbage and setup the stream
    // starting from the header.
    checkHeader: function PDFDocument_checkHeader() {
      var stream = this.stream;
      stream.reset();
      if (find(stream, '%PDF-', 1024)) {
        // Found the header, trim off any garbage before it.
        stream.moveStart();
        return;
      }
      // May not be a PDF file, continue anyway.
    },
    setup: function PDFDocument_setup(ownerPassword, userPassword) {
      this.checkHeader();
      var xref = new XRef(this.stream,
                          this.startXRef,
                          this.mainXRefEntriesOffset);
      this.xref = xref;
      this.catalog = new Catalog(xref);
    },
    get numPages() {
      var linearization = this.linearization;
      var num = linearization ? linearization.numPages : this.catalog.numPages;
      // shadow the prototype getter
      return shadow(this, 'numPages', num);
    },
    getDocumentInfo: function PDFDocument_getDocumentInfo() {
      var info;
      if (this.xref.trailer.has('Info')) {
        var infoDict = this.xref.trailer.get('Info');

        info = {};
        infoDict.forEach(function(key, value) {
          info[key] = typeof value !== 'string' ? value :
            stringToPDFString(value);
        });
      }

      return shadow(this, 'getDocumentInfo', info);
    },
    getFingerprint: function PDFDocument_getFingerprint() {
      var xref = this.xref, fileID;
      if (xref.trailer.has('ID')) {
        fileID = '';
        var id = xref.trailer.get('ID')[0];
        id.split('').forEach(function(el) {
          fileID += Number(el.charCodeAt(0)).toString(16);
        });
      } else {
        // If we got no fileID, then we generate one,
        // from the first 100 bytes of PDF
        var data = this.stream.bytes.subarray(0, 100);
        var hash = calculateMD5(data, 0, data.length);
        fileID = '';
        for (var i = 0, length = hash.length; i < length; i++) {
          fileID += Number(hash[i]).toString(16);
        }
      }

      return shadow(this, 'getFingerprint', fileID);
    },
    getPage: function PDFDocument_getPage(n) {
      return this.catalog.getPage(n);
    }
  };

  return PDFDocument;
})();
<commit_msg>fix 4 lint errors<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

var globalScope = (typeof window === 'undefined') ? this : window;

var isWorker = (typeof window == 'undefined');

var ERRORS = 0, WARNINGS = 1, TODOS = 5;
var verbosity = WARNINGS;

// The global PDFJS object exposes the API
// In production, it will be declared outside a global wrapper
// In development, it will be declared here
if (!globalScope.PDFJS) {
  globalScope.PDFJS = {};
}

// getPdf()
// Convenience function to perform binary Ajax GET
// Usage: getPdf('http://...', callback)
//        getPdf({
//                 url:String ,
//                 [,progress:Function, error:Function]
//               },
//               callback)
function getPdf(arg, callback) {
  var params = arg;
  if (typeof arg === 'string')
    params = { url: arg };

  var xhr = new XMLHttpRequest();

  xhr.open('GET', params.url);

  var headers = params.headers;
  if (headers) {
    for (var property in headers) {
      if (typeof headers[property] === 'undefined')
        continue;

      xhr.setRequestHeader(property, params.headers[property]);
    }
  }

  xhr.mozResponseType = xhr.responseType = 'arraybuffer';
  var protocol = params.url.indexOf(':') < 0 ? window.location.protocol :
    params.url.substring(0, params.url.indexOf(':') + 1);
  xhr.expected = (protocol === 'http:' || protocol === 'https:') ? 200 : 0;

  if ('progress' in params)
    xhr.onprogress = params.progress || undefined;

  if ('error' in params)
    xhr.onerror = params.error || undefined;

  xhr.onreadystatechange = function getPdfOnreadystatechange(e) {
    if (xhr.readyState === 4) {
      if (xhr.status === xhr.expected) {
        var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse ||
                    xhr.responseArrayBuffer || xhr.response);
        callback(data);
      } else if (params.error) {
        params.error(e);
      }
    }
  };
  xhr.send(null);
}
globalScope.PDFJS.getPdf = getPdf;
globalScope.PDFJS.pdfBug = false;

var Page = (function PageClosure() {
  function Page(xref, pageNumber, pageDict, ref) {
    this.pageNumber = pageNumber;
    this.pageDict = pageDict;
    this.xref = xref;
    this.ref = ref;

    this.displayReadyPromise = null;
  }

  Page.prototype = {
    getPageProp: function Page_getPageProp(key) {
      return this.pageDict.get(key);
    },
    inheritPageProp: function Page_inheritPageProp(key) {
      var dict = this.pageDict;
      var obj = dict.get(key);
      while (obj === undefined) {
        dict = dict.get('Parent');
        if (!dict)
          break;
        obj = dict.get(key);
      }
      return obj;
    },
    get content() {
      return shadow(this, 'content', this.getPageProp('Contents'));
    },
    get resources() {
      return shadow(this, 'resources', this.inheritPageProp('Resources'));
    },
    get mediaBox() {
      var obj = this.inheritPageProp('MediaBox');
      // Reset invalid media box to letter size.
      if (!isArray(obj) || obj.length !== 4)
        obj = [0, 0, 612, 792];
      return shadow(this, 'mediaBox', obj);
    },
    get view() {
      var mediaBox = this.mediaBox;
      var cropBox = this.inheritPageProp('CropBox');
      if (!isArray(cropBox) || cropBox.length !== 4)
        return shadow(this, 'view', mediaBox);

      // From the spec, 6th ed., p.963:
      // "The crop, bleed, trim, and art boxes should not ordinarily
      // extend beyond the boundaries of the media box. If they do, they are
      // effectively reduced to their intersection with the media box."
      cropBox = Util.intersect(cropBox, mediaBox);
      if (!cropBox)
        return shadow(this, 'view', mediaBox);

      return shadow(this, 'view', cropBox);
    },
    get annotations() {
      return shadow(this, 'annotations', this.inheritPageProp('Annots'));
    },
    get rotate() {
      var rotate = this.inheritPageProp('Rotate') || 0;
      // Normalize rotation so it's a multiple of 90 and between 0 and 270
      if (rotate % 90 != 0) {
        rotate = 0;
      } else if (rotate >= 360) {
        rotate = rotate % 360;
      } else if (rotate < 0) {
        // The spec doesn't cover negatives, assume its counterclockwise
        // rotation. The following is the other implementation of modulo.
        rotate = ((rotate % 360) + 360) % 360;
      }
      return shadow(this, 'rotate', rotate);
    },

    getOperatorList: function Page_getOperatorList(handler, dependency) {
      var xref = this.xref;
      var content = this.content;
      var resources = this.resources;
      if (isArray(content)) {
        // fetching items
        var streams = [];
        var i, n = content.length;
        for (i = 0; i < n; ++i)
          streams.push(xref.fetchIfRef(content[i]));
        content = new StreamsSequenceStream(streams);
      } else if (isStream(content)) {
        content.reset();
      } else if (!content) {
        // replacing non-existent page content with empty one
        content = new Stream(new Uint8Array(0));
      }

      var pe = this.pe = new PartialEvaluator(
                                xref, handler, 'p' + this.pageNumber + '_');

      return pe.getOperatorList(content, resources, dependency);
    },

    getLinks: function Page_getLinks() {
      var links = [];
      var annotations = pageGetAnnotations();
      var i, n = annotations.length;
      for (i = 0; i < n; ++i) {
        if (annotations[i].type != 'Link')
          continue;
        links.push(annotations[i]);
      }
      return links;
    },
    getAnnotations: function Page_getAnnotations() {
      var xref = this.xref;
      function getInheritableProperty(annotation, name) {
        var item = annotation;
        while (item && !item.has(name)) {
          item = item.get('Parent');
        }
        if (!item)
          return null;
        return item.get(name);
      }
      function isValidUrl(url) {
        if (!url)
          return false;
        var colon = url.indexOf(':');
        if (colon < 0)
          return false;
        var protocol = url.substr(0, colon);
        switch (protocol) {
          case 'http':
          case 'https':
          case 'ftp':
          case 'mailto':
            return true;
          default:
            return false;
        }
      }

      var annotations = this.annotations || [];
      var i, n = annotations.length;
      var items = [];
      for (i = 0; i < n; ++i) {
        var annotationRef = annotations[i];
        var annotation = xref.fetch(annotationRef);
        if (!isDict(annotation))
          continue;
        var subtype = annotation.get('Subtype');
        if (!isName(subtype))
          continue;
        var rect = annotation.get('Rect');

        var item = {};
        item.type = subtype.name;
        item.rect = rect;
        switch (subtype.name) {
          case 'Link':
            var a = annotation.get('A');
            if (a) {
              switch (a.get('S').name) {
                case 'URI':
                  var url = a.get('URI');
                  // TODO: pdf spec mentions urls can be relative to a Base
                  // entry in the dictionary.
                  if (!isValidUrl(url))
                    url = '';
                  item.url = url;
                  break;
                case 'GoTo':
                  item.dest = a.get('D');
                  break;
                default:
                  TODO('other link types');
              }
            } else if (annotation.has('Dest')) {
              // simple destination link
              var dest = annotation.get('Dest');
              item.dest = isName(dest) ? dest.name : dest;
            }
            break;
          case 'Widget':
            var fieldType = getInheritableProperty(annotation, 'FT');
            if (!isName(fieldType))
              break;
            item.fieldType = fieldType.name;
            // Building the full field name by collecting the field and
            // its ancestors 'T' properties and joining them using '.'.
            var fieldName = [];
            var namedItem = annotation, ref = annotationRef;
            while (namedItem) {
              var parent = namedItem.get('Parent');
              var parentRef = namedItem.getRaw('Parent');
              var name = namedItem.get('T');
              if (name) {
                fieldName.unshift(stringToPDFString(name));
              } else {
                // The field name is absent, that means more than one field
                // with the same name may exist. Replacing the empty name
                // with the '`' plus index in the parent's 'Kids' array.
                // This is not in the PDF spec but necessary to id the
                // the input controls.
                var kids = parent.get('Kids');
                var j, jj;
                for (j = 0, jj = kids.length; j < jj; j++) {
                  var kidRef = kids[j];
                  if (kidRef.num == ref.num && kidRef.gen == ref.gen)
                    break;
                }
                fieldName.unshift('`' + j);
              }
              namedItem = parent;
              ref = parentRef;
            }
            item.fullName = fieldName.join('.');
            var alternativeText = stringToPDFString(annotation.get('TU') || '');
            item.alternativeText = alternativeText;
            var da = getInheritableProperty(annotation, 'DA') || '';
            var m = /([\d\.]+)\sTf/.exec(da);
            if (m)
              item.fontSize = parseFloat(m[1]);
            item.textAlignment = getInheritableProperty(annotation, 'Q');
            item.flags = getInheritableProperty(annotation, 'Ff') || 0;
            break;
          case 'Text':
            var content = annotation.get('Contents');
            var title = annotation.get('T');
            item.content = stringToPDFString(content || '');
            item.title = stringToPDFString(title || '');
            item.name = !annotation.has('Name') ? 'Note' :
              annotation.get('Name').name;
            break;
          default:
            TODO('unimplemented annotation type: ' + subtype.name);
            break;
        }
        items.push(item);
      }
      return items;
    }
  };

  return Page;
})();

/**
 * The `PDFDocument` holds all the data of the PDF file. Compared to the
 * `PDFDoc`, this one doesn't have any job management code.
 * Right now there exists one PDFDocument on the main thread + one object
 * for each worker. If there is no worker support enabled, there are two
 * `PDFDocument` objects on the main thread created.
 */
var PDFDocument = (function PDFDocumentClosure() {
  function PDFDocument(arg, callback) {
    if (isStream(arg))
      init.call(this, arg);
    else if (isArrayBuffer(arg))
      init.call(this, new Stream(arg));
    else
      error('PDFDocument: Unknown argument type');
  }

  function init(stream) {
    assertWellFormed(stream.length > 0, 'stream must have data');
    this.stream = stream;
    this.setup();
    this.acroForm = this.catalog.catDict.get('AcroForm');
  }

  function find(stream, needle, limit, backwards) {
    var pos = stream.pos;
    var end = stream.end;
    var str = '';
    if (pos + limit > end)
      limit = end - pos;
    for (var n = 0; n < limit; ++n)
      str += stream.getChar();
    stream.pos = pos;
    var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
    if (index == -1)
      return false; /* not found */
    stream.pos += index;
    return true; /* found */
  }

  PDFDocument.prototype = {
    get linearization() {
      var length = this.stream.length;
      var linearization = false;
      if (length) {
        linearization = new Linearization(this.stream);
        if (linearization.length != length)
          linearization = false;
      }
      // shadow the prototype getter with a data property
      return shadow(this, 'linearization', linearization);
    },
    get startXRef() {
      var stream = this.stream;
      var startXRef = 0;
      var linearization = this.linearization;
      if (linearization) {
        // Find end of first obj.
        stream.reset();
        if (find(stream, 'endobj', 1024))
          startXRef = stream.pos + 6;
      } else {
        // Find startxref by jumping backward from the end of the file.
        var step = 1024;
        var found = false, pos = stream.end;
        while (!found && pos > 0) {
          pos -= step - 'startxref'.length;
          if (pos < 0)
            pos = 0;
          stream.pos = pos;
          found = find(stream, 'startxref', step, true);
        }
        if (found) {
          stream.skip(9);
          var ch;
          do {
            ch = stream.getChar();
          } while (Lexer.isSpace(ch));
          var str = '';
          while ((ch - '0') <= 9) {
            str += ch;
            ch = stream.getChar();
          }
          startXRef = parseInt(str, 10);
          if (isNaN(startXRef))
            startXRef = 0;
        }
      }
      // shadow the prototype getter with a data property
      return shadow(this, 'startXRef', startXRef);
    },
    get mainXRefEntriesOffset() {
      var mainXRefEntriesOffset = 0;
      var linearization = this.linearization;
      if (linearization)
        mainXRefEntriesOffset = linearization.mainXRefEntriesOffset;
      // shadow the prototype getter with a data property
      return shadow(this, 'mainXRefEntriesOffset', mainXRefEntriesOffset);
    },
    // Find the header, remove leading garbage and setup the stream
    // starting from the header.
    checkHeader: function PDFDocument_checkHeader() {
      var stream = this.stream;
      stream.reset();
      if (find(stream, '%PDF-', 1024)) {
        // Found the header, trim off any garbage before it.
        stream.moveStart();
        return;
      }
      // May not be a PDF file, continue anyway.
    },
    setup: function PDFDocument_setup(ownerPassword, userPassword) {
      this.checkHeader();
      var xref = new XRef(this.stream,
                          this.startXRef,
                          this.mainXRefEntriesOffset);
      this.xref = xref;
      this.catalog = new Catalog(xref);
    },
    get numPages() {
      var linearization = this.linearization;
      var num = linearization ? linearization.numPages : this.catalog.numPages;
      // shadow the prototype getter
      return shadow(this, 'numPages', num);
    },
    getDocumentInfo: function PDFDocument_getDocumentInfo() {
      var info;
      if (this.xref.trailer.has('Info')) {
        var infoDict = this.xref.trailer.get('Info');

        info = {};
        infoDict.forEach(function(key, value) {
          info[key] = typeof value !== 'string' ? value :
            stringToPDFString(value);
        });
      }

      return shadow(this, 'getDocumentInfo', info);
    },
    getFingerprint: function PDFDocument_getFingerprint() {
      var xref = this.xref, fileID;
      if (xref.trailer.has('ID')) {
        fileID = '';
        var id = xref.trailer.get('ID')[0];
        id.split('').forEach(function(el) {
          fileID += Number(el.charCodeAt(0)).toString(16);
        });
      } else {
        // If we got no fileID, then we generate one,
        // from the first 100 bytes of PDF
        var data = this.stream.bytes.subarray(0, 100);
        var hash = calculateMD5(data, 0, data.length);
        fileID = '';
        for (var i = 0, length = hash.length; i < length; i++) {
          fileID += Number(hash[i]).toString(16);
        }
      }

      return shadow(this, 'getFingerprint', fileID);
    },
    getPage: function PDFDocument_getPage(n) {
      return this.catalog.getPage(n);
    }
  };

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


<commit_before>import steem from 'steem';
import { ALL_USERS } from './constants';
import Responder from './responder';

class SteemBotCore {
  constructor({username, postingKey, activeKey, config}) {
    this.username = username;
    this.postingKey = postingKey;
    this.activeKey = activeKey;
    this.config = config;
    this.init();
  }

  handlePostOperation(op) {
    if (this.config.post && typeof(this.config.post.handler) === 'function') {
      const { targets, handler } = this.config.post;
      const responder = new Responder({
        targetUsername: op.author,
        targetPermlink: op.permlink,
        responderUsername: this.username,
        postingKey: this.postingKey,
        activeKey: this.activeKey,
      });

      if (typeof(targets) === 'string' && targets === ALL_USERS) {
        handler(op, responder);
      } else if (targets.includes(op.author)) {
        handler(op, responder);
      }
    }
  }

  handleCommentOperation(op) {
    if (this.config.comment && typeof(this.config.comment.handler) === 'function') {
      const { targets, handler } = this.config.comment;
      const responder = new Responder({
        targetUsername: op.author,
        targetPermlink: op.permlink,
        responderUsername: this.username,
        postingKey: this.postingKey,
        activeKey: this.activeKey,
      });

      if (typeof(targets) === 'string' && targets === ALL_USERS) {
        handler(op, responder);
      } else if (targets.includes(op.author)) {
        handler(op, responder);
      }
    }
  }

  handleTransferOperation(op) {
    if (this.config.deposit && typeof(this.config.deposit.handler) === 'function') {
      const { targets, handler } = this.config.deposit;
      const responder = new Responder({
        targetUsername: op.from,
        targetPermlink: '',
        responderUsername: this.username,
        postingKey: this.postingKey,
        activeKey: this.activeKey,
        transferMemo: op.memo,
      });

      if (typeof(targets) === 'string' && targets === ALL_USERS) {
        handler(op, responder);
      } else if (targets.includes(op.to)) {
        handler(op, responder);
      }
    }
  }

  init() {
    steem.api.streamOperations((err, res) => {
      if (err) {
        throw(new Error('Something went wrong with streamOperations method of Steem-js'));
        console.log(err);
      }

      const opType = res[0];
      const op = res[1];

      switch(opType) {
        case 'comment':
          // Both posts and comments are known as 'comment' in this API, so we recognize them by checking the
          // value of parent_author
          if (op.parent_author === '') {
            this.handlePostOperation(op);
          } else {
            this.handleCommentOperation(op);
          }
          break;
        case 'transfer':
          this.handleTransferOperation(op);
          break;
      }
    });
  }
}

export default SteemBotCore;
<commit_msg>reset streamOperations on errors<commit_after>import steem from 'steem';
import { ALL_USERS } from './constants';
import Responder from './responder';

class SteemBotCore {
  constructor({username, postingKey, activeKey, config}) {
    this.username = username;
    this.postingKey = postingKey;
    this.activeKey = activeKey;
    this.config = config;
    this.init();
  }

  handlePostOperation(op) {
    if (this.config.post && typeof(this.config.post.handler) === 'function') {
      const { targets, handler } = this.config.post;
      const responder = new Responder({
        targetUsername: op.author,
        targetPermlink: op.permlink,
        responderUsername: this.username,
        postingKey: this.postingKey,
        activeKey: this.activeKey,
      });

      if (typeof(targets) === 'string' && targets === ALL_USERS) {
        handler(op, responder);
      } else if (targets.includes(op.author)) {
        handler(op, responder);
      }
    }
  }

  handleCommentOperation(op) {
    if (this.config.comment && typeof(this.config.comment.handler) === 'function') {
      const { targets, handler } = this.config.comment;
      const responder = new Responder({
        targetUsername: op.author,
        targetPermlink: op.permlink,
        responderUsername: this.username,
        postingKey: this.postingKey,
        activeKey: this.activeKey,
      });

      if (typeof(targets) === 'string' && targets === ALL_USERS) {
        handler(op, responder);
      } else if (targets.includes(op.author)) {
        handler(op, responder);
      }
    }
  }

  handleTransferOperation(op) {
    if (this.config.deposit && typeof(this.config.deposit.handler) === 'function') {
      const { targets, handler } = this.config.deposit;
      const responder = new Responder({
        targetUsername: op.from,
        targetPermlink: '',
        responderUsername: this.username,
        postingKey: this.postingKey,
        activeKey: this.activeKey,
        transferMemo: op.memo,
      });

      if (typeof(targets) === 'string' && targets === ALL_USERS) {
        handler(op, responder);
      } else if (targets.includes(op.to)) {
        handler(op, responder);
      }
    }
  }

  /**
   * Resetting the streamOperations automatically after 5s
   * Expected scenario is when a node is failing
   */
  resetOperations() {
    setTimeout(() => {
      this.init();
    }, 5000);
  }

  init() {
    steem.api.streamOperations((err, res) => {
      if (err) {
        console.log('Something went wrong with streamOperations method of Steem-js');
        console.log('Attempting to reset the connection...');
        this.resetOperations();
        return;
      }

      const opType = res[0];
      const op = res[1];

      switch(opType) {
        case 'comment':
          // Both posts and comments are known as 'comment' in this API, so we recognize them by checking the
          // value of parent_author
          if (op.parent_author === '') {
            this.handlePostOperation(op);
          } else {
            this.handleCommentOperation(op);
          }
          break;
        case 'transfer':
          this.handleTransferOperation(op);
          break;
      }
    });
  }
}

export default SteemBotCore;
<|endoftext|>


<commit_before>const path = require('path')
require('dotenv').config({ path: path.dirname(__dirname) + '/.env' })

const moment = require('moment')
const db = require('./core/db')
const ManholeRepository = require('./repositories/ManholeRepository')
const Manhole = require('./schemas/Manhole')
const mailgun = require('mailgun.js')
const mg = mailgun.client({
  username: 'api',
  key: process.env.MAILGUN_KEY,
})

const DAYS_INTERVAL = process.env.MAIL_ALERT_INTERVAL || 30

function sendAlert(manhole) {
  const data = {
    from: 'Neri Junior <neri@nerijunior.com>',
    to: 'neri@nerijunior.com',
    subject: 'Teste',
    text: 'Testando NODE JS',
    html: '
Teste HTML
'
  }

  return mg.messages.create(process.env.MAILGUN_DOMAIN, data)
}

function saveAllAlerts(alerts) {
  Promise.all(alerts)
      .then(ids => {

        ids.map((id) => {
          Manhole.findById(id, function(err, manhole){
            if (err) throw err

            console.log('manhole:', manhole)
          })
        })
      })
      .catch(error => {
        console.error(error)
      })
      .then(() => {
        process.exit()
      })
}

ManholeRepository.getAdopted()
  .then(manholes => {

    alerts = []

    manholes.map((manhole) => {
      // Check the last alert sent
      let now = moment()
      let fewDaysAgo = moment().subtract(DAYS_INTERVAL, 'day')

      if (manhole.last_alert) {
        let lastAlert = moment(manhole.last_alert)

        if (lastAlert >= tenDaysAgo) {
          return console.log('not send')
        }
      }

      const promise = sendAlert(manhole)
        .then(() => {
          return manhole._id
        })

      alerts.push(promise)
    })

    saveAllAlerts(alerts)
  })
<commit_msg>cron without "not send"<commit_after>const path = require('path')
require('dotenv').config({ path: path.dirname(__dirname) + '/.env' })

const moment = require('moment')
const db = require('./core/db')
const Manhole = require('./schemas/Manhole')
const mailgun = require('mailgun.js')
const mg = mailgun.client({
  username: 'api',
  key: process.env.MAILGUN_KEY,
})

const ManholeRepository = require('./repositories/ManholeRepository')

const DAYS_INTERVAL = process.env.MAIL_ALERT_INTERVAL || 30

function sendAlert(manhole) {
  const data = {
    from: 'Neri Junior <neri@nerijunior.com>',
    to: 'neri@nerijunior.com',
    subject: 'Teste',
    text: 'Testando NODE JS',
    html: '
Teste HTML
'
  }

  return mg.messages.create(process.env.MAILGUN_DOMAIN, data)
}

function saveAllAlerts(alerts) {
  Promise.all(alerts)
      .then(ids => {

        ids.map((id) => {
          Manhole.findById(id, function(err, manhole){
            if (err) throw err

            console.log('manhole:', manhole)
          })
        })
      })
      .catch(error => {
        console.error(error)
      })
      .then(() => {
        process.exit()
      })
}

ManholeRepository.getAdopted()
  .then(manholes => {

    alerts = []

    manholes.map((manhole) => {
      // Check the last alert sent
      let now = moment()
      let fewDaysAgo = moment().subtract(DAYS_INTERVAL, 'day')

      if (manhole.last_alert) {
        let lastAlert = moment(manhole.last_alert)

        if (lastAlert >= tenDaysAgo) {
          return
        }
      }

      const promise = sendAlert(manhole)
        .then(() => {
          return manhole._id
        })

      alerts.push(promise)
    })

    saveAllAlerts(alerts)
  })
<|endoftext|>


<commit_before><commit_msg>dualrtc server<commit_after>var express = require('express');
var app = express();
var fs = require('fs');
var config = require('./js/config');
var server;

if (config.ws.secured) { // HTTPS
    var https = require('https');
    var options = {
        key: fs.readFileSync('./key/key.pem', 'utf8'),
        cert: fs.readFileSync('./key/cert.pem', 'utf8')
    };
    var securePort = config.ws.securePort;

    server = https.createServer(options, app).listen(securePort, function (err) {
        console.log('[+] Set [https] protocol and server running at port #' + securePort);
    });
} else { // HTTP
    var http = require('http');
    var port = config.ws.port;
    server = http.createServer(app).listen(port, function (err) {
        console.log('[+] Set [http] protocol and server running at port #' + port);
    });
}

var io = require('socket.io').listen(server, {
    log: true,
    origins: '*:*'
});

//io.set('transports', [
//    'websockets',
//    'jsonp-polling'
//]);

var channels = {};

io.sockets.on('connection', function (socket) {

    var initChannel = '';
    if (!io.isConnected) {
        io.isConnected = true;
    }

    socket.on('new-channel', function (data) {
        if (!channels[data.channel]) {
            initChannel = data.channel;
        }

        channels[data.channel] = data.channel;
        onNewNamespace(data.channel, data.sender);
    });

    socket.on('presence', function (channel) {
        var isChannelPresent = !! channels[channel];
        socket.emit('presence', isChannelPresent);
    });

    socket.on('disconnect', function (channel) {
        if (initChannel) {
            delete channels[initChannel];
        }
    });
});

function onNewNamespace(channel, sender) {
    io.of('/' + channel).on('connection', function (socket) {
        var username;
        if (io.isConnected) {
            io.isConnected = false;
            socket.emit('connect', true);
        }

        socket.on('message', function (data) {
            if (data.sender == sender) {
                if (!username) username = data.data.sender;

                socket.broadcast.emit('message', data.data);
            }
        });

        socket.on('disconnect', function () {
            if (username) {
                socket.broadcast.emit('user-left', username);
                username = null;
            }
        });
    });
}

// Handle resource request by server
app.get('/', function(req, res) {
    res.sendFile(__dirname + '/dualrtc.html');
});

app.get('/dualrtc.html', function(req, res) {
    res.sendFile(__dirname + '/dualrtc.html');
});

app.get('/js/jquery-2.1.4.min.js', function(req, res) {
    res.sendFile(__dirname + '/js/jquery-2.1.4.min.js');
});

app.get('/dualrtc/adapter.js', function(req, res) {
    res.sendFile(__dirname + '/dualrtc/adapter.js');
});

app.get('/dualrtc/dualrtc.js', function(req, res) {
    res.sendFile(__dirname + '/dualrtc/dualrtc.js');
});

app.get('/dualrtc/screenShare.js', function(req, res) {
    res.sendFile(__dirname + '/dualrtc/screenShare.js');
});

app.get('/dualrtc/detectrtc.js', function(req, res) {
    res.sendFile(__dirname + '/dualrtc/detectrtc.js');
});

app.use(express.static('.'));
<|endoftext|>