From bc08b71ab8be7850b52c73b7246b05f85b608bbf Mon Sep 17 00:00:00 2001 From: alexlamsl Date: Sat, 19 Mar 2016 19:38:54 +0800 Subject: [PATCH] migrate source to require() merge browserify tasks into one single pass for online package generation fixes #295 --- Gruntfile.js | 52 +- assets/cleancss-browser.js | 7 - assets/master.js | 4 +- assets/ncname-browser.js | 1 - assets/relateurl-browser.js | 1 - assets/uglify-browser.js | 6 - dist/htmlminifier.js | 34170 ++++++++++++++++++++++++++++++++-- dist/htmlminifier.min.js | 14 +- index.html | 6 +- package.json | 9 +- src/htmllint.js | 281 +- src/htmlminifier.js | 1946 +- src/htmlparser.js | 839 +- src/utils.js | 16 + test.js | 4 +- tests/index.html | 10 +- tests/lint-tests.html | 12 +- tests/lint.js | 57 +- tests/minifier.js | 4129 ++-- 19 files changed, 36237 insertions(+), 5327 deletions(-) delete mode 100644 assets/cleancss-browser.js delete mode 100644 assets/ncname-browser.js delete mode 100644 assets/relateurl-browser.js delete mode 100644 assets/uglify-browser.js create mode 100644 src/utils.js diff --git a/Gruntfile.js b/Gruntfile.js index f40eb88..442dc97 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -13,6 +13,21 @@ module.exports = function(grunt) { ' * Licensed under the <%= pkg.license %> license\n' + ' */\n', + browserify: { + src: { + options: { + banner: '<%= banner %>', + require: [ + './src/htmllint.js:html-minifier/src/htmllint', + './src/htmlminifier.js:html-minifier', + './src/htmlparser.js:html-minifier/src/htmlparser' + ] + }, + src: 'src/htmlminifier.js', + dest: 'dist/htmlminifier.js' + } + }, + eslint: { grunt: { src: 'Gruntfile.js' @@ -32,30 +47,8 @@ module.exports = function(grunt) { }, exec: { - 'clean-css': { - command: 'npm run assets/clean-css' - }, - ncname: { - command: 'npm run assets/ncname' - }, - relateurl: { - command: 'npm run assets/relateurl' - }, test: { command: 'node ./test.js' - }, - 'uglify-js': { - command: 'npm run assets/uglify-js' - } - }, - - concat: { - options: { - banner: '<%= banner %>' - }, - dist: { - src: ['src/htmlparser.js', 'src/htmlminifier.js', 'src/htmllint.js'], - dest: 'dist/htmlminifier.js' } }, @@ -69,7 +62,7 @@ module.exports = function(grunt) { }, minify: { files: { - 'dist/htmlminifier.min.js': '<%= concat.dist.dest %>' + 'dist/htmlminifier.min.js': '<%= browserify.src.dest %>' } } }, @@ -116,19 +109,8 @@ module.exports = function(grunt) { }); }); - grunt.registerTask('assets', [ - 'exec:clean-css', - 'exec:ncname', - 'exec:relateurl', - 'exec:uglify-js' - ]); - - grunt.registerTask('build', [ - 'concat' - ]); - grunt.registerTask('dist', [ - 'concat', + 'browserify', 'uglify' ]); diff --git a/assets/cleancss-browser.js b/assets/cleancss-browser.js deleted file mode 100644 index 4233af8..0000000 --- a/assets/cleancss-browser.js +++ /dev/null @@ -1,7 +0,0 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.CleanCSS=e()}}(function(){var e;return function t(e,r,n){function i(a,s){if(!r[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=r[a]={exports:{}};e[a][0].call(c.exports,function(t){var r=e[a][1][t];return i(r?r:t)},c,c.exports,t,e,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a0&&(e.splice(t-1,2),t-=2)}}function a(e,t){var r;return e&&"."===e.charAt(0)&&t&&(r=t.split("/"),r=r.slice(0,r.length-1),r=r.concat(e.split("/")),o(r),e=r.join("/")),e}function s(e){return function(t){return a(t,e)}}function u(e){function t(t){d[e]=t}return t.fromText=function(e,t){throw new Error("amdefine does not implement load.fromText")},t}function l(e,r,o){var a,s,u,l;if(e)s=d[e]={},u={id:e,uri:n,exports:s},a=f(i,s,u,e);else{if(g)throw new Error("amdefine with no module ID cannot be called more than once per file.");g=!0,s=t.exports,u=t,a=f(i,s,u,t.id)}r&&(r=r.map(function(e){return a(e)})),l="function"==typeof o?o.apply(u.exports,r):o,void 0!==l&&(u.exports=l,e&&(d[e]=u.exports))}function c(e,t,r){Array.isArray(e)?(r=t,t=e,e=void 0):"string"!=typeof e&&(r=e,e=t=void 0),t&&!Array.isArray(t)&&(r=t,t=void 0),t||(t=["require","exports","module"]),e?p[e]=[e,t,r]:l(e,t,r)}var f,h,p={},d={},g=!1,m=e("path");return f=function(e,t,n,i){function o(o,a){return"string"==typeof o?h(e,t,n,o,i):(o=o.map(function(r){return h(e,t,n,r,i)}),void(a&&r.nextTick(function(){a.apply(null,o)})))}return o.toUrl=function(e){return 0===e.indexOf(".")?a(e,m.dirname(n.filename)):e},o},i=i||function(){return t.require.apply(t,arguments)},h=function(e,t,r,n,i){var o,c,g=n.indexOf("!"),m=n;if(-1===g){if(n=a(n,i),"require"===n)return f(e,t,r,i);if("exports"===n)return t;if("module"===n)return r;if(d.hasOwnProperty(n))return d[n];if(p[n])return l.apply(null,p[n]),d[n];if(e)return e(m);throw new Error("No module with ID: "+n)}return o=n.substring(0,g),n=n.substring(g+1,n.length),c=h(e,t,r,o,i),n=c.normalize?c.normalize(n,s(i)):a(n,i),d[n]?d[n]:(c.load(n,f(e,t,r,i),u(n),{}),d[n])},c.require=function(e){return d[e]?d[e]:p[e]?(l.apply(null,p[e]),d[e]):void 0},c.amd={},c}t.exports=i}).call(this,e("_process"),"/node_modules\\amdefine\\amdefine.js")},{_process:77,path:75}],2:[function(e,t,r){"use strict";function n(){var e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=t.length;for(e=0;r>e;e++)u[e]=t[e];for(e=0;r>e;++e)l[t.charCodeAt(e)]=e;l["-".charCodeAt(0)]=62,l["_".charCodeAt(0)]=63}function i(e){var t,r,n,i,o,a,s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new c(3*s/4-o),n=o>0?s-4:s;var u=0;for(t=0,r=0;n>t;t+=4,r+=3)i=l[e.charCodeAt(t)]<<18|l[e.charCodeAt(t+1)]<<12|l[e.charCodeAt(t+2)]<<6|l[e.charCodeAt(t+3)],a[u++]=(16711680&i)>>16,a[u++]=(65280&i)>>8,a[u++]=255&i;return 2===o?(i=l[e.charCodeAt(t)]<<2|l[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=l[e.charCodeAt(t)]<<10|l[e.charCodeAt(t+1)]<<4|l[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}function o(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function a(e,t,r){for(var n,i=[],a=t;r>a;a+=3)n=(e[a]<<16)+(e[a+1]<<8)+e[a+2],i.push(o(n));return i.join("")}function s(e){for(var t,r=e.length,n=r%3,i="",o=[],s=16383,l=0,c=r-n;c>l;l+=s)o.push(a(e,l,l+s>c?c:l+s));return 1===n?(t=e[r-1],i+=u[t>>2],i+=u[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=u[t>>10],i+=u[t>>4&63],i+=u[t<<2&63],i+="="),o.push(i),o.join("")}r.toByteArray=i,r.fromByteArray=s;var u=[],l=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],3:[function(e,t,r){},{}],4:[function(e,t,r){arguments[4][3][0].apply(r,arguments)},{dup:3}],5:[function(e,t,r){(function(t){"use strict";function n(){try{var e=new Uint8Array(1);return e.foo=function(){return 42},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(t){return!1}}function i(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e){return this instanceof o?(o.TYPED_ARRAY_SUPPORT||(this.length=0,this.parent=void 0),"number"==typeof e?a(this,e):"string"==typeof e?s(this,e,arguments.length>1?arguments[1]:"utf8"):u(this,e)):arguments.length>1?new o(e,arguments[1]):new o(e)}function a(e,t){if(e=g(e,0>t?0:0|m(t)),!o.TYPED_ARRAY_SUPPORT)for(var r=0;t>r;r++)e[r]=0;return e}function s(e,t,r){"string"==typeof r&&""!==r||(r="utf8");var n=0|b(t,r);return e=g(e,n),e.write(t,r),e}function u(e,t){if(o.isBuffer(t))return l(e,t);if(J(t))return c(e,t);if(null==t)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(t.buffer instanceof ArrayBuffer)return f(e,t);if(t instanceof ArrayBuffer)return h(e,t)}return t.length?p(e,t):d(e,t)}function l(e,t){var r=0|m(t.length);return e=g(e,r),t.copy(e,0,0,r),e}function c(e,t){var r=0|m(t.length);e=g(e,r);for(var n=0;r>n;n+=1)e[n]=255&t[n];return e}function f(e,t){var r=0|m(t.length);e=g(e,r);for(var n=0;r>n;n+=1)e[n]=255&t[n];return e}function h(e,t){return t.byteLength,o.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t),e.__proto__=o.prototype):e=f(e,new Uint8Array(t)),e}function p(e,t){var r=0|m(t.length);e=g(e,r);for(var n=0;r>n;n+=1)e[n]=255&t[n];return e}function d(e,t){var r,n=0;"Buffer"===t.type&&J(t.data)&&(r=t.data,n=0|m(r.length)),e=g(e,n);for(var i=0;n>i;i+=1)e[i]=255&r[i];return e}function g(e,t){o.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t),e.__proto__=o.prototype):e.length=t;var r=0!==t&&t<=o.poolSize>>>1;return r&&(e.parent=K),e}function m(e){if(e>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function v(e,t){if(!(this instanceof v))return new v(e,t);var r=new o(e,t);return delete r.parent,r}function b(e,t){"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"binary":case"raw":case"raws":return r;case"utf8":case"utf-8":return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return W(e).length;default:if(n)return F(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){var n=!1;if(t=0|t,r=void 0===r||r===1/0?this.length:0|r,e||(e="utf8"),0>t&&(t=0),r>this.length&&(r=this.length),t>=r)return"";for(;;)switch(e){case"hex":return L(this,t,r);case"utf8":case"utf-8":return E(this,t,r);case"ascii":return R(this,t,r);case"binary":return M(this,t,r);case"base64":return S(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function w(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=t.length;if(o%2!==0)throw new Error("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;n>a;a++){var s=parseInt(t.substr(2*a,2),16);if(isNaN(s))throw new Error("Invalid hex string");e[r+a]=s}return a}function _(e,t,r,n){return Y(F(t,e.length-r),e,r,n)}function x(e,t,r,n){return Y($(t),e,r,n)}function k(e,t,r,n){return x(e,t,r,n)}function O(e,t,r,n){return Y(W(t),e,r,n)}function C(e,t,r,n){return Y(H(t,e.length-r),e,r,n)}function S(e,t,r){return 0===t&&r===e.length?G.fromByteArray(e):G.fromByteArray(e.slice(t,r))}function E(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;r>i;){var o=e[i],a=null,s=o>239?4:o>223?3:o>191?2:1;if(r>=i+s){var u,l,c,f;switch(s){case 1:128>o&&(a=o);break;case 2:u=e[i+1],128===(192&u)&&(f=(31&o)<<6|63&u,f>127&&(a=f));break;case 3:u=e[i+1],l=e[i+2],128===(192&u)&&128===(192&l)&&(f=(15&o)<<12|(63&u)<<6|63&l,f>2047&&(55296>f||f>57343)&&(a=f));break;case 4:u=e[i+1],l=e[i+2],c=e[i+3],128===(192&u)&&128===(192&l)&&128===(192&c)&&(f=(15&o)<<18|(63&u)<<12|(63&l)<<6|63&c,f>65535&&1114112>f&&(a=f))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=s}return A(n)}function A(e){var t=e.length;if(Z>=t)return String.fromCharCode.apply(String,e);for(var r="",n=0;t>n;)r+=String.fromCharCode.apply(String,e.slice(n,n+=Z));return r}function R(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;r>i;i++)n+=String.fromCharCode(127&e[i]);return n}function M(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;r>i;i++)n+=String.fromCharCode(e[i]);return n}function L(e,t,r){var n=e.length;(!t||0>t)&&(t=0),(!r||0>r||r>n)&&(r=n);for(var i="",o=t;r>o;o++)i+=q(e[o]);return i}function j(e,t,r){for(var n=e.slice(t,r),i="",o=0;oe)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,r,n,i,a){if(!o.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");if(t>i||a>t)throw new RangeError("value is out of bounds");if(r+n>e.length)throw new RangeError("index out of range")}function V(e,t,r,n){0>t&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);o>i;i++)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function B(e,t,r,n){0>t&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);o>i;i++)e[r+i]=t>>>8*(n?i:3-i)&255}function U(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("index out of range");if(0>r)throw new RangeError("index out of range")}function D(e,t,r,n,i){return i||U(e,t,r,4,0xf.fffff(e+31),-0xf.fffff(e+31)),X.write(e,t,r,n,23,4),r+4}function I(e,t,r,n,i){return i||U(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),X.write(e,t,r,n,52,8),r+8}function N(e){if(e=z(e).replace(Q,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function z(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function q(e){return 16>e?"0"+e.toString(16):e.toString(16)}function F(e,t){t=t||1/0;for(var r,n=e.length,i=null,o=[],a=0;n>a;a++){if(r=e.charCodeAt(a),r>55295&&57344>r){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(56320>r){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,128>r){if((t-=1)<0)break;o.push(r)}else if(2048>r){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(65536>r){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(1114112>r))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function $(e){for(var t=[],r=0;r>8,i=r%256,o.push(i),o.push(n);return o}function W(e){return G.toByteArray(N(e))}function Y(e,t,r,n){for(var i=0;n>i&&!(i+r>=t.length||i>=e.length);i++)t[i+r]=e[i];return i}var G=e("base64-js"),X=e("ieee754"),J=e("isarray");r.Buffer=o,r.SlowBuffer=v,r.INSPECT_MAX_BYTES=50,o.poolSize=8192;var K={};o.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:n(),o._augment=function(e){return e.__proto__=o.prototype,e},o.TYPED_ARRAY_SUPPORT?(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})):(o.prototype.length=void 0,o.prototype.parent=void 0),o.isBuffer=function(e){return!(null==e||!e._isBuffer)},o.compare=function(e,t){if(!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,a=Math.min(r,n);a>i&&e[i]===t[i];)++i;return i!==a&&(r=e[i],n=t[i]),n>r?-1:r>n?1:0},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!J(e))throw new TypeError("list argument must be an Array of Buffers.");if(0===e.length)return new o(0);var r;if(void 0===t)for(t=0,r=0;r0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},o.prototype.compare=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?0:o.compare(this,e)},o.prototype.indexOf=function(e,t){function r(e,t,r){for(var n=-1,i=0;r+i2147483647?t=2147483647:-2147483648>t&&(t=-2147483648),t>>=0,0===this.length)return-1;if(t>=this.length)return-1;if(0>t&&(t=Math.max(this.length+t,0)),"string"==typeof e)return 0===e.length?-1:String.prototype.indexOf.call(this,e,t);if(o.isBuffer(e))return r(this,e,t);if("number"==typeof e)return o.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,e,t):r(this,[e],t);throw new TypeError("val must be string, number or Buffer")},o.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else if(isFinite(t))t=0|t,isFinite(r)?(r=0|r,void 0===n&&(n="utf8")):(n=r,r=void 0);else{var i=n;n=t,t=0|r,r=i}var o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(0>r||0>t)||t>this.length)throw new RangeError("attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return _(this,e,t,r);case"ascii":return x(this,e,t,r);case"binary":return k(this,e,t,r);case"base64":return O(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Z=4096;o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),e>t&&(t=e);var n;if(o.TYPED_ARRAY_SUPPORT)n=this.subarray(e,t),n.__proto__=o.prototype;else{var i=t-e;n=new o(i,void 0);for(var a=0;i>a;a++)n[a]=this[a+e]}return n.length&&(n.parent=this.parent||this),n},o.prototype.readUIntLE=function(e,t,r){e=0|e,t=0|t,r||T(e,t,this.length);for(var n=this[e],i=1,o=0;++o0&&(i*=256);)n+=this[e+--t]*i;return n},o.prototype.readUInt8=function(e,t){return t||T(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return t||T(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return t||T(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return t||T(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e=0|e,t=0|t,r||T(e,t,this.length);for(var n=this[e],i=1,o=0;++o=i&&(n-=Math.pow(2,8*t)),n},o.prototype.readIntBE=function(e,t,r){e=0|e,t=0|t,r||T(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},o.prototype.readInt8=function(e,t){return t||T(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){t||T(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(e,t){t||T(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(e,t){return t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return t||T(e,4,this.length),X.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return t||T(e,4,this.length),X.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return t||T(e,8,this.length),X.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return t||T(e,8,this.length),X.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,n){e=+e,t=0|t,r=0|r,n||P(this,e,t,r,Math.pow(2,8*r),0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,1,255,0),o.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):V(this,e,t,!0),t+2},o.prototype.writeUInt16BE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):V(this,e,t,!1),t+2},o.prototype.writeUInt32LE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):B(this,e,t,!0),t+4},o.prototype.writeUInt32BE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},o.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t=0|t,!n){var i=Math.pow(2,8*r-1);P(this,e,t,r,i-1,-i)}var o=0,a=1,s=0>e?1:0;for(this[t]=255&e;++o>0)-s&255;return t+r},o.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t=0|t,!n){var i=Math.pow(2,8*r-1);P(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0>e?1:0;for(this[t+o]=255&e;--o>=0&&(a*=256);)this[t+o]=(e/a>>0)-s&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,1,127,-128),o.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),0>e&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):V(this,e,t,!0),t+2},o.prototype.writeInt16BE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):V(this,e,t,!1),t+2},o.prototype.writeInt32LE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):B(this,e,t,!0),t+4},o.prototype.writeInt32BE=function(e,t,r){return e=+e,t=0|t,r||P(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),o.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},o.prototype.writeFloatLE=function(e,t,r){return D(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return D(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return I(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return I(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-tr&&n>t)for(i=a-1;i>=0;i--)e[i+t]=this[i+r];else if(1e3>a||!o.TYPED_ARRAY_SUPPORT)for(i=0;a>i;i++)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+a),t);return a},o.prototype.fill=function(e,t,r){if(e||(e=0),t||(t=0),r||(r=this.length),t>r)throw new RangeError("end < start");if(r!==t&&0!==this.length){if(0>t||t>=this.length)throw new RangeError("start out of bounds");if(0>r||r>this.length)throw new RangeError("end out of bounds");var n;if("number"==typeof e)for(n=t;r>n;n++)this[n]=e;else{var i=F(e.toString()),o=i.length;for(n=t;r>n;n++)this[n]=i[n%o]}return this}};var Q=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":2,ieee754:70,isarray:73}],6:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],7:[function(e,t,r){(function(r){function n(e){return void 0===e?["all"]:e}function i(e){return!A.existsSync(e)&&!/\.css$/.test(e)}function o(e){return A.existsSync(e)&&A.statSync(e).isDirectory()}function a(e){return e?{hostname:M.parse(e).hostname,port:parseInt(M.parse(e).port)}:{}}function s(e,t){function r(r){return r=t.options.debug?l(t,r):f(t,r),r=u(t,r),e?e.call(null,t.errors.length>0?t.errors:null,r):r}return function(e){return t.options.sourceMap?t.inputSourceMapTracker.track(e,function(){return t.options.sourceMapInlineSources?t.inputSourceMapTracker.resolveSources(function(){return r(e)}):r(e)}):r(e)}}function u(e,t){return t.stats=e.stats,t.errors=e.errors,t.warnings=e.warnings,t}function l(e,t){var n=r.hrtime();e.stats.originalSize=e.sourceTracker.removeAll(t).length,t=f(e,t);var i=r.hrtime(n);return e.stats.timeSpent=~~(1e3*i[0]+i[1]/1e6),e.stats.efficiency=1-t.styles.length/e.stats.originalSize,e.stats.minifiedSize=t.styles.length,t}function c(e){return function(t,n){var i=t.constructor.name+"#"+n,o=r.hrtime();e(t,n);var a=r.hrtime(o);console.log("%d ms: "+i,1e3*a[0]+a[1]/1e6)}}function f(e,t){function r(t,r){return t=a.restore(t,r),t=s.restore(t),t=n.rebase?p(t,e):t,t=o.restore(t),i.restore(t)}var n=e.options,i=new y(e,n.keepSpecialComments,n.keepBreaks,n.sourceMap),o=new w(n.sourceMap),a=new _(n.sourceMap),s=new x(e,n.sourceMap,n.compatibility.properties.urlQuotes),u=n.sourceMap?b:v,l=function(e,r){t="function"==typeof e?e(t):e[r](t)};n.benchmark&&(l=c(l)),l(i,"escape"),l(o,"escape"),l(s,"escape"),l(a,"escape");var f=d(t,e);return g(f,n),n.advanced&&m(f,n,e.validator,!0),u(f,n,r,e.inputSourceMapTracker)}var h=e("./imports/inliner"),p=e("./urls/rebase"),d=e("./tokenizer/tokenize"),g=e("./selectors/simple"),m=e("./selectors/advanced"),v=e("./stringifier/simple"),b=e("./stringifier/source-maps"),y=e("./text/comments-processor"),w=e("./text/expressions-processor"),_=e("./text/free-text-processor"),x=e("./text/urls-processor"),k=e("./utils/compatibility"),O=e("./utils/input-source-map-tracker"),C=e("./utils/source-tracker"),S=e("./utils/source-reader"),E=e("./properties/validator"),A=e("fs"),R=e("path"),M=e("url"),L=e("./utils/object").override,j=5e3,T=t.exports=function(e){e=e||{},this.options={advanced:void 0===e.advanced?!0:!!e.advanced,aggressiveMerging:void 0===e.aggressiveMerging?!0:!!e.aggressiveMerging,benchmark:e.benchmark,compatibility:new k(e.compatibility).toOptions(),debug:e.debug,explicitRoot:!!e.root,explicitTarget:!!e.target,inliner:e.inliner||{},keepBreaks:e.keepBreaks||!1,keepSpecialComments:"keepSpecialComments"in e?e.keepSpecialComments:"*",mediaMerging:void 0===e.mediaMerging?!0:!!e.mediaMerging,processImport:void 0===e.processImport?!0:!!e.processImport,processImportFrom:n(e.processImportFrom),rebase:void 0===e.rebase?!0:!!e.rebase,relativeTo:e.relativeTo,restructuring:void 0===e.restructuring?!0:!!e.restructuring,root:e.root||r.cwd(),roundingPrecision:e.roundingPrecision,semanticMerging:void 0===e.semanticMerging?!1:!!e.semanticMerging,shorthandCompacting:void 0===e.shorthandCompacting?!0:!!e.shorthandCompacting,sourceMap:e.sourceMap,sourceMapInlineSources:!!e.sourceMapInlineSources,target:!e.target||i(e.target)||o(e.target)?e.target:R.dirname(e.target)},this.options.inliner.timeout=this.options.inliner.timeout||j,this.options.inliner.request=L(a(r.env.HTTP_PROXY||r.env.http_proxy),this.options.inliner.request||{})};T.prototype.minify=function(e,t){var n={stats:{},errors:[],warnings:[],options:this.options,debug:this.options.debug,localOnly:!t,sourceTracker:new C,validator:new E(this.options.compatibility)};if(n.options.sourceMap&&(n.inputSourceMapTracker=new O(n)),n.sourceReader=new S(n,e),e=n.sourceReader.toString(),n.options.processImport||e.indexOf("@shallow")>0){var i=t?r.nextTick:function(e){return e()};return i(function(){return new h(n).process(e,{localOnly:n.localOnly,imports:n.options.processImportFrom,whenDone:s(t,n)})})}return s(t,n)(e)}}).call(this,e("_process"))},{"./imports/inliner":11,"./properties/validator":25,"./selectors/advanced":28,"./selectors/simple":41,"./stringifier/simple":45,"./stringifier/source-maps":46,"./text/comments-processor":47,"./text/expressions-processor":49,"./text/free-text-processor":50,"./text/urls-processor":51,"./tokenizer/tokenize":54,"./urls/rebase":55,"./utils/compatibility":59,"./utils/input-source-map-tracker":60,"./utils/object":61,"./utils/source-reader":63,"./utils/source-tracker":64,_process:77,fs:4,path:75,url:110}],8:[function(e,t,r){function n(e,t,r,n){return t+s[r.toLowerCase()]+n}function i(e,t,r){return u[t.toLowerCase()]+r}var o={},a={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#0ff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000",blanchedalmond:"#ffebcd",blue:"#00f",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#0ff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#f0f",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#0f0",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#f00",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#fff",whitesmoke:"#f5f5f5",yellow:"#ff0",yellowgreen:"#9acd32"},s={},u={};for(var l in a){var c=a[l];l.length-1,r=e.replace(f,n);return r!=e&&(r=r.replace(f,n)),t?r.replace(h,i):r},t.exports=o},{}],9:[function(e,t,r){function n(e,t,r){this.hue=e,this.saturation=t,this.lightness=r}function i(e,t,r){var n,i,a;if(e%=360,0>e&&(e+=360),e=~~e/360,0>t?t=0:t>100&&(t=100),t=~~t/100,0>r?r=0:r>100&&(r=100),r=~~r/100,0===t)n=i=a=r;else{var s=.5>r?r*(1+t):r+t-r*t,u=2*r-s;n=o(u,s,e+1/3),i=o(u,s,e),a=o(u,s,e-1/3)}return[~~(255*n),~~(255*i),~~(255*a)]}function o(e,t,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?e+6*(t-e)*r:.5>r?t:2/3>r?e+(t-e)*(2/3-r)*6:e}n.prototype.toHex=function(){var e=i(this.hue,this.saturation,this.lightness),t=e[0].toString(16),r=e[1].toString(16),n=e[2].toString(16);return"#"+((1==t.length?"0":"")+t)+((1==r.length?"0":"")+r)+((1==n.length?"0":"")+n)},t.exports=n},{}],10:[function(e,t,r){function n(e,t,r){this.red=e,this.green=t,this.blue=r}n.prototype.toHex=function(){var e=Math.max(0,Math.min(~~this.red,255)),t=Math.max(0,Math.min(~~this.green,255)),r=Math.max(0,Math.min(~~this.blue,255));return"#"+("00000"+(e<<16|t<<8|r).toString(16)).slice(-6)},t.exports=n},{}],11:[function(e,t,r){(function(r){function n(e){this.outerContext=e}function i(e,t){if(t.shallow)return t.shallow=!1,t.done.push(e),s(t);for(var r=0,n=0,i=0,o=u(e);n-1&&-1==n?r:-1==r&&n>-1?n:Math.min(r,n); -}function s(e){return e.left.length>0?i.apply(null,e.left.shift()):e.whenDone(e.done.join(""))}function u(e){var t=/(\/\*(?!\*\/)[\s\S]*?\*\/)/,r=0,n=0,i=!1;return function(o){var a,s=0,u=0,l=0,c=0;if(i)return!1;do{if(o>r&&n>o)return!0;if(a=e.match(t),!a)return i=!0,!1;r=s=a.index,u=s+a[0].length,c=u+n,l=c-a[0].length,e=e.substring(u),n=c}while(o>c);return c>o&&o>l}}function l(e){for(var t=u(e),r=-1;;)if(r=e.indexOf("{",r+1),-1==r||!t(r))break;return r>-1}function c(e,t,r,n){n.shallow=e.indexOf("@shallow")>0;var i=e.substring(a(e,t)+"@import".length+1,r).replace(/@shallow\)$/,")").trim(),o=0===i.indexOf("url("),u=o?4:0,c=/^['"]/.exec(i.substring(u,u+2)),g=c?i.indexOf(c[0],u+1):_(i," ")[0].length-(o?1:0),m=i.substring(u,g).replace(/['"]/g,"").replace(/\)$/,"").trim(),v=i.substring(g+1).replace(/^\)/,"").trim(),b=n.isRemote||O.test(m);if(b&&(n.localOnly||!f(m,!0,n.imports)))return n.afterContent||l(n.done.join(""))?n.warnings.push('Ignoring remote @import of "'+m+'" as no callback given.'):d(m,v,n),s(n);if(!b&&!f(m,!1,n.imports))return n.afterImport?n.warnings.push('Ignoring local @import of "'+m+'" as after other inlined content.'):d(m,v,n),s(n);if(!b&&n.afterContent)return n.warnings.push('Ignoring local @import of "'+m+'" as after other CSS content.'),s(n);var y=b?h:p;return y(m,v,n)}function f(e,t,r){if(0===r.length)return!1;t&&C.test(e)&&(e="http:"+e);for(var n=t?y.parse(e).host:e,i=!0,o=0;o-1)return s(n);n.debug&&console.error("Inlining remote stylesheet: "+u),n.visited.push(u);var c=0===u.indexOf("http://")?v.get:b.get,f=!1,p=x(y.parse(u),n.inliner.request);void 0!==n.inliner.request.hostname&&(p.path=p.href),c(p,function(e){if(e.statusCode<200||e.statusCode>399)return a("error "+e.statusCode);if(e.statusCode>299){var s=y.resolve(u,e.headers.location);return h(s,t,n)}var c=[],f=y.parse(u);e.on("data",function(e){c.push(e.toString())}),e.on("end",function(){var e=c.join("");n.rebase&&(e=w(e,{toBase:l},n)),n.sourceReader.trackSource(u,e),e=n.sourceTracker.store(u,e),e=o(e,u),t.length>0&&(e="@media "+t+"{"+e+"}"),n.afterImport=!0;var a=x(n,{isRemote:!0,relativeTo:f.protocol+"//"+f.host+f.pathname});r.nextTick(function(){i(e,a)})})}).on("error",function(e){a(e.message)}).on("timeout",function(){a("timeout")}).setTimeout(n.inliner.timeout)}function p(e,t,r){var n="/"==e[0]?r.root:r.relativeTo,o=m.resolve(m.join(n,e));if(!g.existsSync(o)||!g.statSync(o).isFile())return r.errors.push('Broken @import declaration of "'+e+'"'),s(r);if(r.visited.indexOf(o)>-1)return s(r);r.debug&&console.error("Inlining local stylesheet: "+o),r.visited.push(o);var a=m.dirname(o),u=g.readFileSync(o,"utf8");if(r.rebase){var l={relative:!0,fromBase:a,toBase:r.baseRelativeTo};u=w(u,l,r)}var c=m.relative(r.root,o);r.sourceReader.trackSource(c,u),u=r.sourceTracker.store(c,u),t.length>0&&(u="@media "+t+"{"+u+"}"),r.afterImport=!0;var f=x(r,{relativeTo:a});return i(u,f)}function d(e,t,r){var n="@import url("+e+")"+(t.length>0?" "+t:"")+";";r.done.push(n)}var g=e("fs"),m=e("path"),v=e("http"),b=e("https"),y=e("url"),w=e("../urls/rewrite"),_=e("../utils/split"),x=e("../utils/object.js").override,k=/\/\*# sourceMappingURL=(\S+) \*\//,O=/^(https?:)?\/\//,C=/^\/\//;n.prototype.process=function(e,t){var r=this.outerContext.options.root;return t=x(t,{baseRelativeTo:this.outerContext.options.relativeTo||r,debug:this.outerContext.options.debug,done:[],errors:this.outerContext.errors,left:[],inliner:this.outerContext.options.inliner,rebase:this.outerContext.options.rebase,relativeTo:this.outerContext.options.relativeTo||r,root:r,sourceReader:this.outerContext.sourceReader,sourceTracker:this.outerContext.sourceTracker,warnings:this.outerContext.warnings,visited:[]}),i(e,t)},t.exports=n}).call(this,e("_process"))},{"../urls/rewrite":57,"../utils/object.js":61,"../utils/split":65,_process:77,fs:4,http:104,https:69,path:75,url:110}],12:[function(e,t,r){function n(e){return function(t){return"invert"==t[0]||e.isValidColor(t[0])}}function i(e){return function(t){return"inherit"!=t[0]&&e.isValidStyle(t[0])&&!e.isValidColorValue(t[0])}}function o(e,t,r){var n=r[e];return p(n.doubleValues&&2==n.defaultValue.length?[[e,t.important],[n.defaultValue[0]],[n.defaultValue[1]]]:n.doubleValues&&1==n.defaultValue.length?[[e,t.important],[n.defaultValue[0]]]:[[e,t.important],[n.defaultValue]])}function a(e){return function(t){return"inherit"!=t[0]&&e.isValidWidth(t[0])&&!e.isValidStyleKeyword(t[0])&&!e.isValidColorValue(t[0])}}function s(e,t,r){var n=o("background-image",e,t),i=o("background-position",e,t),a=o("background-size",e,t),s=o("background-repeat",e,t),u=o("background-attachment",e,t),l=o("background-origin",e,t),c=o("background-clip",e,t),f=o("background-color",e,t),h=[n,i,a,s,u,l,c,f],p=e.value,g=!1,m=!1,v=!1,b=!1;if(1==e.value.length&&"inherit"==e.value[0][0])return f.value=n.value=s.value=i.value=a.value=l.value=c.value=e.value,h;for(var y=p.length-1;y>=0;y--){var w=p[y];if(r.isValidBackgroundAttachment(w[0]))u.value=[w];else if(r.isValidBackgroundBox(w[0]))m?(l.value=[w],v=!0):(c.value=[w],m=!0);else if(r.isValidBackgroundRepeat(w[0]))b?s.value.unshift(w):(s.value=[w],b=!0);else if(r.isValidBackgroundPositionPart(w[0])||r.isValidBackgroundSizePart(w[0]))if(y>0){var _=p[y-1];if(_[0].indexOf("/")>0){var x=d(_[0],"/");a.value=[[x.pop()].concat(_.slice(1)),w],p[y-1]=[x.pop()].concat(_.slice(1))}else y>1&&"/"==p[y-2]?(a.value=[_,w],y-=2):"/"==_[0]?a.value=[w]:(g||(i.value=[]),i.value.unshift(w),g=!0)}else g||(i.value=[]),i.value.unshift(w),g=!0;else if(r.isValidBackgroundPositionAndSize(w[0])){var k=d(w[0],"/");a.value=[[k.pop()].concat(w.slice(1))],i.value=[[k.pop()].concat(w.slice(1))]}else f.value[0][0]!=t[f.name].defaultValue&&"none"!=f.value[0][0]||!r.isValidColor(w[0])?(r.isValidUrl(w[0])||r.isValidFunction(w[0]))&&(n.value=[w]):f.value=[w]}return m&&!v&&(l.value=c.value.slice(0)),h}function u(e,t){for(var r=e.value,n=-1,i=0,a=r.length;a>i;i++)if("/"==r[i][0]){n=i;break}if(-1==n)return l(e,t);var s=o(e.name,e,t);s.value=r.slice(0,n),s.components=l(s,t);var u=o(e.name,e,t);u.value=r.slice(n+1),u.components=l(u,t);for(var c=0;4>c;c++)s.components[c].multiplex=!0,s.components[c].value=s.components[c].value.concat([["/"]]).concat(u.components[c].value);return s.components}function l(e,t){var r=t[e.name].components,n=[],i=e.value;if(i.length<1)return[];i.length<2&&(i[1]=i[0].slice(0)),i.length<3&&(i[2]=i[0].slice(0)),i.length<4&&(i[3]=i[1].slice(0));for(var o=r.length-1;o>=0;o--){var a=p([[r[o],e.important]]);a.value=[i[o]],n.unshift(a)}return n}function c(e){return function(t,r,n){var i,a,s,u,l=[],c=t.value;for(i=0,s=c.length;s>i;i++)","==c[i][0]&&l.push(i);if(0===l.length)return e(t,r,n);var f=[];for(i=0,s=l.length;s>=i;i++){var h=0===i?0:l[i-1]+1,p=s>i?l[i]:c.length,d=o(t.name,t,r);d.value=c.slice(h,p),f.push(e(d,r,n))}var m=f[0];for(i=0,s=m.length;s>i;i++)for(m[i].multiplex=!0,a=1,u=f.length;u>a;a++)m[i].value.push([g]),Array.prototype.push.apply(m[i].value,f[a][i].value);return m}}function f(e,t,r){var n=o("list-style-type",e,t),i=o("list-style-position",e,t),a=o("list-style-image",e,t),s=[n,i,a];if(1==e.value.length&&"inherit"==e.value[0][0])return n.value=i.value=a.value=[e.value[0]],s;var u=e.value.slice(0),l=u.length,c=0;for(c=0,l=u.length;l>c;c++)if(r.isValidUrl(u[c][0])||"0"==u[c][0]){a.value=[u[c]],u.splice(c,1);break}for(c=0,l=u.length;l>c;c++)if(r.isValidListStyleType(u[c][0])){n.value=[u[c]],u.splice(c,1);break}return u.length>0&&r.isValidListStylePosition(u[0][0])&&(i.value=[u[0]]),s}function h(e,t,r){for(var s,u,l,c=t[e.name],f=[o(c.components[0],e,t),o(c.components[1],e,t),o(c.components[2],e,t)],h=0;3>h;h++){var p=f[h];p.name.indexOf("color")>0?s=p:p.name.indexOf("style")>0?u=p:l=p}if(1==e.value.length&&"inherit"==e.value[0][0]||3==e.value.length&&"inherit"==e.value[0][0]&&"inherit"==e.value[1][0]&&"inherit"==e.value[2][0])return s.value=u.value=l.value=[e.value[0]],f;var d,g,m=e.value.slice(0);return m.length>0&&(g=m.filter(a(r)),d=g.length>1&&("none"==g[0][0]||"auto"==g[0][0])?g[1]:g[0],d&&(l.value=[d],m.splice(m.indexOf(d),1))),m.length>0&&(d=m.filter(i(r))[0],d&&(u.value=[d],m.splice(m.indexOf(d),1))),m.length>0&&(d=m.filter(n(r))[0],d&&(s.value=[d],m.splice(m.indexOf(d),1))),f}var p=e("./wrap-for-optimizing").single,d=e("../utils/split"),g=",";t.exports={background:s,border:h,borderRadius:u,fourValues:l,listStyle:f,multiplex:c,outline:h}},{"../utils/split":65,"./wrap-for-optimizing":27}],13:[function(e,t,r){function n(){return!0}function i(e,t,r){var n=e.value[0][0],i=t.value[0][0];return"none"==i||"inherit"==i||r.isValidUrl(i)?!0:"none"==n||"inherit"==n||r.isValidUrl(n)?!1:l(e,t,r)}function o(e,t,r){return a(e.components[2],t.components[2],r)}function a(e,t,r){var n=e.value[0][0],i=t.value[0][0];return(r.colorOpacity||!r.isValidRgbaColor(n)&&!r.isValidHslaColor(n))&&(r.colorOpacity||!r.isValidRgbaColor(i)&&!r.isValidHslaColor(i))?r.isValidNamedColor(i)||r.isValidHexColor(i)?!0:r.isValidNamedColor(n)||r.isValidHexColor(n)?!1:r.isValidRgbaColor(i)||r.isValidHslaColor(i)?!0:r.isValidRgbaColor(n)||r.isValidHslaColor(n)?!1:l(e,t,r):!1}function s(e,t,r){var n=e.value[0][0],i=t.value[0][0];return!(r.isValidFunction(n)^r.isValidFunction(i))}function u(e,t){var r=e.value[0][0],n=t.value[0][0];return r===n}function l(e,t,r){var n=e.value[0][0],i=t.value[0][0];return r.areSameFunction(n,i)?!0:n===i}function c(e,t,r){var n=e.value[0][0],i=t.value[0][0];return r.isValidAndCompatibleUnitWithoutFunction(n)&&!r.isValidAndCompatibleUnitWithoutFunction(i)?!1:r.isValidUnitWithoutFunction(i)?!0:r.isValidUnitWithoutFunction(n)?!1:r.isValidFunctionWithoutVendorPrefix(i)&&r.isValidFunctionWithoutVendorPrefix(n)?!0:l(e,t,r)}t.exports={always:n,backgroundImage:i,border:o,color:a,sameValue:u,sameFunctionOrValue:l,twoOptionalFunctions:s,unit:c}},{}],14:[function(e,t,r){function n(e){for(var t=i(e),r=e.components.length-1;r>=0;r--){var n=i(e.components[r]);n.value=e.components[r].value.slice(0),t.components.unshift(n)}return t.dirty=!0,t.value=e.value.slice(0),t}function i(e){var t=o([[e.name,e.important,e.hack]]);return t.unused=!1,t}var o=e("./wrap-for-optimizing").single;t.exports={deep:n,shallow:i}},{"./wrap-for-optimizing":27}],15:[function(e,t,r){var n=e("./break-up"),i=e("./can-override"),o=e("./restore"),a={color:{canOverride:i.color,defaultValue:"transparent",shortestValue:"red"},background:{components:["background-image","background-position","background-size","background-repeat","background-attachment","background-origin","background-clip","background-color"],breakUp:n.multiplex(n.background),defaultValue:"0 0",restore:o.multiplex(o.background),shortestValue:"0",shorthand:!0},"background-clip":{canOverride:i.always,defaultValue:"border-box",shortestValue:"border-box"},"background-color":{canOverride:i.color,defaultValue:"transparent",multiplexLastOnly:!0,nonMergeableValue:"none",shortestValue:"red"},"background-image":{canOverride:i.backgroundImage,defaultValue:"none"},"background-origin":{canOverride:i.always,defaultValue:"padding-box",shortestValue:"border-box"},"background-repeat":{canOverride:i.always,defaultValue:["repeat"],doubleValues:!0},"background-position":{canOverride:i.always,defaultValue:["0","0"],doubleValues:!0,shortestValue:"0"},"background-size":{canOverride:i.always,defaultValue:["auto"],doubleValues:!0,shortestValue:"0 0"},"background-attachment":{canOverride:i.always,defaultValue:"scroll"},border:{breakUp:n.border,canOverride:i.border,components:["border-width","border-style","border-color"],defaultValue:"none",restore:o.withoutDefaults,shorthand:!0},"border-color":{canOverride:i.color,defaultValue:"none",shorthand:!0},"border-style":{canOverride:i.always,defaultValue:"none",shorthand:!0},"border-width":{canOverride:i.unit,defaultValue:"medium",shortestValue:"0",shorthand:!0},"list-style":{components:["list-style-type","list-style-position","list-style-image"],canOverride:i.always,breakUp:n.listStyle,restore:o.withoutDefaults,defaultValue:"outside",shortestValue:"none",shorthand:!0},"list-style-type":{canOverride:i.always,defaultValue:"__hack",shortestValue:"none"},"list-style-position":{canOverride:i.always,defaultValue:"outside",shortestValue:"inside"},"list-style-image":{canOverride:i.always,defaultValue:"none"},outline:{components:["outline-color","outline-style","outline-width"],breakUp:n.outline,restore:o.withoutDefaults,defaultValue:"0",shorthand:!0},"outline-color":{canOverride:i.color,defaultValue:"invert",shortestValue:"red"},"outline-style":{canOverride:i.always,defaultValue:"none"},"outline-width":{canOverride:i.unit,defaultValue:"medium",shortestValue:"0"},"-moz-transform":{canOverride:i.sameFunctionOrValue},"-ms-transform":{canOverride:i.sameFunctionOrValue},"-webkit-transform":{canOverride:i.sameFunctionOrValue},transform:{canOverride:i.sameFunctionOrValue}},s=function(e,t,r){r=r||{},a[e]={canOverride:r.canOverride,components:t,breakUp:r.breakUp||n.fourValues,defaultValue:r.defaultValue||"0",restore:r.restore||o.fourValues,shortestValue:r.shortestValue,shorthand:!0};for(var s=0;sl;l++)a[a[u].components[l]].componentOf=u;t.exports=a},{"./break-up":12,"./can-override":13,"./restore":23}],16:[function(e,t,r){function n(e,t,r,n){for(var a=i(t),s=i(r),u=0,l=t.value.length;l>u;u++)for(var c=0,f=r.value.length;f>c;c++)if(t.value[u][0]!=o&&r.value[c][0]!=o&&(a.value=[t.value[u]],s.value=[r.value[c]],!e(a,s,n)))return!1;return!0}var i=e("./clone").shallow,o=",";t.exports=n},{"./clone":14}],17:[function(e,t,r){function n(e){for(var t=e.value.length-1;t>=0;t--)if("inherit"==e.value[t][0])return!0;return!1}t.exports=n},{}],18:[function(e,t,r){function n(e,t,r,n){function i(e){return t===!1||t===!0?t:t.indexOf(e)>-1}function a(t){var r=e[t-1],n=e[t];return h(r.all,r.position)==h(n.all,n.position)}var s,u,l={},c=null;e:for(var f=0,d=e.length;d>f;f++){var g=e[f],m=!("-ms-filter"!=g.name&&"filter"!=g.name||"background"!=c&&"background-image"!=c)?c:g.name,v=g.important,b=g.hack;if(!g.unused)if(f>0&&s&&m==c&&v==s.important&&b==s.hack&&a(f)&&!s.unused)g.unused=!0;else{if(m in l&&(r&&m!=c||i(f))){var y=l[m],w=o[m]&&o[m].canOverride,_=!1;for(u=y.length-1;u>=0;u--){var x=e[y[u]],k=x.name!=m,O=x.important,C=x.hack;if(!x.unused&&(!k||!O)&&(O||!(C&&!b||!C&&b))&&(!O||"star"!=b&&"underscore"!=b)&&(C||b||k||!w||w(x,g,n))){if(O&&!v||O&&b){g.unused=!0,s=g;continue e}_=!0,x.unused=!0}}if(_){f=-1,s=null,c=null,l={};continue}}else{l[m]=l[m]||[],l[m].push(f);var S=p[m];if(S)for(u=S.length-1;u>=0;u--){var E=S[u];l[E]=l[E]||[],l[E].push(f)}}c=m,s=g}}}function i(e,t,r,o,h,p){var d=a(t);s(d,p),n(d,r,h.aggressiveMerging,p);for(var g=0,m=d.length;m>g;g++){var v=d[g];v.variable&&v.block&&i(e,v.value[0],r,o,h,p)}o&&h.shorthandCompacting&&(u(d,h.compatibility,p),l(d,h.sourceMap,p)),f(d),c(d)}var o=e("./compactable"),a=e("./wrap-for-optimizing").all,s=e("./populate-components"),u=e("./override-compactor"),l=e("./shorthand-compactor"),c=e("./remove-unused"),f=e("./restore-from-optimizing"),h=e("../stringifier/one-time").property,p={"animation-delay":["animation"],"animation-direction":["animation"],"animation-duration":["animation"],"animation-fill-mode":["animation"],"animation-iteration-count":["animation"],"animation-name":["animation"],"animation-play-state":["animation"],"animation-timing-function":["animation"],"-moz-animation-delay":["-moz-animation"],"-moz-animation-direction":["-moz-animation"],"-moz-animation-duration":["-moz-animation"],"-moz-animation-fill-mode":["-moz-animation"],"-moz-animation-iteration-count":["-moz-animation"],"-moz-animation-name":["-moz-animation"],"-moz-animation-play-state":["-moz-animation"],"-moz-animation-timing-function":["-moz-animation"],"-o-animation-delay":["-o-animation"],"-o-animation-direction":["-o-animation"],"-o-animation-duration":["-o-animation"],"-o-animation-fill-mode":["-o-animation"],"-o-animation-iteration-count":["-o-animation"],"-o-animation-name":["-o-animation"],"-o-animation-play-state":["-o-animation"],"-o-animation-timing-function":["-o-animation"],"-webkit-animation-delay":["-webkit-animation"],"-webkit-animation-direction":["-webkit-animation"],"-webkit-animation-duration":["-webkit-animation"],"-webkit-animation-fill-mode":["-webkit-animation"],"-webkit-animation-iteration-count":["-webkit-animation"],"-webkit-animation-name":["-webkit-animation"],"-webkit-animation-play-state":["-webkit-animation"],"-webkit-animation-timing-function":["-webkit-animation"],"border-color":["border"],"border-style":["border"],"border-width":["border"],"border-bottom":["border"],"border-bottom-color":["border-bottom","border-color","border"],"border-bottom-style":["border-bottom","border-style","border"],"border-bottom-width":["border-bottom","border-width","border"],"border-left":["border"],"border-left-color":["border-left","border-color","border"],"border-left-style":["border-left","border-style","border"],"border-left-width":["border-left","border-width","border"],"border-right":["border"],"border-right-color":["border-right","border-color","border"],"border-right-style":["border-right","border-style","border"],"border-right-width":["border-right","border-width","border"],"border-top":["border"],"border-top-color":["border-top","border-color","border"],"border-top-style":["border-top","border-style","border"],"border-top-width":["border-top","border-width","border"],"font-family":["font"],"font-size":["font"],"font-style":["font"],"font-variant":["font"],"font-weight":["font"],"transition-delay":["transition"],"transition-duration":["transition"],"transition-property":["transition"],"transition-timing-function":["transition"],"-moz-transition-delay":["-moz-transition"],"-moz-transition-duration":["-moz-transition"],"-moz-transition-property":["-moz-transition"],"-moz-transition-timing-function":["-moz-transition"],"-o-transition-delay":["-o-transition"],"-o-transition-duration":["-o-transition"],"-o-transition-property":["-o-transition"],"-o-transition-timing-function":["-o-transition"],"-webkit-transition-delay":["-webkit-transition"],"-webkit-transition-duration":["-webkit-transition"],"-webkit-transition-property":["-webkit-transition"],"-webkit-transition-timing-function":["-webkit-transition"]};t.exports=i},{"../stringifier/one-time":44,"./compactable":15,"./override-compactor":19,"./populate-components":20,"./remove-unused":21,"./restore-from-optimizing":22,"./shorthand-compactor":24,"./wrap-for-optimizing":27}],19:[function(e,t,r){function n(e){return function(t){return e.name===t.name}}function i(e,t){for(var r=0;r-1}function a(e,t){t.unused=!0,f(t,h(e)),e.value=t.value}function s(e,t){t.unused=!0,e.multiplex=!0,e.value=t.value}function u(e,t){t.unused=!0,e.value=t.value}function l(e,t){t.multiplex?s(e,t):e.multiplex?a(e,t):u(e,t)}function c(e,t){t.unused=!0;for(var r=0,n=e.components.length;n>r;r++)l(e.components[r],t.components[r],e.multiplex)}function f(e,t){e.multiplex=!0;for(var r=0,n=e.components.length;n>r;r++){var i=e.components[r];if(!i.multiplex)for(var o=i.value.slice(0),a=1;t>a;a++)i.value.push([j]),Array.prototype.push.apply(i.value,o)}}function h(e){for(var t=0,r=0,n=e.value.length;n>r;r++)e.value[r][0]==j&&t++;return t+1}function p(e){var t=[[e.name]].concat(e.value);return L([t],0).length}function d(e,t,r){for(var n=0,i=t;i>=0&&(e[i].name!=r||e[i].unused||n++,!(n>1));i--);return n>1}function g(e,t){for(var r=0,n=e.components.length;n>r;r++)if(m(t.isValidFunction,e.components[r]))return!0;return!1}function m(e,t){for(var r=0,n=t.value.length;n>r;r++)if(t.value[r][0]!=j&&e(t.value[r][0]))return!0;return!1}function v(e,t){if(!e.multiplex&&!t.multiplex||e.multiplex&&t.multiplex)return!1;var r,i=e.multiplex?e:t,o=e.multiplex?t:e,u=C(i);A([u]);var l=C(o);A([l]);var c=p(u)+1+p(l);e.multiplex?(r=u.components.filter(n(l))[0],a(r,l)):(r=l.components.filter(n(u))[0],f(l,h(u)),s(r,u)),A([l]);var d=p(l);return d>c}function b(e){return e.name in O}function y(e,t){return!e.multiplex&&("background"==e.name||"background-image"==e.name)&&t.multiplex&&("background"==t.name||"background-image"==t.name)&&w(t.value)}function w(e){for(var t=_(e),r=0,n=t.length;n>r;r++)if(1==t[r].length&&"none"==t[r][0][0])return!0;return!1}function _(e){for(var t=[],r=0,n=[],i=e.length;i>r;r++){var o=e[r];o[0]==j?(t.push(n),n=[]):n.push(o)}return t.push(n),t}function x(e,t,r){var a,s,u,p,w,_,x;e:for(w=e.length-1;w>=0;w--)if(s=e[w],b(s)&&!s.variable)for(a=O[s.name].canOverride||k.sameValue,_=w-1;_>=0;_--)if(u=e[_],b(u)&&!(u.variable||u.unused||s.unused||u.hack&&!s.hack||!u.hack&&s.hack||E(s)||y(u,s)))if(!u.shorthand&&s.shorthand&&o(s,u)){if(!s.important&&u.important)continue;if(!M([u],s.components))continue;if(!m(r.isValidFunction,u)&&g(s,r))continue;p=s.components.filter(n(u))[0],a=O[u.name]&&O[u.name].canOverride||k.sameValue,R(a,u,p,r)&&(u.unused=!0)}else if(u.shorthand&&!s.shorthand&&o(u,s)){if(s.important&&!u.important)continue;if(d(e,w-1,u.name))continue;if(g(u,r))continue;if(p=u.components.filter(n(s))[0],R(a,p,s,r)){var C=!t.properties.backgroundClipMerging&&p.name.indexOf("background-clip")>-1||!t.properties.backgroundOriginMerging&&p.name.indexOf("background-origin")>-1||!t.properties.backgroundSizeMerging&&p.name.indexOf("background-size")>-1,S=O[s.name].nonMergeableValue===s.value[0][0];if(C||S)continue;if(!t.properties.merging&&i(u,r))continue;if(p.value[0][0]!=s.value[0][0]&&(E(u)||E(s)))continue;if(v(u,s))continue;!u.multiplex&&s.multiplex&&f(u,h(s)),l(p,s),u.dirty=!0}}else if(u.shorthand&&s.shorthand&&u.name==s.name){if(!u.multiplex&&s.multiplex)continue;if(!s.important&&u.important){s.unused=!0;continue e}if(s.important&&!u.important){u.unused=!0;continue}for(x=u.components.length-1;x>=0;x--){var A=u.components[x],L=s.components[x];if(a=O[A.name].canOverride||k.sameValue,!R(a,A,L,r))continue e;if(!R(k.twoOptionalFunctions,A,L,r)&&r.isValidFunction(L))continue e}c(u,s),u.dirty=!0}else if(u.shorthand&&s.shorthand&&o(u,s)){if(!u.important&&s.important)continue;if(p=u.components.filter(n(s))[0],a=O[s.name].canOverride||k.sameValue,!R(a,p,s,r))continue;if(u.important&&!s.important){s.unused=!0;continue}var j=O[s.name].restore(s,O);if(j.length>1)continue;p=u.components.filter(n(s))[0],l(p,s),s.dirty=!0}else if(u.name==s.name){if(u.important&&!s.important){s.unused=!0;continue}if(a=O[s.name].canOverride||k.sameValue,!R(a,u,s,r))continue;u.unused=!0}}var k=e("./can-override"),O=e("./compactable"),C=e("./clone").deep,S=e("./clone").shallow,E=e("./has-inherit"),A=e("./restore-from-optimizing"),R=e("./every-combination"),M=e("./vendor-prefixes").same,L=e("../stringifier/one-time").property,j=",";t.exports=x},{"../stringifier/one-time":44,"./can-override":13,"./clone":14,"./compactable":15,"./every-combination":16,"./has-inherit":17,"./restore-from-optimizing":22,"./vendor-prefixes":26}],20:[function(e,t,r){function n(e,t){for(var r=e.length-1;r>=0;r--){var n=e[r],o=i[n.name];o&&o.shorthand&&(n.shorthand=!0,n.dirty=!0,n.components=o.breakUp(n,i,t),n.components.length>0?n.multiplex=n.components[0].multiplex:n.unused=!0)}}var i=e("./compactable");t.exports=n},{"./compactable":15}],21:[function(e,t,r){function n(e){for(var t=e.length-1;t>=0;t--){var r=e[t];r.unused&&r.all.splice(r.position,1)}}t.exports=n},{}],22:[function(e,t,r){function n(e){e.value[e.value.length-1][0]+=u}function i(e){"underscore"==e.hack?e.name=c+e.name:"star"==e.hack?e.name=l+e.name:"backslash"==e.hack?e.value[e.value.length-1][0]+=s:"bang"==e.hack&&(e.value[e.value.length-1][0]+=" "+f)}function o(e,t){for(var r=e.length-1;r>=0;r--){var o,s=e[r],u=a[s.name];if(!s.unused&&(s.dirty||s.important||s.hack)&&(!t&&u&&u.shorthand?(o=u.restore(s,a),s.value=o):o=s.value,s.important&&n(s),s.hack&&i(s),"all"in s)){var l=s.all[s.position];l[0][0]=s.name,l.splice(1,l.length-1),Array.prototype.push.apply(l,o)}}}var a=e("./compactable"),s="\\9",u="!important",l="*",c="_",f="!ie";t.exports=o},{"./compactable":15}],23:[function(e,t,r){function n(e){for(var t=0,r=e.length;r>t;t++){var n=e[t][0];if("inherit"!=n&&n!=c&&n!=f)return!1}return!0}function i(e,t,r){function i(e){Array.prototype.unshift.apply(l,e.value)}function o(e){var r=t[e.name];return r.doubleValues?1==r.defaultValue.length?e.value[0][0]==r.defaultValue[0]&&(e.value[1]?e.value[1][0]==r.defaultValue[0]:!0):e.value[0][0]==r.defaultValue[0]&&(e.value[1]?e.value[1][0]:e.value[0][0])==r.defaultValue[1]:e.value[0][0]==r.defaultValue}for(var a,s,u=e.components,l=[],c=u.length-1;c>=0;c--){var h=u[c],p=o(h);if("background-clip"==h.name){var d=u[c-1],g=o(d);a=h.value[0][0]==d.value[0][0],s=!a&&(g&&!p||!g&&!p||!g&&p&&h.value[0][0]!=d.value[0][0]),a?i(d):s&&(i(h),i(d)),c--}else if("background-size"==h.name){var m=u[c-1],v=o(m);a=!v&&p,s=!a&&(v&&!p||!v&&!p),a?i(m):s?(i(h),l.unshift([f]),i(m)):1==m.value.length&&i(m),c--}else{if(p||t[h.name].multiplexLastOnly&&!r)continue;i(h)}}return 0===l.length&&1==e.value.length&&"0"==e.value[0][0]&&l.push(e.value[0]),0===l.length&&l.push([t[e.name].defaultValue]),n(l)?[l[0]]:l}function o(e,t){if(e.multiplex){for(var r=l(e),n=l(e),i=0;4>i;i++){var o=e.components[i],s=l(e);s.value=[o.value[0]],r.components.push(s);var u=l(e);u.value=[o.value[2]],n.components.push(u)}var c=a(r,t),f=a(n,t);return c.length!=f.length||c[0][0]!=f[0][0]||(c.length>1?c[1][0]!=f[1][0]:0)||(c.length>2?c[2][0]!=f[2][0]:0)||(c.length>3?c[3][0]!=f[3][0]:0)?c.concat([["/"]]).concat(f):c}return a(e,t)}function a(e){var t=e.components,r=t[0].value[0],n=t[1].value[0],i=t[2].value[0],o=t[3].value[0];return r[0]==n[0]&&r[0]==i[0]&&r[0]==o[0]?[r]:r[0]==i[0]&&n[0]==o[0]?[r,n]:n[0]==o[0]?[r,n,i]:[r,n,i,o]}function s(e){return function(t,r){if(!t.multiplex)return e(t,r,!0);var n,i,o=0,a=[],s={};for(n=0,i=t.components[0].value.length;i>n;n++)t.components[0].value[n][0]==c&&o++;for(n=0;o>=n;n++){for(var u=l(t),f=0,h=t.components.length;h>f;f++){var p=t.components[f],d=l(p);u.components.push(d);for(var g=s[d.name]||0,m=p.value.length;m>g;g++){if(p.value[g][0]==c){s[d.name]=g+1;break}d.value.push(p.value[g])}}var v=n==o,b=e(u,r,v);Array.prototype.push.apply(a,b),o>n&&a.push([","])}return a}}function u(e,t){for(var r=e.components,i=[],o=r.length-1;o>=0;o--){var a=r[o],s=t[a.name];a.value[0][0]!=s.defaultValue&&i.unshift(a.value[0])}return 0===i.length&&i.push([t[e.name].defaultValue]),n(i)?[i[0]]:i}var l=e("./clone").shallow,c=",",f="/";t.exports={background:i,borderRadius:o,fourValues:a,multiplex:s,withoutDefaults:u}},{"./clone":14}],24:[function(e,t,r){function n(e){var t;for(var r in e){if(void 0!==t&&e[r].important!=t)return!0;t=e[r].important}return!1}function i(e){var t=[];for(var r in e){var n=e[r],i=n.all[n.position],o=i[0][i[0].length-1];Array.isArray(o)&&Array.prototype.push.apply(t,o)}return t}function o(e,t,r,n,o){var a,s=u[r],d=[[r],[s.defaultValue]],g=h(d);g.shorthand=!0,g.dirty=!0,f([g],o);for(var m=0,v=s.components.length;v>m;m++){var b=t[s.components[m]],y=u[b.name].canOverride;if(c(b))return;if(!p(y,g.components[m],b,o))return;g.components[m]=l(b),g.important=b.important,a=b.all}for(var w in t)t[w].unused=!0;if(n){var _=i(t);_.length>0&&d[0].push(_)}g.position=a.length,g.all=a,g.all.push(d),e.push(g)}function a(e,t,r,i,a){var s=e[t];for(var l in r)if(void 0===s||l!=s.name){var c=u[l],f=r[l];c.components.length>Object.keys(f).length?delete r[l]:n(f)||o(e,f,l,i,a)}}function s(e,t,r){var n={};if(!(e.length<3)){for(var i=0,o=e.length;o>i;i++){var s=e[i];if(!s.unused&&!s.hack&&!s.variable){var l=u[s.name];if(l&&l.componentOf)if(s.shorthand)a(e,i,n,t,r);else{var c=l.componentOf;n[c]=n[c]||{},n[c][s.name]=s}}}a(e,i,n,t,r)}}var u=e("./compactable"),l=e("./clone").deep,c=e("./has-inherit"),f=e("./populate-components"),h=e("./wrap-for-optimizing").single,p=e("./every-combination");t.exports=s},{"./clone":14,"./compactable":15,"./every-combination":16,"./has-inherit":17,"./populate-components":20,"./wrap-for-optimizing":27}],25:[function(e,t,r){function n(e){var t=a.slice(0).filter(function(t){return!(t in e.units)||e.units[t]===!0}),r="(\\-?\\.?\\d+\\.?\\d*("+t.join("|")+"|)|auto|inherit)";this.compatibleCssUnitRegex=new RegExp("^"+r+"$","i"),this.compatibleCssUnitAnyRegex=new RegExp("^(none|"+o.join("|")+"|"+r+"|"+f+"|"+l+"|"+c+")$","i"),this.colorOpacity=e.colors.opacity}var i=e("../utils/split"),o=["thin","thick","medium","inherit","initial"],a=["px","%","em","in","cm","mm","ex","pt","pc","ch","rem","vh","vm","vmin","vmax","vw"],s="(\\-?\\.?\\d+\\.?\\d*("+a.join("|")+"|)|auto|inherit)",u="(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)",l="[A-Z]+(\\-|[A-Z]|[0-9])+\\(.*?\\)",c="\\-(\\-|[A-Z]|[0-9])+\\(.*?\\)",f="var\\(\\-\\-[^\\)]+\\)",h="("+f+"|"+l+"|"+c+")",p="("+s+"|"+u+")",d="(none|"+o.join("|")+"|"+s+"|"+f+"|"+l+"|"+c+")",g=new RegExp("^"+l+"$","i"),m=new RegExp("^"+c+"$","i"),v=new RegExp("^"+f+"$","i"),b=new RegExp("^"+h+"$","i"),y=new RegExp("^"+s+"$","i"),w=new RegExp("^"+p+"$","i"),_=new RegExp("^"+d+"$","i"),x=["repeat","no-repeat","repeat-x","repeat-y","inherit"],k=["inherit","scroll","fixed","local"],O=["center","top","bottom","left","right"],C=["contain","cover"],S=["border-box","content-box","padding-box"],E=["auto","inherit","hidden","none","dotted","dashed","solid","double","groove","ridge","inset","outset"],A=["armenian","circle","cjk-ideographic","decimal","decimal-leading-zero","disc","georgian","hebrew","hiragana","hiragana-iroha","inherit","katakana","katakana-iroha","lower-alpha","lower-greek","lower-latin","lower-roman","none","square","upper-alpha","upper-latin","upper-roman"],R=["inside","outside","inherit"];n.prototype.isValidHexColor=function(e){return(4===e.length||7===e.length)&&"#"===e[0]},n.prototype.isValidRgbaColor=function(e){return e=e.split(" ").join(""),e.length>0&&0===e.indexOf("rgba(")&&e.indexOf(")")===e.length-1},n.prototype.isValidHslaColor=function(e){return e=e.split(" ").join(""),e.length>0&&0===e.indexOf("hsla(")&&e.indexOf(")")===e.length-1},n.prototype.isValidNamedColor=function(e){return"auto"!==e&&("transparent"===e||"inherit"===e||/^[a-zA-Z]+$/.test(e))},n.prototype.isValidVariable=function(e){return v.test(e)},n.prototype.isValidColor=function(e){return this.isValidNamedColor(e)||this.isValidColorValue(e)||this.isValidVariable(e)||this.isValidVendorPrefixedValue(e)},n.prototype.isValidColorValue=function(e){return this.isValidHexColor(e)||this.isValidRgbaColor(e)||this.isValidHslaColor(e)},n.prototype.isValidUrl=function(e){return 0===e.indexOf("__ESCAPED_URL_CLEAN_CSS"); -},n.prototype.isValidUnit=function(e){return _.test(e)},n.prototype.isValidUnitWithoutFunction=function(e){return y.test(e)},n.prototype.isValidAndCompatibleUnit=function(e){return this.compatibleCssUnitAnyRegex.test(e)},n.prototype.isValidAndCompatibleUnitWithoutFunction=function(e){return this.compatibleCssUnitRegex.test(e)},n.prototype.isValidFunctionWithoutVendorPrefix=function(e){return g.test(e)},n.prototype.isValidFunctionWithVendorPrefix=function(e){return m.test(e)},n.prototype.isValidFunction=function(e){return b.test(e)},n.prototype.isValidBackgroundRepeat=function(e){return x.indexOf(e)>=0||this.isValidVariable(e)},n.prototype.isValidBackgroundAttachment=function(e){return k.indexOf(e)>=0||this.isValidVariable(e)},n.prototype.isValidBackgroundBox=function(e){return S.indexOf(e)>=0||this.isValidVariable(e)},n.prototype.isValidBackgroundPositionPart=function(e){return O.indexOf(e)>=0||w.test(e)||this.isValidVariable(e)},n.prototype.isValidBackgroundPosition=function(e){if("inherit"===e)return!0;for(var t=e.split(" "),r=0,n=t.length;n>r;r++)if(""!==t[r]&&!this.isValidBackgroundPositionPart(t[r])&&!this.isValidVariable(t[r]))return!1;return!0},n.prototype.isValidBackgroundSizePart=function(e){return C.indexOf(e)>=0||y.test(e)||this.isValidVariable(e)},n.prototype.isValidBackgroundPositionAndSize=function(e){if(e.indexOf("/")<0)return!1;var t=i(e,"/");return this.isValidBackgroundSizePart(t.pop())&&this.isValidBackgroundPositionPart(t.pop())},n.prototype.isValidListStyleType=function(e){return A.indexOf(e)>=0||this.isValidVariable(e)},n.prototype.isValidListStylePosition=function(e){return R.indexOf(e)>=0||this.isValidVariable(e)},n.prototype.isValidStyle=function(e){return this.isValidStyleKeyword(e)||this.isValidVariable(e)},n.prototype.isValidStyleKeyword=function(e){return E.indexOf(e)>=0},n.prototype.isValidWidth=function(e){return this.isValidUnit(e)||this.isValidWidthKeyword(e)||this.isValidVariable(e)},n.prototype.isValidWidthKeyword=function(e){return o.indexOf(e)>=0},n.prototype.isValidVendorPrefixedValue=function(e){return/^-([A-Za-z0-9]|-)*$/gi.test(e)},n.prototype.areSameFunction=function(e,t){if(!this.isValidFunction(e)||!this.isValidFunction(t))return!1;var r=e.substring(0,e.indexOf("(")),n=t.substring(0,t.indexOf("("));return r===n},t.exports=n},{"../utils/split":65}],26:[function(e,t,r){function n(e){for(var t=[],r=0,n=e.length;n>r;r++)for(var i=e[r],a=0,s=i.value.length;s>a;a++){var u=o.exec(i.value[a][0]);u&&-1==t.indexOf(u[0])&&t.push(u[0])}return t}function i(e,t){return n(e).sort().join(",")==n(t).sort().join(",")}var o=/$\-moz\-|\-ms\-|\-o\-|\-webkit\-/;t.exports={same:i}},{}],27:[function(e,t,r){function n(e){for(var t=[],r=e.length-1;r>=0;r--)if("string"!=typeof e[r][0]){var n=c(e[r]);n.all=e,n.position=r,t.unshift(n)}return t}function i(e){for(var t=1,r=e.length;r>t;t++)if(","==e[t][0]||"/"==e[t][0])return!0;return!1}function o(e){var t=!1,r=e[0][0],n=e[e.length-1];return r[0]==d?t="underscore":r[0]==p?t="star":n[0][0]==g&&-1==n[0].indexOf("important")?t="bang":n[0].indexOf(g)>0&&-1==n[0].indexOf("important")?t="bang":n[0].indexOf(f)>0&&n[0].indexOf(f)==n[0].length-f.length-1?t="backslash":0===n[0].indexOf(f)&&2==n[0].length&&(t="backslash"),t}function a(e){return e.length>1?e[e.length-1][0].indexOf(h)>0:!1}function s(e){e.length>0&&(e[e.length-1][0]=e[e.length-1][0].replace(h,""))}function u(e){e[0][0]=e[0][0].substring(1)}function l(e,t){var r=e[e.length-1];r[0]=r[0].substring(0,r[0].indexOf("backslash"==t?f:g)).trim(),0===r[0].length&&e.pop()}function c(e){var t=a(e);t&&s(e);var r=o(e);"star"==r||"underscore"==r?u(e):"backslash"!=r&&"bang"!=r||l(e,r);var n=0===e[0][0].indexOf("--");return{block:n&&e[1]&&Array.isArray(e[1][0][0]),components:[],dirty:!1,hack:r,important:t,name:e[0][0],multiplex:e.length>2?i(e):!1,position:0,shorthand:!1,unused:e.length<2,value:e.slice(1),variable:n}}var f="\\",h="!important",p="*",d="_",g="!";t.exports={all:n,single:c}},{}],28:[function(e,t,r){function n(e){for(var t=0,r=e.length;r>t;t++){var i=e[t],o=!1;switch(i[0]){case"selector":o=0===i[1].length||0===i[2].length;break;case"block":n(i[2]),o=0===i[2].length}o&&(e.splice(t,1),t--,r--)}}function i(e,t,r){for(var n=0,i=e.length;i>n;n++){var o=e[n];if("block"==o[0]){var s=/@(-moz-|-o-|-webkit-)?keyframes/.test(o[1][0]);a(o[2],t,r,!s)}}}function o(e,t,r){for(var n=0,i=e.length;i>n;n++){var a=e[n];switch(a[0]){case"selector":s(a[1],a[2],!1,!0,t,r);break;case"block":o(a[2],t,r)}}}function a(e,t,r,s){if(i(e,t,r),o(e,t,r),u(e),l(e,t,r),c(e,t,r),f(e,t,r),h(e,t),t.restructuring&&s&&(p(e,t),l(e,t,r)),t.mediaMerging){d(e);for(var m=g(e),v=m.length-1;v>=0;v--)a(m[v][2],t,r,!1)}n(e)}var s=e("../properties/optimizer"),u=e("./remove-duplicates"),l=e("./merge-adjacent"),c=e("./reduce-non-adjacent"),f=e("./merge-non-adjacent-by-selector"),h=e("./merge-non-adjacent-by-body"),p=e("./restructure"),d=e("./remove-duplicate-media-queries"),g=e("./merge-media-queries");t.exports=a},{"../properties/optimizer":18,"./merge-adjacent":32,"./merge-media-queries":33,"./merge-non-adjacent-by-body":34,"./merge-non-adjacent-by-selector":35,"./reduce-non-adjacent":36,"./remove-duplicate-media-queries":37,"./remove-duplicates":38,"./restructure":40}],29:[function(e,t,r){function n(e,t){return"["+t.replace(/ /g,"")+"]"}function i(e,t){return e[0]>t[0]?1:-1}function o(e,t,r,n){return t&&r&&n.length?t+r+" ":t&&r?t+r:r}var a={selectors:function(e,t,r){for(var a=[],s=[],u=0,l=e.length;l>u;u++){var c=e[u],f=c[0].replace(/\s+/g," ").replace(/ ?, ?/g,",").replace(/\s*(\\)?([>+~])(\s*)/g,o).trim();r&&f.indexOf("nav")>0&&(f=f.replace(/\+nav(\S|$)/,"+ nav$1")),(!t||-1==f.indexOf("*+html ")&&-1==f.indexOf("*:first-child+html "))&&(f.indexOf("*")>-1&&(f=f.replace(/\*([:#\.\[])/g,"$1").replace(/^(\:first\-child)?\+html/,"*$1+html")),f.indexOf("[")>-1&&(f=f.replace(/\[([^\]]+)\]/g,n)),-1==s.indexOf(f)&&(c[0]=f,s.push(f),a.push(c)))}return a.sort(i)},selectorDuplicates:function(e){for(var t=[],r=[],n=0,o=e.length;o>n;n++){var a=e[n];-1==r.indexOf(a[0])&&(r.push(a[0]),t.push(a))}return t.sort(i)},block:function(e,t){e[0]=e[0].replace(/\s+/g," ").replace(/(,|:|\() /g,"$1").replace(/ \)/g,")"),t||(e[0]=e[0].replace(/\) /g,")"))},atRule:function(e){e[0]=e[0].replace(/\s+/g," ").trim()}};t.exports=a},{}],30:[function(e,t,r){function n(e){var t=[];if("selector"==e[0])for(var r=!/[\.\+>~]/.test(o(e[1])),u=0,l=e[2].length;l>u;u++){var c=e[2][u];if(0!==c.indexOf("__ESCAPED")&&c[0]!=s){var f=e[2][u][0][0];if(0!==f.length&&0!==f.indexOf("--")){var h=a(e[2],u);t.push([f,h,i(f),e[2][u],f+":"+h,e[1],r])}}}else if("block"==e[0])for(var p=0,d=e[2].length;d>p;p++)t=t.concat(n(e[2][p]));return t}function i(e){return"list-style"==e?e:e.indexOf("-radius")>0?"border-radius":"border-collapse"==e||"border-spacing"==e||"border-image"==e?e:0===e.indexOf("border-")&&/^border\-\w+\-\w+$/.test(e)?e.match(/border\-\w+/)[0]:0===e.indexOf("border-")&&/^border\-\w+$/.test(e)?"border":0===e.indexOf("text-")?e:e.replace(/^\-\w+\-/,"").match(/([a-zA-Z]+)/)[0].toLowerCase()}var o=e("../stringifier/one-time").selectors,a=e("../stringifier/one-time").value,s="at-rule";t.exports=n},{"../stringifier/one-time":44}],31:[function(e,t,r){function n(e,t){return e.compatibility.selectors.special.test(t)}t.exports=n},{}],32:[function(e,t,r){function n(e,t,r){for(var n=[null,[],[]],l=t.compatibility.selectors.adjacentSpace,c=0,f=e.length;f>c;c++){var h=e[c];if("selector"==h[0])if("selector"==n[0]&&a(h[1])==a(n[1])){var p=[n[2].length];Array.prototype.push.apply(n[2],h[2]),i(h[1],n[2],p,!0,t,r),h[2]=[]}else"selector"!=n[0]||o(h[2])!=o(n[2])||u(t,a(h[1]))||u(t,a(n[1]))?n=h:(n[1]=s(n[1].concat(h[1]),!1,l),h[2]=[]);else n=[null,[],[]]}}var i=e("../properties/optimizer"),o=e("../stringifier/one-time").body,a=e("../stringifier/one-time").selectors,s=e("./clean-up").selectors,u=e("./is-special");t.exports=n},{"../properties/optimizer":18,"../stringifier/one-time":44,"./clean-up":29,"./is-special":31}],33:[function(e,t,r){function n(e){for(var t={},r=[],n=e.length-1;n>=0;n--){var a=e[n];if("block"==a[0]){var s=t[a[1][0]];s||(s=[],t[a[1][0]]=s),s.push(n)}}for(var u in t){var l=t[u];e:for(var c=l.length-1;c>0;c--){var f=l[c],h=e[f],p=l[c-1],d=e[p];t:for(var g=1;g>=-1;g-=2){for(var m=1==g,v=m?f+1:p-1,b=m?p:f,y=m?1:-1,w=m?h:d,_=m?d:h,x=o(w);v!=b;){var k=o(e[v]);if(v+=y,!i(x,k))continue t}_[2]=m?w[2].concat(_[2]):_[2].concat(w[2]),w[2]=[],r.push(_);continue e}}}return r}var i=e("./reorderable").canReorder,o=e("./extractor");t.exports=n},{"./extractor":30,"./reorderable":39}],34:[function(e,t,r){function n(e){return/\.|\*| :/.test(e)}function i(e){var t=l(e[1]);return t.indexOf("__")>-1||t.indexOf("--")>-1}function o(e){return e.replace(/--[^ ,>\+~:]+/g,"")}function a(e,t){var r=o(l(e[1]));for(var n in t){var i=t[n],a=o(l(i[1]));(a.indexOf(r)>-1||r.indexOf(a)>-1)&&delete t[n]}}function s(e,t){for(var r={},o=t.compatibility.selectors.adjacentSpace,s=e.length-1;s>=0;s--){var h=e[s];if("selector"==h[0]){h[2].length>0&&!t.semanticMerging&&n(l(h[1]))&&(r={}),h[2].length>0&&t.semanticMerging&&i(h)&&a(h,r);var p=u(h[2]),d=r[p];!d||f(t,l(h[1]))||f(t,l(d[1]))||(h[1]=h[2].length>0?c(d[1].concat(h[1]),!1,o):d[1].concat(h[1]),d[2]=[],r[p]=null),r[u(h[2])]=h}}}var u=e("../stringifier/one-time").body,l=e("../stringifier/one-time").selectors,c=e("./clean-up").selectors,f=e("./is-special");t.exports=s},{"../stringifier/one-time":44,"./clean-up":29,"./is-special":31}],35:[function(e,t,r){function n(e,t,r){var n,u={},l=[];for(n=e.length-1;n>=0;n--)if("selector"==e[n][0]&&0!==e[n][2].length){var c=o(e[n][1]);u[c]=[n].concat(u[c]||[]),2==u[c].length&&l.push(c)}for(n=l.length-1;n>=0;n--){var f=u[l[n]];e:for(var h=f.length-1;h>0;h--){var p=f[h-1],d=e[p],g=f[h],m=e[g];t:for(var v=1;v>=-1;v-=2){for(var b,y=1==v,w=y?p+1:g-1,_=y?g:p,x=y?1:-1,k=y?d:m,O=y?m:d,C=a(k);w!=_;){var S=a(e[w]);w+=x;var E=y?s(C,S):s(S,C);if(!E&&!y)continue e;if(!E&&y)continue t}y?(b=[k[2].length],Array.prototype.push.apply(k[2],O[2]),O[2]=k[2]):(b=[O[2].length],Array.prototype.push.apply(O[2],k[2])),i(O[1],O[2],b,!0,t,r),k[2]=[]}}}}var i=e("../properties/optimizer"),o=e("../stringifier/one-time").selectors,a=e("./extractor"),s=e("./reorderable").canReorder;t.exports=n},{"../properties/optimizer":18,"../stringifier/one-time":44,"./extractor":30,"./reorderable":39}],36:[function(e,t,r){function n(e,t,r){for(var n={},s=[],u=e.length-1;u>=0;u--){var l=e[u];if("selector"==l[0]&&0!==l[2].length)for(var h=c(l[1]),p=l[1].length>1&&!f(t,h),d=t.sourceMap?i(l[1]):l[1],g=p?[h].concat(d):[h],m=0,v=g.length;v>m;m++){var b=g[m];n[b]?s.push(b):n[b]=[],n[b].push({where:u,list:d,isPartial:p&&m>0,isComplex:p&&0===m})}}o(e,s,n,t,r),a(e,n,t,r)}function i(e){for(var t=[],r=0;ru;u++){var c=t[u],f=r[c];s(e,c,f,{filterOut:o,callback:a},n,i)}}function a(e,t,r,n){function i(e){return a.data[e].wherem;m++){var b=g[m],y=t[b];if(y.length<2)continue e;if(a.data=y,s(e,b,y,{filterOut:i,callback:o},r,n),l(d[d.length-1])!=l(d[0]))continue e}p[2]=d[0]}}}function s(e,t,r,n,i,o){for(var a=[],s=[],l=[],c=[],f=r.length-1,p=0;f>=0;f--)if(!n.filterOut(f,a)){var d=r[f].where,g=e[d],m=h(g[2]);a=a.concat(m),s.push(m),c.push(d)}for(f=0,p=s.length;p>f;f++)s[f].length>0&&l.push((l[f-1]||0)+s[f].length);u(t,a,l,!1,i,o);for(var v=c.length,b=a.length-1,y=v-1;y>=0;)if((0===y||a[b]&&s[y].indexOf(a[b])>-1)&&b>-1)b--;else{var w=a.splice(b+1);n.callback(e[c[y]],w,v,y),y--}}var u=e("../properties/optimizer"),l=e("../stringifier/one-time").body,c=e("../stringifier/one-time").selectors,f=e("./is-special"),h=e("../utils/clone-array");t.exports=n},{"../properties/optimizer":18,"../stringifier/one-time":44,"../utils/clone-array":58,"./is-special":31}],37:[function(e,t,r){function n(e){for(var t={},r=0,n=e.length;n>r;r++){var o=e[r];if("block"==o[0]){var a=o[1][0]+"%"+i(o[2]),s=t[a];s&&(s[2]=[]),t[a]=o}}}var i=e("../stringifier/one-time").all;t.exports=n},{"../stringifier/one-time":44}],38:[function(e,t,r){function n(e){for(var t,r,n,a,s={},u=[],l=0,c=e.length;c>l;l++)r=e[l],"selector"==r[0]&&(t=o(r[1]),s[t]&&1==s[t].length?u.push(t):s[t]=s[t]||[],s[t].push(l));for(l=0,c=u.length;c>l;l++){t=u[l],a=[];for(var f=s[t].length-1;f>=0;f--)r=e[s[t][f]],n=i(r[2]),a.indexOf(n)>-1?r[2]=[]:a.push(n)}}var i=e("../stringifier/one-time").body,o=e("../stringifier/one-time").selectors;t.exports=n},{"../stringifier/one-time":44}],39:[function(e,t,r){function n(e,t){for(var r=t.length-1;r>=0;r--)for(var n=e.length-1;n>=0;n--)if(!i(e[n],t[r]))return!1;return!0}function i(e,t){var r=e[0],n=e[1],i=e[2],d=e[5],g=e[6],m=t[0],v=t[1],b=t[2],y=t[5],w=t[6];return"font"==r&&"line-height"==m||"font"==m&&"line-height"==r?!1:h.test(r)&&h.test(m)?!1:i==b&&a(r)==a(m)&&o(r)^o(m)?!1:("border"!=i||!p.test(b)||"border"!=r&&r!=b)&&("border"!=b||!p.test(i)||"border"!=m&&m!=i)?"border"==i&&"border"==b&&r!=m&&(s(r)&&u(m)||u(r)&&s(m))?!1:i!=b?!0:r!=m||i!=b||n!=v&&!l(n,v)?r!=m&&i==b&&r!=i&&m!=b?!0:r!=m&&i==b&&n==v?!0:!(!w||!g||f(i)||f(b)||!c(y,d)):!0:!1}function o(e){return/^\-(?:moz|webkit|ms|o)\-/.test(e)}function a(e){return e.replace(/^\-(?:moz|webkit|ms|o)\-/,"")}function s(e){return"border-top"==e||"border-right"==e||"border-bottom"==e||"border-left"==e}function u(e){return"border-color"==e||"border-style"==e||"border-width"==e}function l(e,t){return o(e)&&o(t)&&e.split("-")[1]!=t.split("-")[2]}function c(e,t){for(var r=0,n=e.length;n>r;r++)for(var i=0,o=t.length;o>i;i++)if(e[r][0]==t[i][0])return!1;return!0}function f(e){return"font"==e||"line-height"==e||"list-style"==e}var h=/align\-items|box\-align|box\-pack|flex|justify/,p=/^border\-(top|right|bottom|left|color|style|width|radius)/;t.exports={canReorder:n,canReorderSingle:i}},{}],40:[function(e,t,r){function n(e,t){return e>t}function i(e,t){var r=h(e);return r[5]=r[5].concat(t[5]),r}function o(e,t){function r(e,t,r){for(var n=r.length-1;n>=0;n--){var i=r[n][0],a=o(t,i);if(E[a].length>1&&k(e,E[a])){h(a);break}}}function o(e,t){var r=p(t);return E[r]=E[r]||[],E[r].push([e,t]),r}function h(e){var t,r=e.split(M),n=[];for(var i in E){var o=i.split(M);for(t=o.length-1;t>=0;t--)if(r.indexOf(o[t])>-1){n.push(i);break}}for(t=n.length-1;t>=0;t--)delete E[n[t]]}function p(e){for(var t=[],r=0,n=e.length;n>r;r++)t.push(l(e[r][1]));return t.join(M)}function d(e){for(var r=[],n=[],i=e.length-1;i>=0;i--)f(t,l(e[i][1]))||(n.unshift(e[i]),e[i][2].length>0&&-1==r.indexOf(e[i])&&r.push(e[i]));return r.length>1?n:[]}function g(e,t){var n=t[0],i=t[1],o=t[4],a=n.length+i.length+1,s=[],u=[],l=d(C[o]);if(!(l.length<2)){var f=v(l,a,1),h=f[0];if(h[1]>0)return r(e,t,f);for(var p=h[0].length-1;p>=0;p--)s=h[0][p][1].concat(s),u.unshift(h[0][p]);s=c(s),w(e,[t],s,u)}}function m(e,t){return e[1]>t[1]}function v(e,t,r){var n=b(e,t,r,R-1);return n.sort(m)}function b(e,t,r,n){var i=[[e,y(e,t,r)]];if(e.length>2&&n>0)for(var o=e.length-1;o>=0;o--){var a=Array.prototype.slice.call(e,0);a.splice(o,1),i=i.concat(b(a,t,r,n-1))}return i}function y(e,t,r){for(var n=0,i=e.length-1;i>=0;i--)n+=e[i][2].length>r?l(e[i][1]).length:-1;return n-(e.length-1)*t+1}function w(t,r,n,i){var o,a,s,l,c=[];for(o=i.length-1;o>=0;o--){var f=i[o];for(a=f[2].length-1;a>=0;a--){var h=f[2][a];for(s=0,l=r.length;l>s;s++){var p=r[s],d=h[0][0],g=p[0],m=p[4];if(d==g&&u([h])==m){f[2].splice(a,1);break}}}}for(o=r.length-1;o>=0;o--)c.unshift(r[o][3]);var v=["selector",n,c];e.splice(t,0,v)}function _(e,t){var r=t[4],n=C[r];n&&n.length>1&&(x(e,t)||g(e,t))}function x(e,t){var r,n,i=[],o=[],a=t[4],s=d(C[a]);if(!(s.length<2)){e:for(var u in C){var l=C[u];for(r=s.length-1;r>=0;r--)if(-1==l.indexOf(s[r]))continue e;i.push(u)}if(i.length<2)return!1;for(r=i.length-1;r>=0;r--)for(n=S.length-1;n>=0;n--)if(S[n][4]==i[r]){o.unshift([S[n],s]);break}return k(e,o)}}function k(e,t){for(var r,n=0,i=[],o=t.length-1;o>=0;o--){r=t[o][0];var a=r[4];n+=a.length+(o>0?1:0),i.push(r)}var s=t[0][1],u=v(s,n,i.length)[0];if(u[1]>0)return!1;var l=[],f=[];for(o=u[0].length-1;o>=0;o--)l=u[0][o][1].concat(l),f.unshift(u[0][o]);for(l=c(l),w(e,i,l,f),o=i.length-1;o>=0;o--){r=i[o];var h=S.indexOf(r);delete C[r[4]],h>-1&&-1==A.indexOf(h)&&A.push(h)}return!0}function O(e,t,r){var n=e[0],i=t[0];if(n!=i)return!1;var o=t[4],a=C[o];return a&&a.indexOf(r)>-1}for(var C={},S=[],E={},A=[],R=2,M="%",L=e.length-1;L>=0;L--){var j,T,P,V,B,U=e[L];if("selector"==U[0])j=!0;else{if("block"!=U[0])continue;j=!1}var D=S.length,I=a(U);A=[];var N=[];for(T=I.length-1;T>=0;T--)for(P=T-1;P>=0;P--)if(!s(I[T],I[P])){N.push(T);break}for(T=I.length-1;T>=0;T--){var z=I[T],q=!1;for(P=0;D>P;P++){var F=S[P];-1!=A.indexOf(P)||s(z,F)||O(z,F,U)||(_(L+1,F,U),-1==A.indexOf(P)&&(A.push(P),delete C[F[4]])),q||(q=z[0]==F[0]&&z[1]==F[1],q&&(B=P))}if(j&&!(N.indexOf(T)>-1)){var $=z[4];C[$]=C[$]||[],C[$].push(U),q?S[B]=i(S[B],z):S.push(z)}}for(A=A.sort(n),T=0,V=A.length;V>T;T++){var H=A[T]-T;S.splice(H,1)}}for(var W=e[0]&&"at-rule"==e[0][0]&&0===e[0][1][0].indexOf("@charset")?1:0;W-1&&(t=t.replace(/([^\w\d\-]|^)\-0([^\.]|$)/g,"$10$2").replace(/([^\w\d\-]|^)\-0([^\.]|$)/g,"$10$2")),t.replace(/(^|\s)0+([1-9])/g,"$1$2").replace(/(^|\D)\.0+(\D|$)/g,"$10$2").replace(/(^|\D)\.0+(\D|$)/g,"$10$2").replace(/\.([1-9]*)0+(\D|$)/g,function(e,t,r){return(t.length>0?".":"")+t+r}).replace(/(^|\D)0\.(\d)/g,"$1.$2"))}function o(e,t){return-1==t.indexOf("0deg")?t:t.replace(/\(0deg\)/g,"(0)")}function a(e,t){return e.indexOf("filter")>-1||-1==t.indexOf(" ")?t:(t=t.replace(/\s+/g," "),t.indexOf("calc")>-1&&(t=t.replace(/\) ?\/ ?/g,")/ ")),t.replace(/\( /g,"(").replace(/ \)/g,")").replace(/, /g,","))}function s(e,t,r){return-1===r.value||-1===t.indexOf(".")?t:t.replace(r.regexp,function(e,t){return Math.round(parseFloat(t)*r.multiplier)/r.multiplier+"px"}).replace(/(\d)\.($|\D)/g,"$1$2")}function u(e,t,r){return/^(?:\-moz\-calc|\-webkit\-calc|calc)\(/.test(t)?t:"flex"==e||"-ms-flex"==e||"-webkit-flex"==e||"flex-basis"==e||"-webkit-flex-basis"==e?t:t.indexOf("%")>0&&("height"==e||"max-height"==e)?t:t.replace(r,"$10$2").replace(r,"$10$2")}function l(e){var t,r=e.value;4==r.length&&"0"===r[0][0]&&"0"===r[1][0]&&"0"===r[2][0]&&"0"===r[3][0]&&(t=e.name.indexOf("box-shadow")>-1?2:1),t&&(e.value.splice(t),e.dirty=!0)}function c(e,t,r){return-1===t.indexOf("#")&&-1==t.indexOf("rgb")&&-1==t.indexOf("hsl")?E.shorten(t):(t=t.replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g,function(e,t,r,n){return new C(t,r,n).toHex()}).replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g,function(e,t,r,n){return new S(t,r,n).toHex()}).replace(/(^|[^='"])#([0-9a-f]{6})/gi,function(e,t,r){return r[0]==r[1]&&r[2]==r[3]&&r[4]==r[5]?t+"#"+r[0]+r[2]+r[4]:t+"#"+r}).replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g,function(e,t,r){var n=r.split(","),i="hsl"==t&&3==n.length||"hsla"==t&&4==n.length||"rgb"==t&&3==n.length&&r.indexOf("%")>0||"rgba"==t&&4==n.length&&r.indexOf("%")>0;return i?(-1==n[1].indexOf("%")&&(n[1]+="%"),-1==n[2].indexOf("%")&&(n[2]+="%"),t+"("+n.join(",")+")"):e}),r.colors.opacity&&-1==e.indexOf("background")&&(t=t.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g,function(e){return O(t,",").pop().indexOf("gradient(")>-1?e:"transparent"})),E.shorten(t))}function f(e,t,r){return U.test(t)?t.replace(U,function(e,t){var n,i=parseInt(t);return 0===i?e:(r.properties.shorterLengthUnits&&r.units.pt&&3*i%4===0&&(n=3*i/4+"pt"),r.properties.shorterLengthUnits&&r.units.pc&&i%16===0&&(n=i/16+"pc"),r.properties.shorterLengthUnits&&r.units["in"]&&i%96===0&&(n=i/96+"in"),n&&(n=e.substring(0,e.indexOf(t))+n),n&&n.length-1||t[1]&&P.indexOf(t[1][0])>-1||t[2]&&P.indexOf(t[2][0])>-1;if(!r&&"/"!=t[1]){var n=0;if("normal"==t[0][0]&&n++,t[1]&&"normal"==t[1][0]&&n++,t[2]&&"normal"==t[2][0]&&n++,!(n>1)){var i;B.indexOf(t[0][0])>-1?i=0:t[1]&&B.indexOf(t[1][0])>-1?i=1:t[2]&&B.indexOf(t[2][0])>-1?i=2:V.indexOf(t[0][0])>-1?i=0:t[1]&&V.indexOf(t[1][0])>-1?i=1:t[2]&&V.indexOf(t[2][0])>-1&&(i=2),void 0!==i&&(e.value[i][0]=I["font-weight"](t[i][0]),e.dirty=!0)}}}function m(e,t){for(var r,v,b,y=A(e),w=0,_=y.length;_>w;w++)if(r=y[w],v=r.name,r.hack&&(("star"==r.hack||"underscore"==r.hack)&&!t.compatibility.properties.iePrefixHack||"backslash"==r.hack&&!t.compatibility.properties.ieSuffixHack||"bang"==r.hack&&!t.compatibility.properties.ieBangHack)&&(r.unused=!0),0===v.indexOf("padding")&&(n(r,0)||n(r,1)||n(r,2)||n(r,3))&&(r.unused=!0),!r.unused)if(r.variable)r.block&&m(r.value[0],t);else{for(var x=0,k=r.value.length;k>x;x++)b=r.value[x][0],I[v]&&(b=I[v](b,x,k)),b=a(v,b),b=s(v,b,t.precision),b=f(v,b,t.compatibility),b=h(v,b),b=i(v,b),t.compatibility.properties.zeroUnits&&(b=o(v,b),b=u(v,b,t.unitsRegexp)),t.compatibility.properties.colors&&(b=c(v,b,t.compatibility)),r.value[x][0]=b;l(r),0===v.indexOf("border")&&v.indexOf("radius")>0?p(r):"filter"==v?d(r):"font"==v&&g(r)}R(y,!0),M(y)}function v(e){for(var t=!1,r=0,n=e.length;n>r;r++){var i=e[r];"at-rule"==i[0]&&T.test(i[1][0])&&(t||-1==i[1][0].indexOf(j)?(e.splice(r,1),r--,n--):(t=!0,e.splice(r,1),e.unshift(["at-rule",[i[1][0].replace(T,j)]])))}}function b(e){var t=["px","em","ex","cm","mm","in","pt","pc","%"],r=["ch","rem","vh","vm","vmax","vmin","vw"];return r.forEach(function(r){e.compatibility.units[r]&&t.push(r)}),new RegExp("(^|\\s|\\(|,)0(?:"+t.join("|")+")(\\W|$)","g")}function y(e){var t={};return t.value=void 0===e.roundingPrecision?L:e.roundingPrecision,t.multiplier=Math.pow(10,t.value),t.regexp=new RegExp("(\\d*\\.\\d{"+(t.value+1)+",})px","g"),t}function w(e,t){var r=t.compatibility.selectors.ie7Hack,n=t.compatibility.selectors.adjacentSpace,i=t.compatibility.properties.spaceAfterClosingBrace,o=!1;t.unitsRegexp=b(t),t.precision=y(t);for(var a=0,s=e.length;s>a;a++){var u=e[a];switch(u[0]){case"selector":u[1]=_(u[1],!r,n),m(u[2],t);break;case"block":x(u[1],i),w(u[2],t);break;case"flat-block":x(u[1],i),m(u[2],t);break;case"at-rule":k(u[1]),o=!0}(0===u[1].length||u[2]&&0===u[2].length)&&(e.splice(a,1),a--,s--)}o&&v(e)}var _=e("./clean-up").selectors,x=e("./clean-up").block,k=e("./clean-up").atRule,O=e("../utils/split"),C=e("../colors/rgb"),S=e("../colors/hsl"),E=e("../colors/hex-name-shortener"),A=e("../properties/wrap-for-optimizing").all,R=e("../properties/restore-from-optimizing"),M=e("../properties/remove-unused"),L=2,j="@charset",T=new RegExp("^"+j,"i"),P=["100","200","300","400","500","600","700","800","900"],V=["normal","bold","bolder","lighter"],B=["bold","bolder","lighter"],U=/(?:^|\s|\()(-?\d+)px/,D=/^(\-?[\d\.]+)(m?s)$/,I={background:function(e,t,r){return 0!==t||1!=r||"none"!=e&&"transparent"!=e?e:"0 0"},"font-weight":function(e){return"normal"==e?"400":"bold"==e?"700":e},outline:function(e,t,r){return 0===t&&1==r&&"none"==e?"0":e}};t.exports=w},{"../colors/hex-name-shortener":8,"../colors/hsl":9,"../colors/rgb":10,"../properties/remove-unused":21,"../properties/restore-from-optimizing":22,"../properties/wrap-for-optimizing":27,"../utils/split":65,"./clean-up":29}],42:[function(e,t,r){function n(e,t,r){if(!r&&-1==e.indexOf("\n"))return 0===e.indexOf(u)?e:void(t.column+=e.length);for(var n=0,i=e.split("\n"),o=i.length,a=0;;){if(n==o-1)break;var s=i[n];if(/\S/.test(s))break;a+=s.length+1,n++}return t.line+=n,t.column=n>0?0:t.column,t.column+=/^(\s)*/.exec(i[n])[0].length,e.substring(a).trimLeft()}function i(e,t,r){var n=e.source||t.source;return n&&r.resolvePath?r.resolvePath(t.source,n):n}function o(e,t,r){var n={line:t.line,column:t.column,source:t.source},o=null,a=t.sourceMapTracker.isTracking(n.source)?t.sourceMapTracker.originalPositionFor(n,e,r||0):{};if(n.line=a.line||n.line,n.column=a.column||n.column,n.source=a.sourceResolved?a.source:i(a,n,t),t.sourceMapInlineSources){var s=t.sourceMapTracker.sourcesContentFor(t.source);o=s&&s[n.source]?s:t.sourceReader.sourceAt(t.source)}return o?[n.line,n.column,n.source,o]:[n.line,n.column,n.source]}function a(e,t){for(var r=e.split("\n"),n=0,i=r.length;i>n;n++){var o=r[n],a=0;for(n>0&&(t.line++,t.column=0);;){var s=o.indexOf(u,a);if(-1==s){t.column+=o.substring(a).length;break}t.column+=s-a,a+=s-a;var l=o.substring(s,o.indexOf("__",s+1)+2),c=l.substring(l.indexOf("(")+1,l.indexOf(")")).split(",");t.line+=~~c[0],t.column=(0===~~c[0]?t.column:0)+~~c[1],a+=l.length}}}function s(e,t,r,i){var s=n(e,t,r),u=r?o(s,t,i):[];return s&&a(s,t),u}var u="__ESCAPED_";t.exports=s},{}],43:[function(e,t,r){function n(e,t){for(var r=t,n=e.length;n>r;r++)if("string"!=typeof e[r])return!0;return!1}function i(e){return"background"==e[0][0]||"transform"==e[0][0]||"src"==e[0][0]}function o(e,t){return 0===e[t][0].indexOf("var(")}function a(e,t){return")"==e[t][0][e[t][0].length-1]||0===e[t][0].indexOf("__ESCAPED_URL_CLEAN_CSS")}function s(e,t){return","==e[t][0]}function u(e,t){return"/"==e[t][0]}function l(e,t){return e[t+1]&&","==e[t+1][0]}function c(e,t){return e[t+1]&&"/"==e[t+1][0]}function f(e){return"filter"==e[0][0]||"-ms-filter"==e[0][0]}function h(e,t,r){return(!r.spaceAfterClosingBrace&&i(e)||o(e,t))&&a(e,t)||c(e,t)||u(e,t)||l(e,t)||s(e,t)}function p(e,t){for(var r=t.store,n=0,i=e.length;i>n;n++)r(e[n],t),i-1>n&&r(",",t)}function d(e,t){for(var r=0,n=e.length;n>r;r++)g(e,r,r==n-1,t)}function g(e,t,r,n){var i=n.store,o=e[t];"string"==typeof o?i(o,n):o[0]==_?m(o[1],r,n):(i(o[0],n),i(":",n),v(e,t,r,n))}function m(e,t,r){var n=r.store;n(e,r),t||n(x,r)}function v(e,t,r,i){var o=i.store,a=e[t],s=0===a[0][0].indexOf("--");if(s&&b(a[1]))return o("{",i),d(a[1],i),void o("};",i);for(var u=1,l=a.length;l>u;u++)o(a[u],i),l-1>u&&(f(a)||!h(a,u,i))?o(" ",i):u==l-1&&!r&&n(e,t+1)&&o(x,i)}function b(e){for(var t=0,r=e.length;r>t;t++)if(e[t][0]==_||Array.isArray(e[t][0]))return!0;return!1}function y(e,t){for(var r=t.keepBreaks?w:"",n=t.store,i=0,o=e.length;o>i;i++){var a=e[i];switch(a[0]){case"at-rule":case"text":n(a[1][0],t),n(r,t);break;case"block":p([a[1]],t),n("{",t),y(a[2],t),n("}",t),n(r,t);break;case"flat-block":p([a[1]],t),n("{",t),d(a[2],t),n("}",t),n(r,t);break;default:p(a[1],t),n("{",t),d(a[2],t),n("}",t),n(r,t)}}}var w=e("os").EOL,_="at-rule",x=";";t.exports={all:y,body:d,property:g,selectors:p,value:v}},{os:74}],44:[function(e,t,r){function n(e,t){t.output.push("string"==typeof e?e:e[0])}function i(){return{output:[],store:n}}function o(e){var t=i();return c.all(e,t),t.output.join("")}function a(e){var t=i();return c.body(e,t),t.output.join("")}function s(e,t){var r=i();return c.property(e,t,!0,r),r.output.join("")}function u(e){var t=i();return c.selectors(e,t),t.output.join("")}function l(e,t){var r=i();return c.value(e,t,!0,r),r.output.join("")}var c=e("./helpers");t.exports={all:o,body:a,property:s,selectors:u,value:l}},{"./helpers":43}],45:[function(e,t,r){function n(e,t){t.output.push("string"==typeof e?e:e[0])}function i(e,t,r){var i={keepBreaks:t.keepBreaks,output:[],spaceAfterClosingBrace:t.compatibility.properties.spaceAfterClosingBrace,store:n};return o(e,i,!1),{styles:r(i.output.join("")).trim()}}var o=e("./helpers").all;t.exports=i},{"./helpers":43}],46:[function(e,t,r){(function(r){function n(e,t){var r="string"==typeof e,n=r?e:e[0];n.indexOf("_")>-1&&(n=t.restore(n,i(t.output))),o(n,r?null:e,t),t.output.push(n)}function i(e){for(var t=[],r=e.length-1;r>=0;r--){var n=e[r];if(t.unshift(n),"{"==n||";"==n)break}return t.join("")}function o(e,t,r){t&&a(t,r);var n=e.split("\n");r.line+=n.length-1,r.column=n.length>1?0:r.column+n.pop().length}function a(e,t){var r=e[e.length-1];if(Array.isArray(r))for(var n=0,i=r.length;i>n;n++)s(r[n],t)}function s(e,t){var r=e[2]||h;f&&(r=r.replace(/\\/g,"/")),t.outputMap.addMapping({generated:{line:t.line,column:t.column},source:r,original:{line:e[0],column:e[1]}}),e[3]&&t.outputMap.setSourceContent(r,e[3][e[2]])}function u(e,t,r,i){var o={column:0,inputMapTracker:i,keepBreaks:t.keepBreaks,line:1,output:[],outputMap:new l,restore:r,sourceMapInlineSources:t.sourceMapInlineSources,spaceAfterClosingBrace:t.compatibility.properties.spaceAfterClosingBrace,store:n};return c(e,o,!1),{sourceMap:o.outputMap,styles:o.output.join("").trim()}}var l=e("source-map").SourceMapGenerator,c=e("./helpers").all,f="win32"==r.platform,h="$stdin";t.exports=u}).call(this,e("_process"))},{"./helpers":43,_process:77,"source-map":92}],47:[function(e,t,r){function n(e,t,r,n){this.comments=new a("COMMENT"),this.specialComments=new a("COMMENT_SPECIAL"),this.context=e,this.restored=0,this.keepAll="*"==t,this.keepOne="1"==t||1===t,this.keepBreaks=r,this.saveWaypoints=n}function i(e){var t=[];return new s(e).each(function(e,r,n){t.push([n,n+e.length])}),function(e){for(var r=0,n=t.length;n>r;r++)if(t[r][0]e)return!0;return!1}}function o(e,t,r,n){for(var i=[],o=0;o0?i.join("")+t.substring(o,t.length):t}var a=e("./escape-store"),s=e("../utils/quote-scanner"),u="/*!",l="/*",c="*/",f=e("os").EOL;n.prototype.escape=function(e){for(var t,r,n,o=[],a=0,s=0,h=0,p=0,d=i(e),g=this.saveWaypoints;s0?m.substring(r+f.length).length:p+m.length),g||v){var b=g?[t,n]:null,y=v?this.specialComments.store(m,b):this.comments.store(m,b);o.push(y)}g&&(p=n+1),h=s+c.length}return o.length>0?o.join("")+e.substring(h,e.length):e},n.prototype.restore=function(e){return e=o(this,e,this.comments,!1),e=o(this,e,this.specialComments,!0)},t.exports=n},{"../utils/quote-scanner":62,"./escape-store":48,os:74}],48:[function(e,t,r){function n(e){this.placeholderRoot="ESCAPED_"+e+"_CLEAN_CSS",this.placeholderToData={},this.dataToPlaceholder={},this.count=0,this.restoreMatcher=new RegExp(this.placeholderRoot+"(\\d+)")}var i="__";n.prototype._nextPlaceholder=function(e){return{index:this.count,value:i+this.placeholderRoot+this.count++ +e+i}},n.prototype.store=function(e,t){var r=t?"("+t.join(",")+")":"",n=this.dataToPlaceholder[e]; -if(!n){var i=this._nextPlaceholder(r);n=i.value,this.placeholderToData[i.index]=e,this.dataToPlaceholder[e]=i.value}return t&&(n=n.replace(/\([^\)]+\)/,r)),n},n.prototype.nextMatch=function(e,t){var r={};return r.start=e.indexOf(this.placeholderRoot,t)-i.length,r.end=e.indexOf(i,r.start+i.length)+i.length,r.start>-1&&r.end>-1&&(r.match=e.substring(r.start,r.end)),r},n.prototype.restore=function(e){var t=this.restoreMatcher.exec(e)[1];return this.placeholderToData[t]},t.exports=n},{}],49:[function(e,t,r){function n(e,t){for(var r=t+a.length,n=0,i=!1,o=!1;;){var l=e[r++];if(i?i="'"!=l&&'"'!=l:(i="'"==l||'"'==l,l==s&&n++,l==u&&n--,l==c&&(o=!0),l!=f||o||1!=n||(r--,n--)),0===n&&l==u)break;if(!l){r=e.substring(0,r).lastIndexOf(f);break}}return r}function i(e){this.expressions=new o("EXPRESSION"),this.saveWaypoints=e}var o=e("./escape-store"),a="expression",s="(",u=")",l=a+s,c="{",f="}",h=e("os").EOL;i.prototype.escape=function(e){for(var t,r,i,o=0,a=0,s=0,u=[],c=0,f=this.saveWaypoints;a0?p.substring(r+h.length).length:c+p.length);var d=f?[t,i]:null,g=this.expressions.store(p,d);u.push(e.substring(s,o)),u.push(g),f&&(c=i+1),s=a}return u.length>0?u.join("")+e.substring(s,e.length):e},i.prototype.restore=function(e){for(var t=[],r=0;r0?t.join("")+e.substring(r,e.length):e},t.exports=i},{"./escape-store":48,os:74}],50:[function(e,t,r){function n(e){this.matches=new o("FREE_TEXT"),this.saveWaypoints=e}function i(e,t,r,n){var i=t;r&&(i=r+t.substring(0,t.indexOf("__ESCAPED_FREE_TEXT_CLEAN_CSS")),n=i.length);var o=i.lastIndexOf(";",n),a=i.lastIndexOf("{",n),s=0;s=o>-1&&a>-1?Math.max(o,a):-1==o?a:o;var u=i.substring(s+1,n);if(/\[[\w\d\-]+[\*\|\~\^\$]?=$/.test(u)&&(e=e.replace(/\\\n|\\\r\n/g,"").replace(/\n|\r\n/g,"")),/^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/.test(e)&&!/format\($/.test(u)){var l=/^(font|font\-family):/.test(u),c=/\[[\w\d\-]+[\*\|\~\^\$]?=$/.test(u),f=/@(-moz-|-o-|-webkit-)?keyframes /.test(u),h=/^(-moz-|-o-|-webkit-)?animation(-name)?:/.test(u);(l||c||f||h)&&(e=e.substring(1,e.length-1))}return e}var o=e("./escape-store"),a=e("../utils/quote-scanner"),s=e("os").EOL;n.prototype.escape=function(e){var t,r,n,i,o=this,u=this.saveWaypoints;return new a(e).each(function(e,a){u&&(t=e.split(s).length-1,r=e.lastIndexOf(s),n=r>0?e.substring(r+s.length).length:e.length,i=[t,n]);var l=o.matches.store(e,i);a.push(l)})},n.prototype.restore=function(e,t){for(var r=[],n=0;n0?r.join("")+e.substring(n,e.length):e},t.exports=n},{"../utils/quote-scanner":62,"./escape-store":48,os:74}],51:[function(e,t,r){function n(e,t,r){this.urls=new o("URL"),this.context=e,this.saveWaypoints=t,this.keepUrlQuotes=r}function i(e,t){return e=e.replace(/^url/gi,"url").replace(/\\?\n|\\?\r\n/g,"").replace(/(\s{2,}|\s)/g," ").replace(/^url\((['"])? /,"url($1").replace(/ (['"])?\)$/,"$1)"),t||/^['"].+['"]$/.test(e)||/url\(.*[\s\(\)].*\)/.test(e)||/url\(['"]data:[^;]+;charset/.test(e)||(e=e.replace(/["']/g,"")),e}var o=e("./escape-store"),a=e("../urls/reduce"),s=e("os").EOL;n.prototype.escape=function(e){var t,r,n,i=this.saveWaypoints,o=this;return a(e,this.context,function(e,a){i&&(t=e.split(s).length-1,r=e.lastIndexOf(s),n=r>0?e.substring(r+s.length).length:e.length);var u=o.urls.store(e,i?[t,n]:null);a.push(u)})},n.prototype.restore=function(e){for(var t=[],r=0;r0?t.join("")+e.substring(r,e.length):e},t.exports=n},{"../urls/reduce":56,"./escape-store":48,os:74}],52:[function(e,t,r){function n(e){return e[0]}function i(){}function o(e,t,r,n){for(var o=r?/^__ESCAPED_COMMENT_/:/__ESCAPED_COMMENT_/,a=r?n.track:i;o.test(e);){var s=e.indexOf("__"),u=e.indexOf("__",s+1)+2,l=e.substring(s,u);e=e.substring(0,s)+e.substring(u),a(l),t.push(l)}return e}function a(e,t,r){return o(e,t,!0,r)}function s(e,t,r){return o(e,t,!1,r)}function u(e,t,r){for(var n=0,i=e.length;i>n;n++)r.track(e[n]),t.push(e[n])}function l(e,t,r){var i=[],o=[],d=/[ ,\/]/;if("string"!=typeof e)return[];e.indexOf(")")>-1&&(e=e.replace(/\)([^\s_;:,\)])/g,r.sourceMap?") __ESCAPED_COMMENT_CLEAN_CSS(0,-1)__ $1":") $1")),e.indexOf("ESCAPED_URL_CLEAN_CSS")>-1&&(e=e.replace(/(ESCAPED_URL_CLEAN_CSS[^_]+?__)/g,r.sourceMap?"$1 __ESCAPED_COMMENT_CLEAN_CSS(0,-1)__ ":"$1 "));for(var g=c(e,";",!1,"{","}"),m=0,v=g.length;v>m;m++){var b=g[m],y=b.indexOf(":"),w="@"==b.trim()[0];if(w)r.track(b),i.push([p,b.trim()]);else if(-1!=y)if(b.indexOf("{")>0&&b.indexOf("{")-1&&(x=a(x,i,r)),x.indexOf("__ESCAPED_COMMENT")>-1&&(x=s(x,o,r)),_.push([x.trim()].concat(r.track(x,!0))),r.track(":"),u(o,i,r);var k=b.indexOf("{"),O=0===x.trim().indexOf("--");if(O&&k>0){var C=b.substring(y+1,k+1),S=b.substring(b.indexOf("}")),E=b.substring(k+1,b.length-S.length);r.track(C),_.push(l(E,t,r)),i.push(_),r.track(S),r.track(v-1>m?";":"")}else{var A=c(b.substring(y+1),d,!0);if(1!=A.length||""!==A[0]){for(var R=0,M=A.length;M>R;R++){var L=A[R],j=L.trim();if(0!==j.length){var T=j[j.length-1],P=j.length>1&&(T==f||T==h);if(P&&(j=j.substring(0,j.length-1)),j.indexOf("__ESCAPED_COMMENT_CLEAN_CSS(0,-")>-1)r.track(j);else if(o=[],j.indexOf("__ESCAPED_COMMENT")>-1&&(j=a(j,i,r)),j.indexOf("__ESCAPED_COMMENT")>-1&&(j=s(j,o,r)),0!==j.length){var V=_.length-1;"important"!=j||"!"!=_[V][0]?"!important"==j||"important"==j&&"!"==_[V][0][_[V][0].length-1]?(r.track(j),_[V][0]+=j):(_.push([j].concat(r.track(L,!0))),u(o,i,r),P&&(_.push([T]),r.track(T))):(r.track(j),_[V-1][0]+="!important",_.pop())}else u(o,i,r)}}v-1>m&&r.track(";"),i.push(_)}else r.warnings.push("Empty property '"+x+"' inside '"+t.filter(n).join(",")+"' selector. Ignoring.")}}else r.track(b),b.indexOf("__ESCAPED_COMMENT_SPECIAL")>-1&&i.push(b.trim())}return i}var c=e("../utils/split"),f=",",h="/",p="at-rule";t.exports=l},{"../utils/split":65}],53:[function(e,t,r){function n(e,t){for(var r,n=[],o=i(e,","),a=0,s=o.length;s>a;a++)r=t.track(o[a],!0,a),t.track(","),n.push([o[a].trim()].concat(r));return n}var i=e("../utils/split");t.exports=n},{"../utils/split":65}],54:[function(e,t,r){function n(e,t){var r=f(i(e),"}",!0,"{","}");if(0===r.length)return[];var n={chunk:r.shift(),chunks:r,column:0,cursor:0,line:1,mode:"top",resolvePath:t.options.explicitTarget?o(t.options.root,t.options.target):null,source:void 0,sourceMap:t.options.sourceMap,sourceMapInlineSources:t.options.sourceMapInlineSources,sourceMapTracker:t.inputSourceMapTracker,sourceReader:t.sourceReader,sourceTracker:t.sourceTracker,state:[],track:t.options.sourceMap?function(e,t,r){return[[c(e,n,t,r)]]}:function(){return[]},warnings:t.warnings};return s(n)}function i(e){return e.replace(/\r\n/g,"\n")}function o(e,t){var r=h.relative(e,t);return function(e,t){return e!=t?h.normalize(h.join(h.relative(r,h.dirname(e)),t)):t}}function a(e){var t,r=e.mode,n=e.chunk;if(n.length==e.cursor){if(0===e.chunks.length)return null;e.chunk=n=e.chunks.shift(),e.cursor=0}if("body"==r)return"}"==n[e.cursor]?[e.cursor,"bodyEnd"]:-1==n.indexOf("}",e.cursor)?null:(t=e.cursor+f(n.substring(e.cursor-1),"}",!0,"{","}")[0].length-2,[t,"bodyEnd"]);var i=n.indexOf("@",e.cursor),o=n.indexOf("__ESCAPED_",e.cursor),a=n.indexOf("{",e.cursor),s=n.indexOf("}",e.cursor);return o>-1&&/\S/.test(n.substring(e.cursor,o))&&(o=-1),t=i,(-1==t||o>-1&&t>o)&&(t=o),(-1==t||a>-1&&t>a)&&(t=a),(-1==t||s>-1&&t>s)&&(t=s),-1!=t?o===t?[t,"escape"]:a===t?[t,"bodyStart"]:s===t?[t,"bodyEnd"]:i===t?[t,"special"]:void 0:void 0}function s(e){for(var t,r,n=e.chunk,i=[];;){var o=a(e);if(!o){var c=e.chunk.substring(e.cursor);c.trim().length>0&&("body"==e.mode?e.warnings.push("Missing '}' after '"+c+"'. Ignoring."):i.push(["text",[c]]),e.cursor+=c.length);break}var f,h,d=o[0],g=o[1];if(n=e.chunk,e.cursor!=d&&"bodyEnd"!=g){var m=n.substring(e.cursor,d),v=/^\s+/.exec(m);v&&(e.cursor+=v[0].length,e.track(v[0]))}if("special"==g){var b=n.indexOf("{",d),y=n.indexOf(";",d),w=y>-1&&(-1==b||b>y),_=-1==b&&-1==y;if(_)e.warnings.push("Broken declaration: '"+n.substring(e.cursor)+"'."),e.cursor=n.length;else if(w)f=n.indexOf(";",d+1),r=n.substring(e.cursor,f+1),i.push(["at-rule",[r].concat(e.track(r,!0))]),e.track(";"),e.cursor=f+1;else{f=n.indexOf("{",d+1),r=n.substring(e.cursor,f);var x=r.trim(),k=p.test(x);h=e.mode,e.cursor=f+1,e.mode=k?"body":"block",t=[k?"flat-block":"block"],t.push([x].concat(e.track(r,!0))),e.track("{"),t.push(s(e)),"string"==typeof t[2]&&(t[2]=u(t[2],[[x]],e)),e.mode=h,e.track("}"),i.push(t)}}else if("escape"==g){f=n.indexOf("__",d+1);var O=n.substring(e.cursor,f+2),C=!!e.sourceTracker.nextStart(O),S=!!e.sourceTracker.nextEnd(O);if(C)e.track(O),e.state.push({source:e.source,line:e.line,column:e.column}),e.source=e.sourceTracker.nextStart(O).filename,e.line=1,e.column=0;else if(S){var E=e.state.pop();e.source=E.source,e.line=E.line,e.column=E.column,e.track(O)}else 0===O.indexOf("__ESCAPED_COMMENT_SPECIAL")&&i.push(["text",[O]]),e.track(O);e.cursor=f+2}else if("bodyStart"==g){var A=l(n.substring(e.cursor,d),e);h=e.mode,e.cursor=d+1,e.mode="body";var R=u(s(e),A,e);e.track("{"),e.mode=h,i.push(["selector",A,R])}else if("bodyEnd"==g){if("top"==e.mode){var M=e.cursor,L="}"==n[e.cursor]?"Unexpected '}' in '"+n.substring(M-20,M+20)+"'. Ignoring.":"Unexpected content: '"+n.substring(M,d+1)+"'. Ignoring.";e.warnings.push(L),e.cursor=d+1;continue}"block"==e.mode&&e.track(n.substring(e.cursor,d)),"block"!=e.mode&&(i=n.substring(e.cursor,d)),e.cursor=d+1;break}}return i}var u=e("./extract-properties"),l=e("./extract-selectors"),c=e("../source-maps/track"),f=e("../utils/split"),h=e("path"),p=/(@(font\-face|page|\-ms\-viewport|\-o\-viewport|viewport|counter\-style)|\\@.+?)/;t.exports=n},{"../source-maps/track":42,"../utils/split":65,"./extract-properties":52,"./extract-selectors":53,path:75}],55:[function(e,t,r){function n(e,t){var r={absolute:t.options.explicitRoot,relative:!t.options.explicitRoot&&t.options.explicitTarget,fromBase:t.options.relativeTo};return r.absolute||r.relative?(r.absolute&&t.options.explicitTarget&&t.warnings.push("Both 'root' and output file given so rebasing URLs as absolute paths"),r.absolute&&(r.toBase=i.resolve(t.options.root)),r.relative&&(r.toBase=i.resolve(t.options.target)),r.fromBase&&r.toBase?o(e,r,t):e):e}var i=e("path"),o=e("./rewrite");t.exports=n},{"./rewrite":57,path:75}],56:[function(e,t,r){function n(e,t,r){for(var n=0,i=0,o=0,c=0,f=!1,h=0,p=[],d=e.indexOf(s)>-1;o-1&&(n=i),'"'==e[n+a.length])o=e.indexOf('"',n+a.length+1);else if("'"==e[n+a.length])o=e.indexOf("'",n+a.length+1);else if(f=0===e.substring(n+a.length).trim().indexOf(l),o=e.indexOf(u,n),f)for(;;){if(c=e.indexOf(u,o+1),-1==c||/[\s\{\};]/.test(e.substring(o,c)))break;o=c}-1==o?(o=e.indexOf("}",n),-1==o?o=e.length:o--,t.warnings.push("Broken URL declaration: '"+e.substring(n,o+1)+"'.")):e[o]!=u&&(o=e.indexOf(u,o)),p.push(e.substring(h,n));var g=e.substring(n,o+1);r(g,p),h=o+1}return p.length>0?p.join("")+e.substring(h,e.length):e}function i(e,t,r){for(var n,i,o=0,a=0,s=0,u=0,l=0,p=[],d=0,g=0,m="'",v='"';u-1&&a>-1&&o>a&&(o=a),d=e.indexOf(m,o),g=e.indexOf(v,o),d>-1&&g>-1&&g>d)s=d,i=m;else if(d>-1&&g>-1&&d>g)s=g,i=v;else if(d>-1)s=d,i=m;else{if(!(g>-1))break;s=g,i=v}if(p.push(e.substring(l,s)),u=e.indexOf(i,s+1),n=e.substring(o,u),-1==u||/^@import\s+(url\(|__ESCAPED)/i.test(n)||h.test(n)){l=s;break}var b=e.substring(s,u+1);r(b,p),l=u+1}return p.length>0?p.join("")+e.substring(l,e.length):e}function o(e,t,r){return e=n(e,t,r),e=i(e,t,r)}var a="url(",s="URL(",u=")",l="data:",c="@import",f="@IMPORT",h=/\*\//;t.exports=o},{}],57:[function(e,t,r){(function(r){function n(e){return"/"==e[0]}function i(e){return"#"==e[0]}function o(e){return 0===e.indexOf("__ESCAPED_URL_CLEAN_CSS__")}function a(e){return/^\w+:\w+/.test(e)}function s(e){return/^[^:]+?:\/\//.test(e)||0===e.indexOf("//")}function u(e,t){return b.parse(e).protocol==b.parse(t).protocol&&b.parse(e).host==b.parse(t).host}function l(e){return e.lastIndexOf(".css")===e.length-4}function c(e){return 0===e.indexOf("data:")}function f(e,t){return v.resolve(v.join(t.fromBase||"",e)).replace(t.toBase,"")}function h(e,t){return v.relative(t.toBase,v.join(t.fromBase||"",e))}function p(e){return w?e.replace(/\\/g,"/"):e}function d(e,t){return n(e)||i(e)||o(e)||a(e)?e:t.rebase!==!1||l(e)?!t.imports&&l(e)?e:c(e)?"'"+e+"'":s(e)&&!s(t.toBase)?e:s(e)&&!u(e,t.toBase)?e:!s(e)&&s(t.toBase)?b.resolve(t.toBase,e):p(t.absolute?f(e,t):h(e,t)):e}function g(e){return e.indexOf("'")>-1?'"':e.indexOf('"')>-1?"'":/\s/.test(e)||/[\(\)]/.test(e)?"'":""}function m(e,t,r){return y(e,r,function(e,r){var n,i=e.replace(/^(url\()?\s*['"]?|['"]?\s*\)?$/g,""),o=e.match(/^(url\()?\s*(['"]).*?(['"])\s*\)?$/);n=t.urlQuotes&&o&&o[2]===o[3]?o[2]:g(i),r.push("url("+n+d(i,t)+n+")")})}var v=e("path"),b=e("url"),y=e("./reduce"),w="win32"==r.platform;t.exports=m}).call(this,e("_process"))},{"./reduce":56,_process:77,path:75,url:110}],58:[function(e,t,r){function n(e){for(var t=e.slice(0),r=0,i=t.length;i>r;r++)Array.isArray(t[r])&&(t[r]=n(t[r]));return t}t.exports=n},{}],59:[function(e,t,r){function n(e){this.source=e||{}}function i(e,t){for(var r in e){var n=e[r];"object"!=typeof n||a.isRegExp(n)?t[r]=r in t?t[r]:n:t[r]=i(n,t[r]||{})}return t}function o(e){if("object"==typeof e)return e;if(!/[,\+\-]/.test(e))return s[e]||s["*"];var t=e.split(","),r=t[0]in s?s[t.shift()]:s["*"];return e={},t.forEach(function(t){var r="+"==t[0],n=t.substring(1).split("."),i=n[0],o=n[1];e[i]=e[i]||{},e[i][o]=r}),i(r,e)}var a=e("util"),s={"*":{colors:{opacity:!0},properties:{backgroundClipMerging:!1,backgroundOriginMerging:!1,backgroundSizeMerging:!1,colors:!0,ieBangHack:!1,iePrefixHack:!1,ieSuffixHack:!0,merging:!0,shorterLengthUnits:!1,spaceAfterClosingBrace:!0,urlQuotes:!1,zeroUnits:!0},selectors:{adjacentSpace:!1,ie7Hack:!1,special:/(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:dir\([a-z-]*\)|:first(?![a-z-])|:fullscreen|:left|:read-only|:read-write|:right|:placeholder|:host|::content|\/deep\/|::shadow)/},units:{ch:!0,"in":!0,pc:!0,pt:!0,rem:!0,vh:!0,vm:!0,vmax:!0,vmin:!0,vw:!0}},ie8:{colors:{opacity:!1},properties:{backgroundClipMerging:!1,backgroundOriginMerging:!1,backgroundSizeMerging:!1,colors:!0,ieBangHack:!1,iePrefixHack:!0,ieSuffixHack:!0,merging:!1,shorterLengthUnits:!1,spaceAfterClosingBrace:!0,urlQuotes:!1,zeroUnits:!0},selectors:{adjacentSpace:!1,ie7Hack:!1,special:/(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not|:placeholder|:host|::content|\/deep\/|::shadow)/},units:{ch:!1,"in":!0,pc:!0,pt:!0,rem:!1,vh:!1,vm:!1,vmax:!1,vmin:!1,vw:!1}},ie7:{colors:{opacity:!1},properties:{backgroundClipMerging:!1,backgroundOriginMerging:!1,backgroundSizeMerging:!1,colors:!0,ieBangHack:!0,iePrefixHack:!0,ieSuffixHack:!0,merging:!1,shorterLengthUnits:!1,spaceAfterClosingBrace:!0,urlQuotes:!1,zeroUnits:!0},selectors:{adjacentSpace:!1,ie7Hack:!0,special:/(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:focus|:before|:after|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not|:placeholder|:host|::content|\/deep\/|::shadow)/},units:{ch:!1,"in":!0,pc:!0,pt:!0,rem:!1,vh:!1,vm:!1,vmax:!1,vmin:!1,vw:!1}}};n.prototype.toOptions=function(){return i(s["*"],o(this.source))},t.exports=n},{util:114}],60:[function(e,t,r){(function(r,n,i){function o(e){this.options=e.options,this.errors=e.errors,this.warnings=e.warnings,this.sourceTracker=e.sourceTracker,this.timeout=this.options.inliner.timeout,this.requestOptions=this.options.inliner.request,this.localOnly=e.localOnly,this.relativeTo=e.options.target||r.cwd(),this.maps={},this.sourcesContent={}}function a(e,t,r){return e.trackLoaded(void 0,void 0,e.options.sourceMap),r()}function s(e,t,r,n){function i(){n.cursor+=o+1,s(e,t,r,n)}for(var o=0;n.cursor-1&&(o=c.index),f.index>-1&&f.index-1&&h.index299)return n(e.statusCode);var t=[];e.on("data",function(e){t.push(e.toString())}),e.on("end",function(){r(t.join(""))})}).on("error",function(e){a||(n(e.message),a=!0)}).on("timeout",function(){a||(n("timeout"),a=!0)}).setTimeout(e.timeout)}function f(e,t,r,n,i){for(var o,a=n.length,s={line:t,column:r+a};a-- >0&&(s.column--,!(o=e.data.originalPositionFor(s))););return null===o.line&&t>1&&i>0?f(e,t-1,r,n,i-1):(e.path&&o.source&&(o.source=x.test(e.path)?y.resolve(e.path,o.source):m.join(e.path,o.source),o.sourceResolved=!0),o)}function h(e,t){var r=e.maps[t].data,n=x.test(t),i={};r.sources.forEach(function(o,a){var s=n?y.resolve(m.dirname(t),o):m.relative(e.relativeTo,m.resolve(m.dirname(t),o));i[s]=r.sourcesContent&&r.sourcesContent[a]}),e.sourcesContent[t]=i}function p(e,t,r){function n(){return p(e,t,r)}if(0===t.length)return r();var i=t.shift(),o=i[0],a=i[1],s=x.test(o);if(s&&e.localOnly)return e.warnings.push('No callback given to `#minify` method, cannot fetch a remote file from "'+a+'"'),n();if(!s){var u=m.join(e.options.root,a);return g.existsSync(u)?e.sourcesContent[o][a]=g.readFileSync(u,"utf-8"):e.warnings.push('Missing original source file at "'+u+'".'),n()}c(e,a,function(t){e.sourcesContent[o][a]=t,n()},function(t){e.warnings.push('Broken original source file at "'+a+'" - '+t),n()})}var d=e("source-map").SourceMapConsumer,g=e("fs"),m=e("path"),v=e("http"),b=e("https"),y=e("url"),w=e("../utils/object.js").override,_=/\/\*# sourceMappingURL=(\S+) \*\//,x=/^(https?:)?\/\//,k=/^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/,O=n.unescape;o.prototype.track=function(e,t){return"string"==typeof this.options.sourceMap?a(this,e,t):s(this,e,t,{files:[],cursor:0,errors:this.errors})},o.prototype.trackLoaded=function(e,t,r){var n=this.options.explicitTarget?this.options.target:this.options.root,i=x.test(e);t&&(t=i?m.dirname(t):m.dirname(m.relative(n,t))),this.maps[e]={path:t,data:new d(r)},h(this,e)},o.prototype.isTracking=function(e){return!!this.maps[e]},o.prototype.originalPositionFor=function(e,t,r){return f(this.maps[e.source],e.line,e.column,t,r)},o.prototype.sourcesContentFor=function(e){return this.sourcesContent[e]},o.prototype.resolveSources=function(e){var t=[];for(var r in this.sourcesContent){var n=this.sourcesContent[r];for(var i in n)n[i]||t.push([r,i])}return p(this,t,e)},t.exports=o}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../utils/object.js":61,_process:77,buffer:5,fs:4,http:104,https:69,path:75,"source-map":92,url:110}],61:[function(e,t,r){t.exports={override:function(e,t){var r={};for(var n in e)r[n]=e[n];for(var i in t)r[i]=t[i];return r}}},{}],62:[function(e,t,r){function n(e){this.data=e}function i(e,t,r){for(var n="\\",i=r;;){if(i=e.indexOf(t,i+1),-1==i)return-1;if(e[i-1]!=n)return i}}var o=function(e,t,r,n){var i="/*",o="*/",a="\\",s="}",u=e.substring(n,r),l=u.lastIndexOf(o,r),c=u.lastIndexOf(i,r),f=!1;if(l>=r&&c>-1&&(f=!0),r>c&&c>l&&(f=!0),f){var h=e.indexOf(o,r);return h>-1?h:(h=e.indexOf(s,r),h>-1?h-1:e.length)}for(;;){if(void 0===e[r])break;if(e[r]==t&&(e[r-1]!=a||e[r-2]==a))break;r++}return r};n.prototype.each=function(e){for(var t=this.data,r=[],n=0,a=0,s=0,u=null,l="'",c='"',f=t.length;ah?(n=h,u=l):(n=p,u=c),-1==n)break;if(a=o(t,u,n+1,s),-1==a)break;var d=t.substring(n,a+1);r.push(t.substring(s,n)),d.length>0&&e(d,r,n),s=a+1}return r.length>0?r.join("")+t.substring(s,t.length):t},t.exports=n},{}],63:[function(e,t,r){(function(r){function n(e,t){this.outerContext=e,this.data=t,this.sources={}}function i(e){var t=e.data;return e.trackSource(void 0,t),t}function o(e){var t=e.data.toString();return e.trackSource(void 0,t),t}function a(e){return e.data.map(function(t){return e.outerContext.options.processImport===!1?t+"@shallow":t}).map(function(t){return!e.outerContext.options.relativeTo||/^https?:\/\//.test(t)?t:u.relative(e.outerContext.options.relativeTo,t)}).map(function(e){return"@import url("+e+");"}).join("")}function s(e){var t=[],r=u.resolve(e.outerContext.options.target||e.outerContext.options.root);for(var n in e.data){var i=e.data[n].styles,o=e.data[n].sourceMap,a=c.test(n),s=a?n:u.resolve(n),f=u.dirname(s),h={absolute:e.outerContext.options.explicitRoot,relative:!e.outerContext.options.explicitRoot,imports:!0,rebase:e.outerContext.options.rebase,fromBase:f,toBase:a?f:r,urlQuotes:e.outerContext.options.compatibility.properties.urlQuotes};i=l(i,h,e.outerContext),e.trackSource(n,i),i=e.outerContext.sourceTracker.store(n,i),e.outerContext.options.sourceMap&&o&&e.outerContext.inputSourceMapTracker.trackLoaded(n,n,o),t.push(i)}return t.join("")}var u=e("path"),l=e("../urls/rewrite"),c=/^(https?:)?\/\//;n.prototype.sourceAt=function(e){return this.sources[e]},n.prototype.trackSource=function(e,t){this.sources[e]={},this.sources[e][e]=t},n.prototype.toString=function(){return"string"==typeof this.data?i(this):r.isBuffer(this.data)?o(this):Array.isArray(this.data)?a(this):s(this)},t.exports=n}).call(this,{isBuffer:e("../../../is-buffer/index.js")})},{"../../../is-buffer/index.js":72,"../urls/rewrite":57,path:75}],64:[function(e,t,r){function n(){this.sources=[]}n.prototype.store=function(e,t){return this.sources.push(e),"__ESCAPED_SOURCE_CLEAN_CSS"+(this.sources.length-1)+"__"+t+"__ESCAPED_SOURCE_END_CLEAN_CSS__"},n.prototype.nextStart=function(e){var t=/__ESCAPED_SOURCE_CLEAN_CSS(\d+)__/.exec(e);return t?{index:t.index,filename:this.sources[~~t[1]]}:null},n.prototype.nextEnd=function(e){return/__ESCAPED_SOURCE_END_CLEAN_CSS__/g.exec(e)},n.prototype.removeAll=function(e){return e.replace(/__ESCAPED_SOURCE_CLEAN_CSS\d+__/g,"").replace(/__ESCAPED_SOURCE_END_CLEAN_CSS__/g,"")},t.exports=n},{}],65:[function(e,t,r){function n(e,t,r,n,i){var o="string"!=typeof t,a=o?t.test(e):e.indexOf(t);if(!a)return[e];if(n=n||"(",i=i||")",-1==e.indexOf(n)&&!r)return e.split(t);for(var s=0,u=0,l=0,c=e.length,f=[];c>u;)e[u]==n?s++:e[u]==i&&s--,0===s&&u>0&&c>u+1&&(o?t.test(e[u]):e[u]==t)&&(f.push(e.substring(l,u+(r?1:0))),l=u+1),u++;if(u+1>l){var h=e.substring(l),p=h[h.length-1];!r&&(o?t.test(p):p==t)&&(h=h.substring(0,h.length-1)),f.push(h)}return f}t.exports=n},{}],66:[function(e,t,r){t.exports=e("./lib/clean")},{"./lib/clean":7}],67:[function(e,t,r){(function(e){function t(e){return Array.isArray?Array.isArray(e):"[object Array]"===m(e)}function n(e){return"boolean"==typeof e}function i(e){return null===e}function o(e){return null==e}function a(e){return"number"==typeof e}function s(e){return"string"==typeof e}function u(e){return"symbol"==typeof e}function l(e){return void 0===e}function c(e){return"[object RegExp]"===m(e)}function f(e){return"object"==typeof e&&null!==e}function h(e){return"[object Date]"===m(e)}function p(e){return"[object Error]"===m(e)||e instanceof Error}function d(e){return"function"==typeof e}function g(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function m(e){return Object.prototype.toString.call(e)}r.isArray=t,r.isBoolean=n,r.isNull=i,r.isNullOrUndefined=o,r.isNumber=a,r.isString=s,r.isSymbol=u,r.isUndefined=l,r.isRegExp=c,r.isObject=f,r.isDate=h,r.isError=p,r.isFunction=d,r.isPrimitive=g,r.isBuffer=e.isBuffer}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":72}],68:[function(e,t,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!o(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,r,n,o,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[e],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),r.apply(this,o)}else if(a(r))for(o=Array.prototype.slice.call(arguments,1),l=r.slice(),n=l.length,u=0;n>u;u++)l[u].apply(this,o);return!0},n.prototype.addListener=function(e,t){var r;if(!i(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,i(t.listener)?t.listener:t),this._events[e]?a(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,a(this._events[e])&&!this._events[e].warned&&(r=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var n=!1;return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,t){var r,n,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],o=r.length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(r)){for(s=o;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){n=s;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],i(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],69:[function(e,t,r){var n=e("http"),i=t.exports;for(var o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);i.request=function(e,t){return e||(e={}),e.scheme="https",e.protocol="https:",n.request.call(this,e,t)}},{http:104}],70:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,c=-7,f=r?i-1:0,h=r?-1:1,p=e[t+f];for(f+=h,o=p&(1<<-c)-1,p>>=-c,c+=s;c>0;o=256*o+e[t+f],f+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=n;c>0;a=256*a+e[t+f],f+=h,c-=8);if(0===o)o=1-l;else{if(o===u)return a?NaN:(p?-1:1)*(1/0);a+=Math.pow(2,n),o-=l}return(p?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,l=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+f>=1?h/u:h*Math.pow(2,1-f),t*u>=2&&(a++,u/=2),a+f>=c?(s=0,a=c):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+p]=255&s,p+=d,s/=256,i-=8);for(a=a<0;e[r+p]=255&a,p+=d,a/=256,l-=8);e[r+p-d]|=128*g}},{}],71:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],72:[function(e,t,r){t.exports=function(e){return!(null==e||!(e._isBuffer||e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)))}},{}],73:[function(e,t,r){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],74:[function(e,t,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n"},{}],75:[function(e,t,r){(function(e){function t(e,t){for(var r=0,n=e.length-1;n>=0;n--){var i=e[n];"."===i?e.splice(n,1):".."===i?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n=-1&&!i;o--){var a=o>=0?arguments[o]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(r=a+"/"+r,i="/"===a.charAt(0))}return r=t(n(r.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(e){var i=r.isAbsolute(e),o="/"===a(e,-1);return e=t(n(e.split("/"),function(e){return!!e}),!i).join("/"),e||i||(e="."),e&&o&&(e+="/"),(i?"/":"")+e},r.isAbsolute=function(e){return"/"===e.charAt(0)},r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(n(e,function(e,t){ -if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},r.relative=function(e,t){function n(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=r.resolve(e).substr(1),t=r.resolve(t).substr(1);for(var i=n(e.split("/")),o=n(t.split("/")),a=Math.min(i.length,o.length),s=a,u=0;a>u;u++)if(i[u]!==o[u]){s=u;break}for(var l=[],u=s;ut&&(t=e.length+t),e.substr(t,r)}}).call(this,e("_process"))},{_process:77}],76:[function(e,t,r){(function(e){"use strict";function r(t){for(var r=new Array(arguments.length-1),n=0;n1)for(var r=1;r1&&(n=r[0]+"@",e=r[1]),e=e.replace(T,".");var i=e.split("."),o=a(i,t).join(".");return n+o}function u(e){for(var t,r,n=[],i=0,o=e.length;o>i;)t=e.charCodeAt(i++),t>=55296&&56319>=t&&o>i?(r=e.charCodeAt(i++),56320==(64512&r)?n.push(((1023&t)<<10)+(1023&r)+65536):(n.push(t),i--)):n.push(t);return n}function l(e){return a(e,function(e){var t="";return e>65535&&(e-=65536,t+=U(e>>>10&1023|55296),e=56320|1023&e),t+=U(e)}).join("")}function c(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:k}function f(e,t){return e+22+75*(26>e)-((0!=t)<<5)}function h(e,t,r){var n=0;for(e=r?B(e/E):e>>1,e+=B(e/t);e>V*C>>1;n+=k)e=B(e/V);return B(n+(V+1)*e/(e+S))}function p(e){var t,r,n,i,a,s,u,f,p,d,g=[],m=e.length,v=0,b=R,y=A;for(r=e.lastIndexOf(M),0>r&&(r=0),n=0;r>n;++n)e.charCodeAt(n)>=128&&o("not-basic"),g.push(e.charCodeAt(n));for(i=r>0?r+1:0;m>i;){for(a=v,s=1,u=k;i>=m&&o("invalid-input"),f=c(e.charCodeAt(i++)),(f>=k||f>B((x-v)/s))&&o("overflow"),v+=f*s,p=y>=u?O:u>=y+C?C:u-y,!(p>f);u+=k)d=k-p,s>B(x/d)&&o("overflow"),s*=d;t=g.length+1,y=h(v-a,t,0==a),B(v/t)>x-b&&o("overflow"),b+=B(v/t),v%=t,g.splice(v++,0,b)}return l(g)}function d(e){var t,r,n,i,a,s,l,c,p,d,g,m,v,b,y,w=[];for(e=u(e),m=e.length,t=R,r=0,a=A,s=0;m>s;++s)g=e[s],128>g&&w.push(U(g));for(n=i=w.length,i&&w.push(M);m>n;){for(l=x,s=0;m>s;++s)g=e[s],g>=t&&l>g&&(l=g);for(v=n+1,l-t>B((x-r)/v)&&o("overflow"),r+=(l-t)*v,t=l,s=0;m>s;++s)if(g=e[s],t>g&&++r>x&&o("overflow"),g==t){for(c=r,p=k;d=a>=p?O:p>=a+C?C:p-a,!(d>c);p+=k)y=c-d,b=k-d,w.push(U(f(d+y%b,0))),c=B(y/b);w.push(U(f(c,0))),a=h(r,v,n==i),r=0,++n}++r,++t}return w.join("")}function g(e){return s(e,function(e){return L.test(e)?p(e.slice(4).toLowerCase()):e})}function m(e){return s(e,function(e){return j.test(e)?"xn--"+d(e):e})}var v="object"==typeof n&&n&&!n.nodeType&&n,b="object"==typeof r&&r&&!r.nodeType&&r,y="object"==typeof t&&t;y.global!==y&&y.window!==y&&y.self!==y||(i=y);var w,_,x=2147483647,k=36,O=1,C=26,S=38,E=700,A=72,R=128,M="-",L=/^xn--/,j=/[^\x20-\x7E]/,T=/[\x2E\u3002\uFF0E\uFF61]/g,P={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},V=k-O,B=Math.floor,U=String.fromCharCode;if(w={version:"1.3.2",ucs2:{decode:u,encode:l},decode:p,encode:d,toASCII:m,toUnicode:g},"function"==typeof e&&"object"==typeof e.amd&&e.amd)e("punycode",function(){return w});else if(v&&b)if(r.exports==v)b.exports=w;else for(_ in w)w.hasOwnProperty(_)&&(v[_]=w[_]);else i.punycode=w}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,o){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var l=e.length;u>0&&l>u&&(l=u);for(var c=0;l>c;++c){var f,h,p,d,g=e[c].replace(s,"%20"),m=g.indexOf(r);m>=0?(f=g.substr(0,m),h=g.substr(m+1)):(f=g,h=""),p=decodeURIComponent(f),d=decodeURIComponent(h),n(a,p)?i(a[p])?a[p].push(d):a[p]=[a[p],d]:a[p]=d}return a};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],80:[function(e,t,r){"use strict";function n(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||n||(r=t.decoder.write(r),u=!t.objectMode&&0===r.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&f(e))),p(e,t)}else i||(t.reading=!1);return a(t)}function a(e){return!e.ended&&(e.needReadable||e.length=V?e=V:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u(e,t){return 0===t.length&&t.ended?0:t.objectMode?0===e?0:1:null===e||isNaN(e)?t.flowing&&t.buffer.length?t.buffer[0].length:t.length:0>=e?0:(e>t.highWaterMark&&(t.highWaterMark=s(e)),e>t.length?t.ended?t.length:(t.needReadable=!0,0):e)}function l(e,t){var r=null;return E.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function c(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,f(e)}}function f(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(j("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?C(h,e):h(e))}function h(e){j("emit readable"),e.emit("readable"),y(e)}function p(e,t){t.readingMore||(t.readingMore=!0,C(d,e,t))}function d(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=i)r=o?n.join(""):1===n.length?n[0]:E.concat(n,i),n.length=0;else if(el&&e>u;l++){var s=n[0],f=Math.min(e-u,s.length);o?r+=s.slice(0,f):s.copy(r,u,0,f),f0)throw new Error("endReadable called on non-empty stream");t.endEmitted||(t.ended=!0,C(x,t,e))}function x(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function k(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r],r)}function O(e,t){for(var r=0,n=e.length;n>r;r++)if(e[r]===t)return r;return-1}t.exports=i;var C=e("process-nextick-args"),S=e("isarray"),E=e("buffer").Buffer;i.ReadableState=n;var A,R=(e("events"),function(e,t){return e.listeners(t).length});!function(){try{A=e("stream")}catch(t){}finally{A||(A=e("events").EventEmitter)}}();var E=e("buffer").Buffer,M=e("core-util-is");M.inherits=e("inherits");var L=e("util"),j=void 0;j=L&&L.debuglog?L.debuglog("stream"):function(){};var T;M.inherits(i,A);var P,P;i.prototype.push=function(e,t){var r=this._readableState;return r.objectMode||"string"!=typeof e||(t=t||r.defaultEncoding,t!==r.encoding&&(e=new E(e,t),t="")),o(this,r,e,t,!1)},i.prototype.unshift=function(e){var t=this._readableState;return o(this,t,e,"",!0)},i.prototype.isPaused=function(){return this._readableState.flowing===!1},i.prototype.setEncoding=function(t){return T||(T=e("string_decoder/").StringDecoder),this._readableState.decoder=new T(t),this._readableState.encoding=t,this};var V=8388608;i.prototype.read=function(e){j("read",e);var t=this._readableState,r=e;if(("number"!=typeof e||e>0)&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return j("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?_(this):f(this),null;if(e=u(e,t),0===e&&t.ended)return 0===t.length&&_(this),null;var n=t.needReadable;j("need readable",n),(0===t.length||t.length-e0?w(e,t):null,null===i&&(t.needReadable=!0,e=0),t.length-=e,0!==t.length||t.ended||(t.needReadable=!0),r!==e&&t.ended&&0===t.length&&_(this),null!==i&&this.emit("data",i),i},i.prototype._read=function(e){this.emit("error",new Error("not implemented"))},i.prototype.pipe=function(e,t){function n(e){j("onunpipe"),e===f&&o()}function i(){j("onend"),e.end()}function o(){j("cleanup"),e.removeListener("close",u),e.removeListener("finish",l),e.removeListener("drain",m),e.removeListener("error",s),e.removeListener("unpipe",n),f.removeListener("end",i),f.removeListener("end",o),f.removeListener("data",a),v=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||m()}function a(t){j("ondata");var r=e.write(t);!1===r&&(1!==h.pipesCount||h.pipes[0]!==e||1!==f.listenerCount("data")||v||(j("false write response, pause",f._readableState.awaitDrain),f._readableState.awaitDrain++),f.pause())}function s(t){j("onerror",t),c(),e.removeListener("error",s),0===R(e,"error")&&e.emit("error",t)}function u(){e.removeListener("finish",l),c()}function l(){j("onfinish"),e.removeListener("close",u),c()}function c(){j("unpipe"),f.unpipe(e)}var f=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,j("pipe count=%d opts=%j",h.pipesCount,t);var p=(!t||t.end!==!1)&&e!==r.stdout&&e!==r.stderr,d=p?i:o;h.endEmitted?C(d):f.once("end",d),e.on("unpipe",n);var m=g(f);e.on("drain",m);var v=!1;return f.on("data",a),e._events&&e._events.error?S(e._events.error)?e._events.error.unshift(s):e._events.error=[s,e._events.error]:e.on("error",s),e.once("close",u),e.once("finish",l),e.emit("pipe",f),h.flowing||(j("pipe resume"),f.resume()),e},i.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;n>i;i++)r[i].emit("unpipe",this);return this}var o=O(t.pipes,e);return-1===o?this:(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this),this)},i.prototype.on=function(e,t){var r=A.prototype.on.call(this,e,t);if("data"===e&&!1!==this._readableState.flowing&&this.resume(),"readable"===e&&!this._readableState.endEmitted){var n=this._readableState;n.readableListening||(n.readableListening=!0,n.emittedReadable=!1,n.needReadable=!0,n.reading?n.length&&f(this,n):C(m,this))}return r},i.prototype.addListener=i.prototype.on,i.prototype.resume=function(){var e=this._readableState;return e.flowing||(j("resume"),e.flowing=!0,v(this,e)),this},i.prototype.pause=function(){return j("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(j("pause"),this._readableState.flowing=!1,this.emit("pause")),this},i.prototype.wrap=function(e){var t=this._readableState,r=!1,n=this;e.on("end",function(){if(j("wrapped end"),t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&n.push(e)}n.push(null)}),e.on("data",function(i){if(j("wrapped data"),t.decoder&&(i=t.decoder.write(i)),(!t.objectMode||null!==i&&void 0!==i)&&(t.objectMode||i&&i.length)){var o=n.push(i);o||(r=!0,e.pause())}});for(var i in e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));var o=["error","close","destroy","pause","resume"];return k(o,function(t){e.on(t,n.emit.bind(n,t))}),n._read=function(t){j("wrapped _read",t),r&&(r=!1,e.resume())},n},i._fromList=w}).call(this,e("_process"))},{"./_stream_duplex":83,_process:77,buffer:5,"core-util-is":67,events:68,inherits:71,isarray:73,"process-nextick-args":76,"string_decoder/":108,util:3}],86:[function(e,t,r){"use strict";function n(e){this.afterTransform=function(t,r){return i(e,t,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function i(e,t,r){var n=e._transformState;n.transforming=!1;var i=n.writecb;if(!i)return e.emit("error",new Error("no writecb in Transform class"));n.writechunk=null,n.writecb=null,null!==r&&void 0!==r&&e.push(r),i(t);var o=e._readableState;o.reading=!1,(o.needReadable||o.length-1?setImmediate:k,C=e("buffer").Buffer;a.WritableState=o;var S=e("core-util-is");S.inherits=e("inherits");var E,A={deprecate:e("util-deprecate")};!function(){try{E=e("stream")}catch(t){}finally{E||(E=e("events").EventEmitter)}}();var C=e("buffer").Buffer;S.inherits(a,E);var R;o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:A.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var R;a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},a.prototype.write=function(e,t,r){var i=this._writableState,o=!1;return"function"==typeof t&&(r=t,t=null),C.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=n),i.ended?s(this,r):u(this,i,e,r)&&(i.pendingcb++,o=c(this,i,e,t,r)),o},a.prototype.cork=function(){var e=this._writableState;e.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||v(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e},a.prototype._write=function(e,t,r){r(new Error("not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||_(this,n,r)}}).call(this,e("_process"))},{"./_stream_duplex":83,_process:77,buffer:5,"core-util-is":67,events:68,inherits:71,"process-nextick-args":76,"util-deprecate":112}],88:[function(e,t,r){t.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":84}],89:[function(e,t,r){var n=function(){try{return e("stream")}catch(t){}}();r=t.exports=e("./lib/_stream_readable.js"),r.Stream=n||r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":83,"./lib/_stream_passthrough.js":84,"./lib/_stream_readable.js":85,"./lib/_stream_transform.js":86,"./lib/_stream_writable.js":87}],90:[function(e,t,r){t.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":86}],91:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":87}],92:[function(e,t,r){r.SourceMapGenerator=e("./source-map/source-map-generator").SourceMapGenerator,r.SourceMapConsumer=e("./source-map/source-map-consumer").SourceMapConsumer,r.SourceNode=e("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":99,"./source-map/source-map-generator":100,"./source-map/source-node":101}],93:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(){this._array=[],this._set={}}var i=e("./util");n.fromArray=function(e,t){for(var r=new n,i=0,o=e.length;o>i;i++)r.add(e[i],t);return r},n.prototype.size=function(){return Object.getOwnPropertyNames(this._set).length},n.prototype.add=function(e,t){var r=this.has(e),n=this._array.length;r&&!t||this._array.push(e),r||(this._set[i.toSetString(e)]=n)},n.prototype.has=function(e){return Object.prototype.hasOwnProperty.call(this._set,i.toSetString(e))},n.prototype.indexOf=function(e){if(this.has(e))return this._set[i.toSetString(e)];throw new Error('"'+e+'" is not in the set.')},n.prototype.at=function(e){if(e>=0&&ee?(-e<<1)+1:(e<<1)+0}function i(e){var t=1===(1&e),r=e>>1;return t?-r:r}var o=e("./base64"),a=5,s=1<>>=a,i>0&&(t|=l),r+=o.encode(t);while(i>0);return r},t.decode=function(e,t,r){var n,s,c=e.length,f=0,h=0;do{if(t>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(s=o.decode(e.charCodeAt(t++)),-1===s)throw new Error("Invalid base64 digit: "+e.charAt(t-1));n=!!(s&l),s&=u,f+=s<=0&&e=t&&r>=e?e-t:e>=n&&i>=e?e-n+l:e>=o&&a>=e?e-o+c:e==s?62:e==u?63:-1}})},{amdefine:1}],96:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(e,r,i,o,a,s){var u=Math.floor((r-e)/2)+e,l=a(i,o[u],!0);return 0===l?u:l>0?r-u>1?n(u,r,i,o,a,s):s==t.LEAST_UPPER_BOUND?r1?n(e,u,i,o,a,s):s==t.LEAST_UPPER_BOUND?u:0>e?-1:e}t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2,t.search=function(e,r,i,o){if(0===r.length)return-1;var a=n(-1,r.length,e,r,i,o||t.GREATEST_LOWER_BOUND);if(0>a)return-1;for(;a-1>=0&&0===i(r[a],r[a-1],!0);)--a;return a}})},{amdefine:1}],97:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(e,t){var r=e.generatedLine,n=t.generatedLine,i=e.generatedColumn,a=t.generatedColumn;return n>r||n==r&&a>=i||o.compareByGeneratedPositionsInflated(e,t)<=0}function i(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var o=e("./util");i.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},i.prototype.add=function(e){n(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},i.prototype.toArray=function(){return this._sorted||(this._array.sort(o.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},t.MappingList=i})},{"./util":102,amdefine:1}],98:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function i(e,t){return Math.round(e+Math.random()*(t-e))}function o(e,t,r,a){if(a>r){var s=i(r,a),u=r-1;n(e,s,a);for(var l=e[a],c=r;a>c;c++)t(e[c],l)<=0&&(u+=1,n(e,u,c));n(e,u+1,c);var f=u+1;o(e,t,r,f-1),o(e,t,f+1,a)}}t.quickSort=function(e,t){o(e,t,0,e.length-1)}})},{amdefine:1}],99:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(e){var t=e;return"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=t.sections?new a(t):new i(t)}function i(e){var t=e;"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=s.getArg(t,"version"),n=s.getArg(t,"sources"),i=s.getArg(t,"names",[]),o=s.getArg(t,"sourceRoot",null),a=s.getArg(t,"sourcesContent",null),u=s.getArg(t,"mappings"),c=s.getArg(t,"file",null);if(r!=this._version)throw new Error("Unsupported version: "+r);n=n.map(s.normalize),this._names=l.fromArray(i,!0),this._sources=l.fromArray(n,!0),this.sourceRoot=o,this.sourcesContent=a,this._mappings=u,this.file=c}function o(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function a(e){var t=e;"string"==typeof e&&(t=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=s.getArg(t,"version"),i=s.getArg(t,"sections");if(r!=this._version)throw new Error("Unsupported version: "+r);this._sources=new l,this._names=new l;var o={line:-1,column:0};this._sections=i.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var t=s.getArg(e,"offset"),r=s.getArg(t,"line"),i=s.getArg(t,"column");if(r=0){var o=this._originalMappings[i];if(void 0===e.column)for(var a=o.originalLine;o&&o.originalLine===a;)n.push({line:s.getArg(o,"generatedLine",null),column:s.getArg(o,"generatedColumn",null),lastColumn:s.getArg(o,"lastGeneratedColumn",null)}),o=this._originalMappings[++i];else for(var l=o.originalColumn;o&&o.originalLine===t&&o.originalColumn==l;)n.push({line:s.getArg(o,"generatedLine",null),column:s.getArg(o,"generatedColumn",null),lastColumn:s.getArg(o,"lastGeneratedColumn",null)}),o=this._originalMappings[++i]}return n},t.SourceMapConsumer=n,i.prototype=Object.create(n.prototype),i.prototype.consumer=n,i.fromSourceMap=function(e){var t=Object.create(i.prototype),r=t._names=l.fromArray(e._names.toArray(),!0),n=t._sources=l.fromArray(e._sources.toArray(),!0);t.sourceRoot=e._sourceRoot,t.sourcesContent=e._generateSourcesContent(t._sources.toArray(),t.sourceRoot),t.file=e._file;for(var a=e._mappings.toArray().slice(),u=t.__generatedMappings=[],c=t.__originalMappings=[],h=0,p=a.length;p>h;h++){var d=a[h],g=new o;g.generatedLine=d.generatedLine,g.generatedColumn=d.generatedColumn,d.source&&(g.source=n.indexOf(d.source),g.originalLine=d.originalLine,g.originalColumn=d.originalColumn,d.name&&(g.name=r.indexOf(d.name)),c.push(g)),u.push(g)}return f(t.__originalMappings,s.compareByOriginalPositions),t},i.prototype._version=3,Object.defineProperty(i.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?s.join(this.sourceRoot,e):e},this)}}),i.prototype._parseMappings=function(e,t){for(var r,n,i,a,u,l=1,h=0,p=0,d=0,g=0,m=0,v=e.length,b=0,y={},w={},_=[],x=[];v>b;)if(";"===e.charAt(b))l++,b++,h=0;else if(","===e.charAt(b))b++;else{for(r=new o,r.generatedLine=l,a=b;v>a&&!this._charIsMappingSeparator(e,a);a++);if(n=e.slice(b,a),i=y[n])b+=n.length;else{for(i=[];a>b;)c.decode(e,b,w),u=w.value,b=w.rest,i.push(u);if(2===i.length)throw new Error("Found a source, but no line and column");if(3===i.length)throw new Error("Found a source and line, but no column");y[n]=i}r.generatedColumn=h+i[0],h=r.generatedColumn,i.length>1&&(r.source=g+i[1],g+=i[1],r.originalLine=p+i[2],p=r.originalLine,r.originalLine+=1,r.originalColumn=d+i[3],d=r.originalColumn,i.length>4&&(r.name=m+i[4],m+=i[4])),x.push(r),"number"==typeof r.originalLine&&_.push(r)}f(x,s.compareByGeneratedPositionsDeflated),this.__generatedMappings=x,f(_,s.compareByOriginalPositions),this.__originalMappings=_},i.prototype._findMapping=function(e,t,r,n,i,o){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[n]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[n]);return u.search(e,t,i,o)},i.prototype.computeColumnSpans=function(){for(var e=0;e=0){var i=this._generatedMappings[r];if(i.generatedLine===t.generatedLine){var o=s.getArg(i,"source",null);null!==o&&(o=this._sources.at(o),null!=this.sourceRoot&&(o=s.join(this.sourceRoot,o)));var a=s.getArg(i,"name",null);return null!==a&&(a=this._names.at(a)),{source:o,line:s.getArg(i,"originalLine",null),column:s.getArg(i,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}},i.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}):!1},i.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=s.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var r;if(null!=this.sourceRoot&&(r=s.urlParse(this.sourceRoot))){var n=e.replace(/^file:\/\//,"");if("file"==r.scheme&&this._sources.has(n))return this.sourcesContent[this._sources.indexOf(n)];if((!r.path||"/"==r.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},i.prototype.generatedPositionFor=function(e){var t=s.getArg(e,"source");if(null!=this.sourceRoot&&(t=s.relative(this.sourceRoot,t)),!this._sources.has(t))return{line:null,column:null,lastColumn:null};t=this._sources.indexOf(t);var r={source:t,originalLine:s.getArg(e,"line"),originalColumn:s.getArg(e,"column")},i=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",s.compareByOriginalPositions,s.getArg(e,"bias",n.GREATEST_LOWER_BOUND));if(i>=0){var o=this._originalMappings[i];if(o.source===r.source)return{line:s.getArg(o,"generatedLine",null),column:s.getArg(o,"generatedColumn",null),lastColumn:s.getArg(o,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},t.BasicSourceMapConsumer=i,a.prototype=Object.create(n.prototype),a.prototype.constructor=n,a.prototype._version=3,Object.defineProperty(a.prototype,"sources",{get:function(){for(var e=[],t=0;t0&&e.column>=0)||t||r||n)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:n}))},n.prototype._serializeMappings=function(){for(var e,t=0,r=1,n=0,a=0,s=0,u=0,l="",c=this._mappings.toArray(),f=0,h=c.length;h>f;f++){if(e=c[f],e.generatedLine!==r)for(t=0;e.generatedLine!==r;)l+=";",r++;else if(f>0){if(!o.compareByGeneratedPositionsInflated(e,c[f-1]))continue;l+=","}l+=i.encode(e.generatedColumn-t),t=e.generatedColumn,null!=e.source&&(l+=i.encode(this._sources.indexOf(e.source)-u),u=this._sources.indexOf(e.source),l+=i.encode(e.originalLine-1-a),a=e.originalLine-1,l+=i.encode(e.originalColumn-n),n=e.originalColumn,null!=e.name&&(l+=i.encode(this._names.indexOf(e.name)-s),s=this._names.indexOf(e.name)))}return l},n.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=o.relative(t,e));var r=o.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},n.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},n.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=n})},{"./array-set":93,"./base64-vlq":94,"./mapping-list":97,"./util":102,amdefine:1}],101:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(e,t,r,n,i){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==t?null:t,this.source=null==r?null:r,this.name=null==i?null:i,this[u]=!0,null!=n&&this.add(n)}var i=e("./source-map-generator").SourceMapGenerator,o=e("./util"),a=/(\r?\n)/,s=10,u="$$$isSourceNode$$$";n.fromStringWithSourceMap=function(e,t,r){function i(e,t){if(null===e||void 0===e.source)s.add(t);else{var i=r?o.join(r,e.source):e.source;s.add(new n(e.originalLine,e.originalColumn,i,t,e.name))}}var s=new n,u=e.split(a),l=function(){var e=u.shift(),t=u.shift()||"";return e+t},c=1,f=0,h=null;return t.eachMapping(function(e){if(null!==h){if(!(c0&&(h&&i(h,l()),s.add(u.join(""))),t.sources.forEach(function(e){var n=t.sourceContentFor(e);null!=n&&(null!=r&&(e=o.join(r,e)),s.setSourceContent(e,n))}),s},n.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},n.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},n.prototype.walk=function(e){for(var t,r=0,n=this.children.length;n>r;r++)t=this.children[r],t[u]?t.walk(e):""!==t&&e(t,{source:this.source,line:this.line,column:this.column,name:this.name})},n.prototype.join=function(e){var t,r,n=this.children.length;if(n>0){for(t=[],r=0;n-1>r;r++)t.push(this.children[r]),t.push(e);t.push(this.children[r]),this.children=t}return this},n.prototype.replaceRight=function(e,t){var r=this.children[this.children.length-1];return r[u]?r.replaceRight(e,t):"string"==typeof r?this.children[this.children.length-1]=r.replace(e,t):this.children.push("".replace(e,t)),this},n.prototype.setSourceContent=function(e,t){this.sourceContents[o.toSetString(e)]=t},n.prototype.walkSourceContents=function(e){for(var t=0,r=this.children.length;r>t;t++)this.children[t][u]&&this.children[t].walkSourceContents(e);for(var n=Object.keys(this.sourceContents),t=0,r=n.length;r>t;t++)e(o.fromSetString(n[t]),this.sourceContents[n[t]])},n.prototype.toString=function(){var e="";return this.walk(function(t){e+=t}),e},n.prototype.toStringWithSourceMap=function(e){var t={code:"",line:1,column:0},r=new i(e),n=!1,o=null,a=null,u=null,l=null;return this.walk(function(e,i){t.code+=e,null!==i.source&&null!==i.line&&null!==i.column?(o===i.source&&a===i.line&&u===i.column&&l===i.name||r.addMapping({source:i.source,original:{line:i.line,column:i.column},generated:{line:t.line,column:t.column},name:i.name}),o=i.source,a=i.line,u=i.column,l=i.name,n=!0):n&&(r.addMapping({generated:{line:t.line,column:t.column}}),o=null,n=!1);for(var c=0,f=e.length;f>c;c++)e.charCodeAt(c)===s?(t.line++,t.column=0,c+1===f?(o=null,n=!1):n&&r.addMapping({source:i.source,original:{line:i.line,column:i.column},generated:{line:t.line,column:t.column},name:i.name})):t.column++}),this.walkSourceContents(function(e,t){r.setSourceContent(e,t)}),{code:t.code,map:r}},t.SourceNode=n})},{"./source-map-generator":100,"./util":102,amdefine:1}],102:[function(e,t,r){if("function"!=typeof n)var n=e("amdefine")(t,e);n(function(e,t,r){function n(e,t,r){if(t in e)return e[t];if(3===arguments.length)return r;throw new Error('"'+t+'" is a required argument.')}function i(e){var t=e.match(g);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}function o(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}function a(e){var t=e,r=i(e);if(r){if(!r.path)return e;t=r.path}for(var n,a="/"===t.charAt(0),s=t.split(/\/+/),u=0,l=s.length-1;l>=0;l--)n=s[l],"."===n?s.splice(l,1):".."===n?u++:u>0&&(""===n?(s.splice(l+1,u),u=0):(s.splice(l,2),u--));return t=s.join("/"),""===t&&(t=a?"/":"."),r?(r.path=t,o(r)):t}function s(e,t){""===e&&(e="."),""===t&&(t=".");var r=i(t),n=i(e);if(n&&(e=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),o(r);if(r||t.match(m))return t;if(n&&!n.host&&!n.path)return n.host=t,o(n);var s="/"===t.charAt(0)?t:a(e.replace(/\/+$/,"")+"/"+t);return n?(n.path=s,o(n)):s}function u(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==t.indexOf(e+"/");){var n=e.lastIndexOf("/");if(0>n)return t;if(e=e.slice(0,n),e.match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)}function l(e){return"$"+e}function c(e){return e.substr(1)}function f(e,t,r){var n=e.source-t.source;return 0!==n?n:(n=e.originalLine-t.originalLine,0!==n?n:(n=e.originalColumn-t.originalColumn,0!==n||r?n:(n=e.generatedColumn-t.generatedColumn,0!==n?n:(n=e.generatedLine-t.generatedLine,0!==n?n:e.name-t.name))))}function h(e,t,r){var n=e.generatedLine-t.generatedLine;return 0!==n?n:(n=e.generatedColumn-t.generatedColumn,0!==n||r?n:(n=e.source-t.source,0!==n?n:(n=e.originalLine-t.originalLine,0!==n?n:(n=e.originalColumn-t.originalColumn,0!==n?n:e.name-t.name))))}function p(e,t){return e===t?0:e>t?1:-1}function d(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r?r:(r=e.generatedColumn-t.generatedColumn,0!==r?r:(r=p(e.source,t.source),0!==r?r:(r=e.originalLine-t.originalLine,0!==r?r:(r=e.originalColumn-t.originalColumn,0!==r?r:p(e.name,t.name)))))}t.getArg=n;var g=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,m=/^data:.+\,.+$/;t.urlParse=i,t.urlGenerate=o,t.normalize=a,t.join=s,t.relative=u,t.toSetString=l,t.fromSetString=c,t.compareByOriginalPositions=f,t.compareByGeneratedPositionsDeflated=h,t.compareByGeneratedPositionsInflated=d})},{amdefine:1}],103:[function(e,t,r){function n(){i.call(this)}t.exports=n;var i=e("events").EventEmitter,o=e("inherits");o(n,i),n.Readable=e("readable-stream/readable.js"),n.Writable=e("readable-stream/writable.js"),n.Duplex=e("readable-stream/duplex.js"),n.Transform=e("readable-stream/transform.js"),n.PassThrough=e("readable-stream/passthrough.js"),n.Stream=n,n.prototype.pipe=function(e,t){function r(t){e.writable&&!1===e.write(t)&&l.pause&&l.pause()}function n(){l.readable&&l.resume&&l.resume()}function o(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function s(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){l.removeListener("data",r),e.removeListener("drain",n),l.removeListener("end",o),l.removeListener("close",a),l.removeListener("error",s),e.removeListener("error",s),l.removeListener("end",u),l.removeListener("close",u),e.removeListener("close",u)}var l=this;l.on("data",r),e.on("drain",n),e._isStdio||t&&t.end===!1||(l.on("end",o),l.on("close",a));var c=!1;return l.on("error",s),e.on("error",s),l.on("end",u),l.on("close",u),e.on("close",u),e.emit("pipe",l),e}},{events:68,inherits:71,"readable-stream/duplex.js":82,"readable-stream/passthrough.js":88,"readable-stream/readable.js":89,"readable-stream/transform.js":90,"readable-stream/writable.js":91}],104:[function(e,t,r){(function(t){var n=e("./lib/request"),i=e("xtend"),o=e("builtin-status-codes"),a=e("url"),s=r;s.request=function(e,r){e="string"==typeof e?a.parse(e):i(e);var o=-1===t.location.protocol.search(/^https?:$/)?"http:":"",s=e.protocol||o,u=e.hostname||e.host,l=e.port,c=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?s+"//"+u:"")+(l?":"+l:"")+c,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var f=new n(e);return r&&f.on("response",r),f},s.get=function(e,t){var r=s.request(e,t);return r.end(),r},s.Agent=function(){},s.Agent.defaultMaxSockets=4,s.STATUS_CODES=o,s.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":106,"builtin-status-codes":6,url:110,xtend:115}],105:[function(e,t,r){(function(e){function t(e){try{return o.responseType=e,o.responseType===e}catch(t){}return!1}function n(e){return"function"==typeof e}r.fetch=n(e.fetch)&&n(e.ReadableByteStream),r.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),r.blobConstructor=!0}catch(i){}var o=new e.XMLHttpRequest;o.open("GET",e.location.host?"/":"https://example.com");var a="undefined"!=typeof e.ArrayBuffer,s=a&&n(e.ArrayBuffer.prototype.slice);r.arraybuffer=a&&t("arraybuffer"),r.msstream=!r.fetch&&s&&t("ms-stream"),r.mozchunkedarraybuffer=!r.fetch&&a&&t("moz-chunked-arraybuffer"),r.overrideMimeType=n(o.overrideMimeType),r.vbArray=n(e.VBArray),o=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],106:[function(e,t,r){(function(r,n,i){function o(e){return s.fetch?"fetch":s.mozchunkedarraybuffer?"moz-chunked-arraybuffer":s.msstream?"ms-stream":s.arraybuffer&&e?"arraybuffer":s.vbArray&&e?"text:vbarray":"text"}function a(e){try{var t=e.status;return null!==t&&0!==t}catch(r){return!1}}var s=e("./capability"),u=e("inherits"),l=e("./response"),c=e("stream"),f=e("to-arraybuffer"),h=l.IncomingMessage,p=l.readyStates,d=t.exports=function(e){var t=this;c.Writable.call(t),t._opts=e,t._body=[],t._headers={},e.auth&&t.setHeader("Authorization","Basic "+new i(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(r){t.setHeader(r,e.headers[r])});var r;if("prefer-streaming"===e.mode)r=!1;else if("allow-wrong-content-type"===e.mode)r=!s.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");r=!0}t._mode=o(r),t.on("finish",function(){t._onFinish()})};u(d,c.Writable),d.prototype.setHeader=function(e,t){var r=this,n=e.toLowerCase();-1===g.indexOf(n)&&(r._headers[n]={name:e,value:t})},d.prototype.getHeader=function(e){var t=this;return t._headers[e.toLowerCase()].value},d.prototype.removeHeader=function(e){var t=this;delete t._headers[e.toLowerCase()]},d.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t,o=e._opts,a=e._headers;if("POST"!==o.method&&"PUT"!==o.method&&"PATCH"!==o.method||(t=s.blobConstructor?new n.Blob(e._body.map(function(e){return f(e)}),{type:(a["content-type"]||{}).value||""}):i.concat(e._body).toString()),"fetch"===e._mode){var u=Object.keys(a).map(function(e){return[a[e].name,a[e].value]});n.fetch(e._opts.url,{method:e._opts.method,headers:u,body:t,mode:"cors",credentials:o.withCredentials?"include":"same-origin"}).then(function(t){e._fetchResponse=t,e._connect()},function(t){e.emit("error",t)})}else{var l=e._xhr=new n.XMLHttpRequest;try{l.open(e._opts.method,e._opts.url,!0)}catch(c){return void r.nextTick(function(){e.emit("error",c)})}"responseType"in l&&(l.responseType=e._mode.split(":")[0]),"withCredentials"in l&&(l.withCredentials=!!o.withCredentials),"text"===e._mode&&"overrideMimeType"in l&&l.overrideMimeType("text/plain; charset=x-user-defined"),Object.keys(a).forEach(function(e){l.setRequestHeader(a[e].name,a[e].value)}),e._response=null,l.onreadystatechange=function(){switch(l.readyState){case p.LOADING:case p.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(l.onprogress=function(){e._onXHRProgress()}),l.onerror=function(){e._destroyed||e.emit("error",new Error("XHR error"))};try{l.send(t)}catch(c){return void r.nextTick(function(){e.emit("error",c)})}}}},d.prototype._onXHRProgress=function(){var e=this;a(e._xhr)&&!e._destroyed&&(e._response||e._connect(),e._response._onXHRProgress())},d.prototype._connect=function(){var e=this;e._destroyed||(e._response=new h(e._xhr,e._fetchResponse,e._mode),e.emit("response",e._response))},d.prototype._write=function(e,t,r){var n=this;n._body.push(e),r()},d.prototype.abort=d.prototype.destroy=function(){var e=this;e._destroyed=!0,e._response&&(e._response._destroyed=!0),e._xhr&&e._xhr.abort()},d.prototype.end=function(e,t,r){var n=this;"function"==typeof e&&(r=e,e=void 0),c.Writable.prototype.end.call(n,e,t,r)},d.prototype.flushHeaders=function(){},d.prototype.setTimeout=function(){},d.prototype.setNoDelay=function(){},d.prototype.setSocketKeepAlive=function(){};var g=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":105,"./response":107,_process:77,buffer:5,inherits:71,stream:103,"to-arraybuffer":109}],107:[function(e,t,r){(function(t,n,i){var o=e("./capability"),a=e("inherits"),s=e("stream"),u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},l=r.IncomingMessage=function(e,r,n){function a(){h.read().then(function(e){if(!u._destroyed){if(e.done)return void u.push(null);u.push(new i(e.value)),a()}})}var u=this;if(s.Readable.call(u),u._mode=n,u.headers={},u.rawHeaders=[],u.trailers={},u.rawTrailers=[],u.on("end",function(){t.nextTick(function(){u.emit("close")})}),"fetch"===n){u._fetchResponse=r,u.statusCode=r.status,u.statusMessage=r.statusText;for(var l,c,f=r.headers[Symbol.iterator]();l=(c=f.next()).value,!c.done;)u.headers[l[0].toLowerCase()]=l[1],u.rawHeaders.push(l[0],l[1]);var h=r.body.getReader();a()}else{u._xhr=e,u._pos=0,u.statusCode=e.status,u.statusMessage=e.statusText;var p=e.getAllResponseHeaders().split(/\r?\n/);if(p.forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===u.headers[r]&&(u.headers[r]=[]),u.headers[r].push(t[2])):void 0!==u.headers[r]?u.headers[r]+=", "+t[2]:u.headers[r]=t[2],u.rawHeaders.push(t[1],t[2])}}),u._charset="x-user-defined",!o.overrideMimeType){var d=u.rawHeaders["mime-type"];if(d){var g=d.match(/;\s*charset=([^;])(;|$)/);g&&(u._charset=g[1].toLowerCase())}u._charset||(u._charset="utf-8")}}};a(l,s.Readable),l.prototype._read=function(){},l.prototype._onXHRProgress=function(){var e=this,t=e._xhr,r=null;switch(e._mode){case"text:vbarray":if(t.readyState!==u.DONE)break;try{r=new n.VBArray(t.responseBody).toArray()}catch(o){}if(null!==r){e.push(new i(r));break}case"text":try{r=t.responseText}catch(o){e._mode="text:vbarray";break}if(r.length>e._pos){var a=r.substr(e._pos);if("x-user-defined"===e._charset){for(var s=new i(a.length),l=0;le._pos&&(e.push(new i(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(r)}e._xhr.readyState===u.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":105,_process:77,buffer:5,inherits:71,stream:103}],108:[function(e,t,r){function n(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function o(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var s=e("buffer").Buffer,u=s.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},l=r.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),n(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=o;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new s(6),this.charReceived=0,this.charLength=0};l.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&56319>=n)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,n=t.charCodeAt(i);if(n>=55296&&56319>=n){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,i)}return t},l.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(2>=t&&r>>4==14){this.charLength=3;break}if(3>=t&&r>>3==30){this.charLength=4;break}}this.charReceived=t},l.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding; -t+=n.slice(0,r).toString(i)}return t}},{buffer:5}],109:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(n.isBuffer(e)){for(var t=new Uint8Array(e.length),r=e.length,i=0;r>i;i++)t[i]=e[i];return t.buffer}throw new Error("Argument must be a Buffer")}},{buffer:5}],110:[function(e,t,r){"use strict";function n(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function i(e,t,r){if(e&&l.isObject(e)&&e instanceof n)return e;var i=new n;return i.parse(e,t,r),i}function o(e){return l.isString(e)&&(e=i(e)),e instanceof n?e.format():n.prototype.format.call(e)}function a(e,t){return i(e,!1,!0).resolve(t)}function s(e,t){return e?i(e,!1,!0).resolveObject(t):t}var u=e("punycode"),l=e("./util");r.parse=i,r.resolve=a,r.resolveObject=s,r.format=o,r.Url=n;var c=/^([a-z0-9.+-]+:)/i,f=/:[0-9]*$/,h=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,p=["<",">",'"',"`"," ","\r","\n"," "],d=["{","}","|","\\","^","`"].concat(p),g=["'"].concat(d),m=["%","/","?",";","#"].concat(g),v=["/","?","#"],b=255,y=/^[+a-z0-9A-Z_-]{0,63}$/,w=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,_={javascript:!0,"javascript:":!0},x={javascript:!0,"javascript:":!0},k={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},O=e("querystring");n.prototype.parse=function(e,t,r){if(!l.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var n=e.indexOf("?"),i=-1!==n&&nA)&&(S=A)}var R,M;M=-1===S?s.lastIndexOf("@"):s.lastIndexOf("@",S),-1!==M&&(R=s.slice(0,M),s=s.slice(M+1),this.auth=decodeURIComponent(R)),S=-1;for(var E=0;EA)&&(S=A)}-1===S&&(S=s.length),this.host=s.slice(0,S),s=s.slice(S),this.parseHost(),this.hostname=this.hostname||"";var L="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!L)for(var j=this.hostname.split(/\./),E=0,T=j.length;T>E;E++){var P=j[E];if(P&&!P.match(y)){for(var V="",B=0,U=P.length;U>B;B++)V+=P.charCodeAt(B)>127?"x":P[B];if(!V.match(y)){var D=j.slice(0,E),I=j.slice(E+1),N=P.match(w);N&&(D.push(N[1]),I.unshift(N[2])),I.length&&(s="/"+I.join(".")+s),this.hostname=D.join(".");break}}}this.hostname.length>b?this.hostname="":this.hostname=this.hostname.toLowerCase(),L||(this.hostname=u.toASCII(this.hostname));var z=this.port?":"+this.port:"",q=this.hostname||"";this.host=q+z,this.href+=this.host,L&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==s[0]&&(s="/"+s))}if(!_[d])for(var E=0,T=g.length;T>E;E++){var F=g[E];if(-1!==s.indexOf(F)){var $=encodeURIComponent(F);$===F&&($=escape(F)),s=s.split(F).join($)}}var H=s.indexOf("#");-1!==H&&(this.hash=s.substr(H),s=s.slice(0,H));var W=s.indexOf("?");if(-1!==W?(this.search=s.substr(W),this.query=s.substr(W+1),t&&(this.query=O.parse(this.query)),s=s.slice(0,W)):t&&(this.search="",this.query={}),s&&(this.pathname=s),k[d]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var z=this.pathname||"",Y=this.search||"";this.path=z+Y}return this.href=this.format(),this},n.prototype.format=function(){var e=this.auth||"";e&&(e=encodeURIComponent(e),e=e.replace(/%3A/i,":"),e+="@");var t=this.protocol||"",r=this.pathname||"",n=this.hash||"",i=!1,o="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&l.isObject(this.query)&&Object.keys(this.query).length&&(o=O.stringify(this.query));var a=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||k[t])&&i!==!1?(i="//"+(i||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):i||(i=""),n&&"#"!==n.charAt(0)&&(n="#"+n),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(e){return encodeURIComponent(e)}),a=a.replace("#","%23"),t+i+r+a+n},n.prototype.resolve=function(e){return this.resolveObject(i(e,!1,!0)).format()},n.prototype.resolveObject=function(e){if(l.isString(e)){var t=new n;t.parse(e,!1,!0),e=t}for(var r=new n,i=Object.keys(this),o=0;o0?r.host.split("@"):!1;C&&(r.auth=C.shift(),r.host=r.hostname=C.shift())}return r.search=e.search,r.query=e.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!_.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var S=_.slice(-1)[0],E=(r.host||e.host||_.length>1)&&("."===S||".."===S)||""===S,A=0,R=_.length;R>=0;R--)S=_[R],"."===S?_.splice(R,1):".."===S?(_.splice(R,1),A++):A&&(_.splice(R,1),A--);if(!y&&!w)for(;A--;A)_.unshift("..");!y||""===_[0]||_[0]&&"/"===_[0].charAt(0)||_.unshift(""),E&&"/"!==_.join("/").substr(-1)&&_.push("");var M=""===_[0]||_[0]&&"/"===_[0].charAt(0);if(O){r.hostname=r.host=M?"":_.length?_.shift():"";var C=r.host&&r.host.indexOf("@")>0?r.host.split("@"):!1;C&&(r.auth=C.shift(),r.host=r.hostname=C.shift())}return y=y||r.host&&_.length,y&&!M&&_.unshift(""),_.length?r.pathname=_.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var e=this.host,t=f.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":111,punycode:78,querystring:81}],111:[function(e,t,r){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],112:[function(e,t,r){(function(e){function r(e,t){function r(){if(!i){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation")?console.trace(t):console.warn(t),i=!0}return e.apply(this,arguments)}if(n("noDeprecation"))return e;var i=!1;return r}function n(t){try{if(!e.localStorage)return!1}catch(r){return!1}var n=e.localStorage[t];return null==n?!1:"true"===String(n).toLowerCase()}t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],113:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],114:[function(e,t,r){(function(t,n){function i(e,t){var n={seen:[],stylize:a};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&r._extend(n,t),_(n.showHidden)&&(n.showHidden=!1),_(n.depth)&&(n.depth=2),_(n.colors)&&(n.colors=!1),_(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=o),u(n,e,n.depth)}function o(e,t){var r=i.styles[t];return r?"["+i.colors[r][0]+"m"+e+"["+i.colors[r][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}function u(e,t,n){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return y(i)||(i=u(e,i,n)),i}var o=l(e,t);if(o)return o;var a=Object.keys(t),g=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),C(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.length){if(S(t)){var m=t.name?": "+t.name:"";return e.stylize("[Function"+m+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(O(t))return e.stylize(Date.prototype.toString.call(t),"date");if(C(t))return c(t)}var v="",b=!1,w=["{","}"];if(d(t)&&(b=!0,w=["[","]"]),S(t)){var _=t.name?": "+t.name:"";v=" [Function"+_+"]"}if(x(t)&&(v=" "+RegExp.prototype.toString.call(t)),O(t)&&(v=" "+Date.prototype.toUTCString.call(t)),C(t)&&(v=" "+c(t)),0===a.length&&(!b||0==t.length))return w[0]+v+w[1];if(0>n)return x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var k;return k=b?f(e,t,n,g,a):a.map(function(r){return h(e,t,n,g,r,b)}),e.seen.pop(),p(k,v,w)}function l(e,t){if(_(t))return e.stylize("undefined","undefined");if(y(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return b(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):m(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,r,n,i){for(var o=[],a=0,s=t.length;s>a;++a)L(t,String(a))?o.push(h(e,t,r,n,String(a),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(h(e,t,r,n,i,!0))}),o}function h(e,t,r,n,i,o){var a,s,l;if(l=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},l.get?s=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(s=e.stylize("[Setter]","special")),L(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(l.value)<0?(s=m(r)?u(e,l.value,null):u(e,l.value,r-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),_(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function p(e,t,r){var n=0,i=e.reduce(function(e,t){return n++,t.indexOf("\n")>=0&&n++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}function d(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function m(e){return null===e}function v(e){return null==e}function b(e){return"number"==typeof e}function y(e){return"string"==typeof e}function w(e){return"symbol"==typeof e}function _(e){return void 0===e}function x(e){return k(e)&&"[object RegExp]"===A(e)}function k(e){return"object"==typeof e&&null!==e}function O(e){return k(e)&&"[object Date]"===A(e)}function C(e){return k(e)&&("[object Error]"===A(e)||e instanceof Error)}function S(e){return"function"==typeof e}function E(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return Object.prototype.toString.call(e)}function R(e){return 10>e?"0"+e.toString(10):e.toString(10)}function M(){var e=new Date,t=[R(e.getHours()),R(e.getMinutes()),R(e.getSeconds())].join(":");return[e.getDate(),V[e.getMonth()],t].join(" ")}function L(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var j=/%[sdj%]/g;r.format=function(e){if(!y(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return e}}),s=n[r];o>r;s=n[++r])a+=m(s)||!k(s)?" "+s:" "+i(s);return a},r.deprecate=function(e,i){function o(){if(!a){if(t.throwDeprecation)throw new Error(i);t.traceDeprecation?console.trace(i):console.error(i),a=!0}return e.apply(this,arguments)}if(_(n.process))return function(){return r.deprecate(e,i).apply(this,arguments)};if(t.noDeprecation===!0)return e;var a=!1;return o};var T,P={};r.debuglog=function(e){if(_(T)&&(T=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!P[e])if(new RegExp("\\b"+e+"\\b","i").test(T)){var n=t.pid;P[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else P[e]=function(){};return P[e]},r.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=g,r.isNull=m,r.isNullOrUndefined=v,r.isNumber=b,r.isString=y,r.isSymbol=w,r.isUndefined=_,r.isRegExp=x,r.isObject=k,r.isDate=O,r.isError=C,r.isFunction=S,r.isPrimitive=E,r.isBuffer=e("./support/isBuffer");var V=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];r.log=function(){console.log("%s - %s",M(),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!k(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":113,_process:77,inherits:71}],115:[function(e,t,r){function n(){for(var e={},t=0;t1&&(n=r[0]+"@",t=r[1]),t=t.replace(C,".");var o=t.split("."),s=a(o,e).join(".");return n+s}function u(t){for(var e,r,n=[],o=0,s=t.length;s>o;)e=t.charCodeAt(o++),e>=55296&&56319>=e&&s>o?(r=t.charCodeAt(o++),56320==(64512&r)?n.push(((1023&e)<<10)+(1023&r)+65536):(n.push(e),o--)):n.push(e);return n}function h(t){return a(t,function(t){var e="";return t>65535&&(t-=65536,e+=D(t>>>10&1023|55296),t=56320|1023&t),e+=D(t)}).join("")}function l(t){return 10>t-48?t-22:26>t-65?t-65:26>t-97?t-97:j}function c(t,e){return t+22+75*(26>t)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?Q(t/E):t>>1,t+=Q(t/e);t>L*A>>1;n+=j)t=Q(t/L);return Q(n+(L+1)*t/(t+R))}function m(t){var e,r,n,o,a,i,u,c,m,p,v=[],x=t.length,y=0,d=q,g=S;for(r=t.lastIndexOf(P),0>r&&(r=0),n=0;r>n;++n)t.charCodeAt(n)>=128&&s("not-basic"),v.push(t.charCodeAt(n));for(o=r>0?r+1:0;x>o;){for(a=y,i=1,u=j;o>=x&&s("invalid-input"),c=l(t.charCodeAt(o++)),(c>=j||c>Q((I-y)/i))&&s("overflow"),y+=c*i,m=g>=u?w:u>=g+A?A:u-g,!(m>c);u+=j)p=j-m,i>Q(I/p)&&s("overflow"),i*=p;e=v.length+1,g=f(y-a,e,0==a),Q(y/e)>I-d&&s("overflow"),d+=Q(y/e),y%=e,v.splice(y++,0,d)}return h(v)}function p(t){var e,r,n,o,a,i,h,l,m,p,v,x,y,d,g,b=[];for(t=u(t),x=t.length,e=q,r=0,a=S,i=0;x>i;++i)v=t[i],128>v&&b.push(D(v));for(n=o=b.length,o&&b.push(P);x>n;){for(h=I,i=0;x>i;++i)v=t[i],v>=e&&h>v&&(h=v);for(y=n+1,h-e>Q((I-r)/y)&&s("overflow"),r+=(h-e)*y,e=h,i=0;x>i;++i)if(v=t[i],e>v&&++r>I&&s("overflow"),v==e){for(l=r,m=j;p=a>=m?w:m>=a+A?A:m-a,!(p>l);m+=j)g=l-p,d=j-p,b.push(D(c(p+g%d,0))),l=Q(g/d);b.push(D(c(l,0))),a=f(r,y,n==o),r=0,++n}++r,++e}return b.join("")}function v(t){return i(t,function(t){return T.test(t)?m(t.slice(4).toLowerCase()):t})}function x(t){return i(t,function(t){return U.test(t)?"xn--"+p(t):t})}var y="object"==typeof n&&n&&!n.nodeType&&n,d="object"==typeof r&&r&&!r.nodeType&&r,g="object"==typeof e&&e;g.global!==g&&g.window!==g&&g.self!==g||(o=g);var b,O,I=2147483647,j=36,w=1,A=26,R=38,E=700,S=72,q=128,P="-",T=/^xn--/,U=/[^\x20-\x7E]/,C=/[\x2E\u3002\uFF0E\uFF61]/g,H={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=j-w,Q=Math.floor,D=String.fromCharCode;if(b={version:"1.3.2",ucs2:{decode:u,encode:h},decode:m,encode:p,toASCII:x,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(y&&d)if(r.exports==y)d.exports=b;else for(O in b)b.hasOwnProperty(O)&&(y[O]=b[O]);else o.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],2:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,s){e=e||"&",r=r||"=";var a={};if("string"!=typeof t||0===t.length)return a;var i=/\+/g;t=t.split(e);var u=1e3;s&&"number"==typeof s.maxKeys&&(u=s.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;h>l;++l){var c,f,m,p,v=t[l].replace(i,"%20"),x=v.indexOf(r);x>=0?(c=v.substr(0,x),f=v.substr(x+1)):(c=v,f=""),m=decodeURIComponent(c),p=decodeURIComponent(f),n(a,m)?o(a[m])?a[m].push(p):a[m]=[a[m],p]:a[m]=p}return a};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],3:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n-1){if(++o-1&&(r=r.toString(),null===t.port&&(t.port=r),t.extra.portIsDefault=t.port===r)}e.exports=n},{}],13:[function(t,e,r){"use strict";function n(t,e){t.query.string.full=o(t.query.object,!1),e.removeEmptyQueries&&(t.query.string.stripped=o(t.query.object,!0))}function o(t,e){var r=0,n="";for(var o in t)if(""!==o&&t.hasOwnProperty(o)){var s=t[o];""===s&&e||(n+=1===++r?"?":"&",o=encodeURIComponent(o),n+=""!==s?o+"="+encodeURIComponent(s).replace(/%20/g,"+"):o)}return n}e.exports=n},{}],14:[function(t,e,r){"use strict";function n(t){var e=t.protocol;return e&&e.indexOf(":")===e.length-1&&(e=e.substr(0,e.length-1)),t.host={full:t.hostname,stripped:null},t.path={absolute:{array:null,string:t.pathname},relative:{array:null,string:null}},t.query={object:t.query,string:{full:null,stripped:null}},t.extra={hrefInfo:{minimumPathOnly:null,minimumResourceOnly:null,minimumQueryOnly:null,minimumHashOnly:null,empty:null,separatorOnlyQuery:"?"===t.search},portIsDefault:null,relation:{maximumScheme:null,maximumAuth:null,maximumHost:null,maximumPort:null,maximumPath:null,maximumResource:null,maximumQuery:null,maximumHash:null,minimumScheme:null,minimumAuth:null,minimumHost:null,minimumPort:null,minimumPath:null,minimumResource:null,minimumQuery:null,minimumHash:null,overridesQuery:null},resourceIsIndex:null,slashes:t.slashes},t.resource=null,t.scheme=e,delete t.hostname,delete t.pathname,delete t.protocol,delete t.search,delete t.slashes,t}function o(t,e){var r=!0;return e.rejectedSchemes.every(function(e){return r=!(0===t.indexOf(e+":"))}),r}function s(t,e){return o(t,e)?n(a(t,!0,e.slashesDenoteHost)):{href:t,valid:!1}}var a=t("url").parse;e.exports=s},{url:22}],15:[function(t,e,r){"use strict";function n(t,e,r){i.upToPath(t,e,r),t.extra.relation.minimumScheme&&(t.scheme=e.scheme),t.extra.relation.minimumAuth&&(t.auth=e.auth),t.extra.relation.minimumHost&&(t.host=u.clone(e.host)),t.extra.relation.minimumPort&&s(t,e),t.extra.relation.minimumScheme&&o(t,e),i.pathOn(t,e,r),t.extra.relation.minimumResource&&a(t,e),t.extra.relation.minimumQuery&&(t.query=u.clone(e.query)),t.extra.relation.minimumHash&&(t.hash=e.hash)}function o(t,e){if(t.extra.relation.maximumHost||!t.extra.hrefInfo.minimumResourceOnly){var r=t.path.absolute.array,n="/";r?(t.extra.hrefInfo.minimumPathOnly&&0!==t.path.absolute.string.indexOf("/")&&(r=e.path.absolute.array.concat(r)),r=h.resolveDotSegments(r),n+=h.join(r)):r=[],t.path.absolute.array=r,t.path.absolute.string=n}else t.path=u.clone(e.path)}function s(t,e){t.port=e.port,t.extra.portIsDefault=e.extra.portIsDefault}function a(t,e){t.resource=e.resource,t.extra.resourceIsIndex=e.extra.resourceIsIndex}var i=t("./findRelation"),u=t("../util/object"),h=t("../util/path");e.exports=n},{"../util/object":19,"../util/path":20,"./findRelation":16}],16:[function(t,e,r){"use strict";function n(t,e,r){var n=t.extra.hrefInfo.minimumPathOnly,o=t.scheme===e.scheme||!t.scheme,s=o&&(t.auth===e.auth||r.removeAuth||n),a=r.ignore_www?"stripped":"full",i=s&&(t.host[a]===e.host[a]||n),u=i&&(t.port===e.port||n);t.extra.relation.minimumScheme=o,t.extra.relation.minimumAuth=s,t.extra.relation.minimumHost=i,t.extra.relation.minimumPort=u,t.extra.relation.maximumScheme=!o||o&&!s,t.extra.relation.maximumAuth=!o||o&&!i,t.extra.relation.maximumHost=!o||o&&!u}function o(t,e,r){var n=t.extra.hrefInfo.minimumQueryOnly,o=t.extra.hrefInfo.minimumHashOnly,s=t.extra.hrefInfo.empty,a=t.extra.relation.minimumPort,i=t.extra.relation.minimumScheme,u=a&&t.path.absolute.string===e.path.absolute.string,h=t.resource===e.resource||!t.resource&&e.extra.resourceIsIndex||r.removeDirectoryIndexes&&t.extra.resourceIsIndex&&!e.resource,l=u&&(h||n||o||s),c=r.removeEmptyQueries?"stripped":"full",f=t.query.string[c],m=e.query.string[c],p=l&&!!f&&f===m||(o||s)&&!t.extra.hrefInfo.separatorOnlyQuery,v=p&&t.hash===e.hash;t.extra.relation.minimumPath=u,t.extra.relation.minimumResource=l,t.extra.relation.minimumQuery=p,t.extra.relation.minimumHash=v,t.extra.relation.maximumPort=!i||i&&!u,t.extra.relation.maximumPath=!i||i&&!l,t.extra.relation.maximumResource=!i||i&&!p,t.extra.relation.maximumQuery=!i||i&&!v,t.extra.relation.maximumHash=!i||i&&!v,t.extra.relation.overridesQuery=u&&t.extra.relation.maximumResource&&!p&&!!m}e.exports={pathOn:o,upToPath:n}},{}],17:[function(t,e,r){"use strict";function n(t,e,r){return o(e,t,r),s(e,t,r),e}var o=t("./absolutize"),s=t("./relativize");e.exports=n},{"./absolutize":15,"./relativize":18}],18:[function(t,e,r){"use strict";function n(t,e){var r=[],n=!0,o=-1;return e.forEach(function(e,s){n&&(t[s]!==e?n=!1:o=s),n||r.push("..")}),t.forEach(function(t,e){e>o&&r.push(t)}),r}function o(t,e,r){if(t.extra.relation.minimumScheme){var o=n(t.path.absolute.array,e.path.absolute.array);t.path.relative.array=o,t.path.relative.string=s.join(o)}}var s=t("../util/path");e.exports=o},{"../util/path":20}],19:[function(t,e,r){"use strict";function n(t){if(t instanceof Object){var e=t instanceof Array?[]:{};for(var r in t)t.hasOwnProperty(r)&&(e[r]=n(t[r]));return e}return t}function o(t){return!!t&&"object"==typeof t&&t.constructor===Object}function s(t,e){if(t instanceof Object&&e instanceof Object)for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports={clone:n,isPlainObject:o,shallowMerge:s}},{}],20:[function(t,e,r){"use strict";function n(t){return t.length?t.join("/")+"/":""}function o(t){var e=[];return t.forEach(function(t){".."!==t?"."!==t&&e.push(t):e.length&&e.splice(e.length-1,1)}),e}e.exports={join:n,resolveDotSegments:o}},{}],21:[function(t,e,r){"use strict";function n(t,e){this.options=a(e,{defaultPorts:{ftp:21,http:80,https:443},directoryIndexes:["index.html"],ignore_www:!1,output:n.SHORTEST,rejectedSchemes:["data","javascript","mailto"],removeAuth:!1,removeDirectoryIndexes:!0,removeEmptyQueries:!1,removeRootTrailingSlash:!0,schemeRelative:!0,site:void 0,slashesDenoteHost:!0}),this.from=u.from(t,this.options,null)}var o=t("./constants"),s=t("./format"),a=t("./options"),i=t("./util/object"),u=t("./parse"),h=t("./relate");n.prototype.relate=function(t,e,r){if(i.isPlainObject(e)?(r=e,e=t,t=null):e||(e=t,t=null),r=a(r,this.options),t=t||r.site,t=u.from(t,r,this.from),!t||!t.href)throw new Error("from value not defined.");if(t.extra.hrefInfo.minimumPathOnly)throw new Error("from value supplied is not absolute: "+t.href);return e=u.to(e,r),e.valid===!1?e.href:(e=h(t,e,r),e=s(e,r))},n.relate=function(t,e,r){return(new n).relate(t,e,r)},i.shallowMerge(n,o),e.exports=n},{"./constants":5,"./format":6,"./options":7,"./parse":10,"./relate":17,"./util/object":19}],22:[function(t,e,r){"use strict";function n(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function o(t,e,r){if(t&&h.isObject(t)&&t instanceof n)return t;var o=new n;return o.parse(t,e,r),o}function s(t){return h.isString(t)&&(t=o(t)),t instanceof n?t.format():n.prototype.format.call(t)}function a(t,e){return o(t,!1,!0).resolve(e)}function i(t,e){return t?o(t,!1,!0).resolveObject(e):e}var u=t("punycode"),h=t("./util");r.parse=o,r.resolve=a,r.resolveObject=i,r.format=s,r.Url=n;var l=/^([a-z0-9.+-]+:)/i,c=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,m=["<",">",'"',"`"," ","\r","\n"," "],p=["{","}","|","\\","^","`"].concat(m),v=["'"].concat(p),x=["%","/","?",";","#"].concat(v),y=["/","?","#"],d=255,g=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,O={javascript:!0,"javascript:":!0},I={javascript:!0,"javascript:":!0},j={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),o=-1!==n&&nS)&&(R=S)}var q,P;P=-1===R?i.lastIndexOf("@"):i.lastIndexOf("@",R),-1!==P&&(q=i.slice(0,P),i=i.slice(P+1),this.auth=decodeURIComponent(q)),R=-1;for(var E=0;ES)&&(R=S)}-1===R&&(R=i.length),this.host=i.slice(0,R),i=i.slice(R),this.parseHost(),this.hostname=this.hostname||"";var T="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!T)for(var U=this.hostname.split(/\./),E=0,C=U.length;C>E;E++){var H=U[E];if(H&&!H.match(g)){for(var L="",Q=0,D=H.length;D>Q;Q++)L+=H.charCodeAt(Q)>127?"x":H[Q];if(!L.match(g)){var _=U.slice(0,E),B=U.slice(E+1),N=H.match(b);N&&(_.push(N[1]),B.unshift(N[2])),B.length&&(i="/"+B.join(".")+i),this.hostname=_.join(".");break}}}this.hostname.length>d?this.hostname="":this.hostname=this.hostname.toLowerCase(),T||(this.hostname=u.toASCII(this.hostname));var k=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+k,this.href+=this.host,T&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==i[0]&&(i="/"+i))}if(!O[p])for(var E=0,C=v.length;C>E;E++){var F=v[E];if(-1!==i.indexOf(F)){var V=encodeURIComponent(F);V===F&&(V=escape(F)),i=i.split(F).join(V)}}var M=i.indexOf("#");-1!==M&&(this.hash=i.substr(M),i=i.slice(0,M));var $=i.indexOf("?");if(-1!==$?(this.search=i.substr($),this.query=i.substr($+1),e&&(this.query=w.parse(this.query)),i=i.slice(0,$)):e&&(this.search="",this.query={}),i&&(this.pathname=i),j[p]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var k=this.pathname||"",K=this.search||"";this.path=k+K}return this.href=this.format(),this},n.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var e=this.protocol||"",r=this.pathname||"",n=this.hash||"",o=!1,s="";this.host?o=t+this.host:this.hostname&&(o=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(o+=":"+this.port)),this.query&&h.isObject(this.query)&&Object.keys(this.query).length&&(s=w.stringify(this.query));var a=this.search||s&&"?"+s||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||j[e])&&o!==!1?(o="//"+(o||""),r&&"/"!==r.charAt(0)&&(r="/"+r)):o||(o=""),n&&"#"!==n.charAt(0)&&(n="#"+n),a&&"?"!==a.charAt(0)&&(a="?"+a),r=r.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),e+o+r+a+n},n.prototype.resolve=function(t){return this.resolveObject(o(t,!1,!0)).format()},n.prototype.resolveObject=function(t){if(h.isString(t)){var e=new n;e.parse(t,!1,!0),t=e}for(var r=new n,o=Object.keys(this),s=0;s0?r.host.split("@"):!1;A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!O.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var R=O.slice(-1)[0],E=(r.host||t.host||O.length>1)&&("."===R||".."===R)||""===R,S=0,q=O.length;q>=0;q--)R=O[q],"."===R?O.splice(q,1):".."===R?(O.splice(q,1),S++):S&&(O.splice(q,1),S--);if(!g&&!b)for(;S--;S)O.unshift("..");!g||""===O[0]||O[0]&&"/"===O[0].charAt(0)||O.unshift(""),E&&"/"!==O.join("/").substr(-1)&&O.push("");var P=""===O[0]||O[0]&&"/"===O[0].charAt(0);if(w){r.hostname=r.host=P?"":O.length?O.shift():"";var A=r.host&&r.host.indexOf("@")>0?r.host.split("@"):!1;A&&(r.auth=A.shift(),r.host=r.hostname=A.shift())}return g=g||r.host&&O.length,g&&!P&&O.unshift(""),O.length?r.pathname=O.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":23,punycode:1,querystring:4}],23:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}]},{},[21])(21)}); \ No newline at end of file diff --git a/assets/uglify-browser.js b/assets/uglify-browser.js deleted file mode 100644 index 17ed0ef..0000000 --- a/assets/uglify-browser.js +++ /dev/null @@ -1,6 +0,0 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.UglifyJS=e()}}(function(){return function e(n,t,r){function o(a,u){if(!t[a]){if(!n[a]){var s="function"==typeof require&&require;if(!u&&s)return s(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=t[a]={exports:{}};n[a][0].call(l.exports,function(e){var t=n[a][1][e];return o(t?t:e)},l,l.exports,e,n,t,r)}return t[a].exports}for(var i="function"==typeof require&&require,a=0;a1)for(var t=1;to;o++)t.add(e[o],n);return t},r.prototype.size=function(){return Object.getOwnPropertyNames(this._set).length},r.prototype.add=function(e,n){var t=o.toSetString(e),r=this._set.hasOwnProperty(t),i=this._array.length;r&&!n||this._array.push(e),r||(this._set[t]=i)},r.prototype.has=function(e){var n=o.toSetString(e);return this._set.hasOwnProperty(n)},r.prototype.indexOf=function(e){var n=o.toSetString(e);if(this._set.hasOwnProperty(n))return this._set[n];throw new Error('"'+e+'" is not in the set.')},r.prototype.at=function(e){if(e>=0&&ee?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),t=e>>1;return n?-t:t}var i=e("./base64"),a=5,u=1<>>=a,o>0&&(n|=c),t+=i.encode(n);while(o>0);return t},t.decode=function(e,n,t){var r,u,l=e.length,f=0,p=0;do{if(n>=l)throw new Error("Expected more digits in base 64 VLQ value.");if(u=i.decode(e.charCodeAt(n++)),-1===u)throw new Error("Invalid base64 digit: "+e.charAt(n-1));r=!!(u&c),u&=s,f+=u<=0&&e=n&&t>=e?e-n:e>=r&&o>=e?e-r+c:e>=i&&a>=e?e-i+l:e==u?62:e==s?63:-1}},{}],6:[function(e,n,t){function r(e,n,o,i,a,u){var s=Math.floor((n-e)/2)+e,c=a(o,i[s],!0);return 0===c?s:c>0?n-s>1?r(s,n,o,i,a,u):u==t.LEAST_UPPER_BOUND?n1?r(e,s,o,i,a,u):u==t.LEAST_UPPER_BOUND?s:0>e?-1:e}t.GREATEST_LOWER_BOUND=1,t.LEAST_UPPER_BOUND=2,t.search=function(e,n,o,i){if(0===n.length)return-1;var a=r(-1,n.length,e,n,o,i||t.GREATEST_LOWER_BOUND);if(0>a)return-1;for(;a-1>=0&&0===o(n[a],n[a-1],!0);)--a;return a}},{}],7:[function(e,n,t){function r(e,n){var t=e.generatedLine,r=n.generatedLine,o=e.generatedColumn,a=n.generatedColumn;return r>t||r==t&&a>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=e("./util");o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){r(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},t.MappingList=o},{"./util":12}],8:[function(e,n,t){function r(e,n,t){var r=e[n];e[n]=e[t],e[t]=r}function o(e,n){return Math.round(e+Math.random()*(n-e))}function i(e,n,t,a){if(a>t){var u=o(t,a),s=t-1;r(e,u,a);for(var c=e[a],l=t;a>l;l++)n(e[l],c)<=0&&(s+=1,r(e,s,l));r(e,s+1,l);var f=s+1;i(e,n,t,f-1),i(e,n,f+1,a)}}t.quickSort=function(e,n){i(e,n,0,e.length-1)}},{}],9:[function(e,n,t){function r(e){var n=e;return"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=n.sections?new a(n):new o(n)}function o(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var t=u.getArg(n,"version"),r=u.getArg(n,"sources"),o=u.getArg(n,"names",[]),i=u.getArg(n,"sourceRoot",null),a=u.getArg(n,"sourcesContent",null),s=u.getArg(n,"mappings"),l=u.getArg(n,"file",null);if(t!=this._version)throw new Error("Unsupported version: "+t);r=r.map(u.normalize).map(function(e){return i&&u.isAbsolute(i)&&u.isAbsolute(e)?u.relative(i,e):e}),this._names=c.fromArray(o,!0),this._sources=c.fromArray(r,!0),this.sourceRoot=i,this.sourcesContent=a,this._mappings=s,this.file=l}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function a(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var t=u.getArg(n,"version"),o=u.getArg(n,"sections");if(t!=this._version)throw new Error("Unsupported version: "+t);this._sources=new c,this._names=new c;var i={line:-1,column:0};this._sections=o.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var n=u.getArg(e,"offset"),t=u.getArg(n,"line"),o=u.getArg(n,"column");if(t=0){var i=this._originalMappings[o];if(void 0===e.column)for(var a=i.originalLine;i&&i.originalLine===a;)r.push({line:u.getArg(i,"generatedLine",null),column:u.getArg(i,"generatedColumn",null),lastColumn:u.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var c=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==c;)r.push({line:u.getArg(i,"generatedLine",null),column:u.getArg(i,"generatedColumn",null),lastColumn:u.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return r},t.SourceMapConsumer=r,o.prototype=Object.create(r.prototype),o.prototype.consumer=r,o.fromSourceMap=function(e){var n=Object.create(o.prototype),t=n._names=c.fromArray(e._names.toArray(),!0),r=n._sources=c.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file;for(var a=e._mappings.toArray().slice(),s=n.__generatedMappings=[],l=n.__originalMappings=[],p=0,d=a.length;d>p;p++){var h=a[p],g=new i;g.generatedLine=h.generatedLine,g.generatedColumn=h.generatedColumn,h.source&&(g.source=r.indexOf(h.source),g.originalLine=h.originalLine,g.originalColumn=h.originalColumn,h.name&&(g.name=t.indexOf(h.name)),l.push(g)),s.push(g)}return f(n.__originalMappings,u.compareByOriginalPositions),n},o.prototype._version=3,Object.defineProperty(o.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?u.join(this.sourceRoot,e):e},this)}}),o.prototype._parseMappings=function(e,n){for(var t,r,o,a,s,c=1,p=0,d=0,h=0,g=0,m=0,_=e.length,v=0,y={},b={},A=[],w=[];_>v;)if(";"===e.charAt(v))c++,v++,p=0;else if(","===e.charAt(v))v++;else{for(t=new i,t.generatedLine=c,a=v;_>a&&!this._charIsMappingSeparator(e,a);a++);if(r=e.slice(v,a),o=y[r])v+=r.length;else{for(o=[];a>v;)l.decode(e,v,b),s=b.value,v=b.rest,o.push(s);if(2===o.length)throw new Error("Found a source, but no line and column");if(3===o.length)throw new Error("Found a source and line, but no column");y[r]=o}t.generatedColumn=p+o[0],p=t.generatedColumn,o.length>1&&(t.source=g+o[1],g+=o[1],t.originalLine=d+o[2],d=t.originalLine,t.originalLine+=1,t.originalColumn=h+o[3],h=t.originalColumn,o.length>4&&(t.name=m+o[4],m+=o[4])),w.push(t),"number"==typeof t.originalLine&&A.push(t)}f(w,u.compareByGeneratedPositionsDeflated),this.__generatedMappings=w,f(A,u.compareByOriginalPositions),this.__originalMappings=A},o.prototype._findMapping=function(e,n,t,r,o,i){if(e[t]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[t]);if(e[r]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[r]);return s.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[t];if(o.generatedLine===n.generatedLine){var i=u.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),null!=this.sourceRoot&&(i=u.join(this.sourceRoot,i)));var a=u.getArg(o,"name",null);return null!==a&&(a=this._names.at(a)),{source:i,line:u.getArg(o,"originalLine",null),column:u.getArg(o,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}):!1},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=u.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var t;if(null!=this.sourceRoot&&(t=u.urlParse(this.sourceRoot))){var r=e.replace(/^file:\/\//,"");if("file"==t.scheme&&this._sources.has(r))return this.sourcesContent[this._sources.indexOf(r)];if((!t.path||"/"==t.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(n)return null;throw new Error('"'+e+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=u.getArg(e,"source");if(null!=this.sourceRoot&&(n=u.relative(this.sourceRoot,n)),!this._sources.has(n))return{line:null,column:null,lastColumn:null};n=this._sources.indexOf(n);var t={source:n,originalLine:u.getArg(e,"line"),originalColumn:u.getArg(e,"column")},o=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",u.compareByOriginalPositions,u.getArg(e,"bias",r.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===t.source)return{line:u.getArg(i,"generatedLine",null),column:u.getArg(i,"generatedColumn",null),lastColumn:u.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},t.BasicSourceMapConsumer=o,a.prototype=Object.create(r.prototype),a.prototype.constructor=r,a.prototype._version=3,Object.defineProperty(a.prototype,"sources",{get:function(){for(var e=[],n=0;n0&&e.column>=0)||n||t||r)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&t))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:t,original:n,name:r}))},r.prototype._serializeMappings=function(){for(var e,n,t,r=0,a=1,u=0,s=0,c=0,l=0,f="",p=this._mappings.toArray(),d=0,h=p.length;h>d;d++){if(e=p[d],e.generatedLine!==a)for(r=0;e.generatedLine!==a;)f+=";",a++;else if(d>0){if(!i.compareByGeneratedPositionsInflated(e,p[d-1]))continue;f+=","}f+=o.encode(e.generatedColumn-r),r=e.generatedColumn,null!=e.source&&(t=this._sources.indexOf(e.source),f+=o.encode(t-l),l=t,f+=o.encode(e.originalLine-1-s),s=e.originalLine-1,f+=o.encode(e.originalColumn-u),u=e.originalColumn,null!=e.name&&(n=this._names.indexOf(e.name),f+=o.encode(n-c),c=n))}return f},r.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var t=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,t)?this._sourcesContents[t]:null},this)},r.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},r.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=r},{"./array-set":3,"./base64-vlq":4,"./mapping-list":7,"./util":12}],11:[function(e,n,t){function r(e,n,t,r,o){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==n?null:n,this.source=null==t?null:t,this.name=null==o?null:o,this[s]=!0,null!=r&&this.add(r)}var o=e("./source-map-generator").SourceMapGenerator,i=e("./util"),a=/(\r?\n)/,u=10,s="$$$isSourceNode$$$";r.fromStringWithSourceMap=function(e,n,t){function o(e,n){if(null===e||void 0===e.source)u.add(n);else{var o=t?i.join(t,e.source):e.source;u.add(new r(e.originalLine,e.originalColumn,o,n,e.name))}}var u=new r,s=e.split(a),c=function(){var e=s.shift(),n=s.shift()||"";return e+n},l=1,f=0,p=null;return n.eachMapping(function(e){if(null!==p){if(!(l0&&(p&&o(p,c()),u.add(s.join(""))),n.sources.forEach(function(e){var r=n.sourceContentFor(e);null!=r&&(null!=t&&(e=i.join(t,e)),u.setSourceContent(e,r))}),u},r.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[s]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},r.prototype.prepend=function(e){if(Array.isArray(e))for(var n=e.length-1;n>=0;n--)this.prepend(e[n]);else{if(!e[s]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},r.prototype.walk=function(e){for(var n,t=0,r=this.children.length;r>t;t++)n=this.children[t],n[s]?n.walk(e):""!==n&&e(n,{source:this.source,line:this.line,column:this.column,name:this.name})},r.prototype.join=function(e){var n,t,r=this.children.length;if(r>0){for(n=[],t=0;r-1>t;t++)n.push(this.children[t]),n.push(e);n.push(this.children[t]),this.children=n}return this},r.prototype.replaceRight=function(e,n){var t=this.children[this.children.length-1];return t[s]?t.replaceRight(e,n):"string"==typeof t?this.children[this.children.length-1]=t.replace(e,n):this.children.push("".replace(e,n)),this},r.prototype.setSourceContent=function(e,n){this.sourceContents[i.toSetString(e)]=n},r.prototype.walkSourceContents=function(e){for(var n=0,t=this.children.length;t>n;n++)this.children[n][s]&&this.children[n].walkSourceContents(e);for(var r=Object.keys(this.sourceContents),n=0,t=r.length;t>n;n++)e(i.fromSetString(r[n]),this.sourceContents[r[n]])},r.prototype.toString=function(){var e="";return this.walk(function(n){e+=n}),e},r.prototype.toStringWithSourceMap=function(e){var n={code:"",line:1,column:0},t=new o(e),r=!1,i=null,a=null,s=null,c=null;return this.walk(function(e,o){n.code+=e,null!==o.source&&null!==o.line&&null!==o.column?(i===o.source&&a===o.line&&s===o.column&&c===o.name||t.addMapping({source:o.source,original:{line:o.line,column:o.column},generated:{line:n.line,column:n.column},name:o.name}),i=o.source,a=o.line,s=o.column,c=o.name,r=!0):r&&(t.addMapping({generated:{line:n.line,column:n.column}}),i=null,r=!1);for(var l=0,f=e.length;f>l;l++)e.charCodeAt(l)===u?(n.line++,n.column=0,l+1===f?(i=null,r=!1):r&&t.addMapping({source:o.source,original:{line:o.line,column:o.column},generated:{line:n.line,column:n.column},name:o.name})):n.column++}),this.walkSourceContents(function(e,n){t.setSourceContent(e,n)}),{code:n.code,map:t}},t.SourceNode=r},{"./source-map-generator":10,"./util":12}],12:[function(e,n,t){function r(e,n,t){if(n in e)return e[n];if(3===arguments.length)return t;throw new Error('"'+n+'" is a required argument.')}function o(e){var n=e.match(g);return n?{scheme:n[1],auth:n[2],host:n[3],port:n[4],path:n[5]}:null}function i(e){var n="";return e.scheme&&(n+=e.scheme+":"),n+="//",e.auth&&(n+=e.auth+"@"),e.host&&(n+=e.host),e.port&&(n+=":"+e.port),e.path&&(n+=e.path),n}function a(e){var n=e,r=o(e);if(r){if(!r.path)return e;n=r.path}for(var a,u=t.isAbsolute(n),s=n.split(/\/+/),c=0,l=s.length-1;l>=0;l--)a=s[l],"."===a?s.splice(l,1):".."===a?c++:c>0&&(""===a?(s.splice(l+1,c),c=0):(s.splice(l,2),c--));return n=s.join("/"),""===n&&(n=u?"/":"."),r?(r.path=n,i(r)):n}function u(e,n){""===e&&(e="."),""===n&&(n=".");var t=o(n),r=o(e);if(r&&(e=r.path||"/"),t&&!t.scheme)return r&&(t.scheme=r.scheme),i(t);if(t||n.match(m))return n;if(r&&!r.host&&!r.path)return r.host=n,i(r);var u="/"===n.charAt(0)?n:a(e.replace(/\/+$/,"")+"/"+n);return r?(r.path=u,i(r)):u}function s(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var t=0;0!==n.indexOf(e+"/");){var r=e.lastIndexOf("/");if(0>r)return n;if(e=e.slice(0,r),e.match(/^([^\/]+:\/)?\/*$/))return n;++t}return Array(t+1).join("../")+n.substr(e.length+1)}function c(e){return"$"+e}function l(e){return e.substr(1)}function f(e,n,t){var r=e.source-n.source;return 0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r||t?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=e.generatedLine-n.generatedLine,0!==r?r:e.name-n.name))))}function p(e,n,t){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r||t?r:(r=e.source-n.source,0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:e.name-n.name))))}function d(e,n){return e===n?0:e>n?1:-1}function h(e,n){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=d(e.source,n.source),0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:d(e.name,n.name)))))}t.getArg=r;var g=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,m=/^data:.+\,.+$/;t.urlParse=o,t.urlGenerate=i,t.normalize=a,t.join=u,t.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(g)},t.relative=s,t.toSetString=c,t.fromSetString=l,t.compareByOriginalPositions=f,t.compareByGeneratedPositionsDeflated=p,t.compareByGeneratedPositionsInflated=h},{}],13:[function(e,n,t){t.SourceMapGenerator=e("./lib/source-map-generator").SourceMapGenerator,t.SourceMapConsumer=e("./lib/source-map-consumer").SourceMapConsumer,t.SourceNode=e("./lib/source-node").SourceNode},{"./lib/source-map-consumer":9,"./lib/source-map-generator":10,"./lib/source-node":11}],14:[function(e,n,t){function r(e){for(var n=Object.create(null),t=0;t=0;)if(n[t]==e)return!0;return!1}function u(e,n){for(var t=0,r=n.length;r>t;++t)if(e(n[t]))return n[t]}function s(e,n){if(0>=n)return"";if(1==n)return e;var t=s(e,n>>1);return t+=t,1&n&&(t+=e),t}function c(e,n){Error.call(this,e),this.msg=e,this.defs=n}function l(e,n,t){e===!0&&(e={});var r=e||{};if(t)for(var o in r)r.hasOwnProperty(o)&&!n.hasOwnProperty(o)&&c.croak("`"+o+"` is not a supported option",n);for(var o in n)n.hasOwnProperty(o)&&(r[o]=e&&e.hasOwnProperty(o)?e[o]:n[o]);return r}function f(e,n){var t=0;for(var r in n)n.hasOwnProperty(r)&&(e[r]=n[r],t++);return t}function p(){}function d(e,n){e.indexOf(n)<0&&e.push(n)}function h(e,n){return e.replace(/\{(.+?)\}/g,function(e,t){return n[t]})}function g(e,n){for(var t=e.length;--t>=0;)e[t]===n&&e.splice(t,1)}function m(e,n){function t(e,t){for(var r=[],o=0,i=0,a=0;o=0})}function y(e){function n(e){if(1==e.length)return t+="return str === "+JSON.stringify(e[0])+";";t+="switch(str){";for(var n=0;n3){r.sort(function(e,n){return n.length-e.length}),t+="switch(str.length){";for(var o=0;o=0;)if(!n(e[t]))return!1;return!0}function A(){this._values=Object.create(null),this._size=0}function w(e,n,r,o){arguments.length<4&&(o=Q),n=n?n.split(/\s+/):[];var i=n;o&&o.PROPS&&(n=n.concat(o.PROPS));for(var a="return function AST_"+e+"(props){ if (props) { ",u=n.length;--u>=0;)a+="this."+n[u]+" = props."+n[u]+";";var s=o&&new o;(s&&s.initialize||r&&r.initialize)&&(a+="this.initialize();"),a+="}}";var c=new Function(a)();if(s&&(c.prototype=s,c.BASE=o),o&&o.SUBCLASSES.push(c),c.prototype.CTOR=c,c.PROPS=n||null,c.SELF_PROPS=i,c.SUBCLASSES=[],e&&(c.prototype.TYPE=c.TYPE=e),r)for(u in r)r.hasOwnProperty(u)&&(/^\$/.test(u)?c[u.substr(1)]=r[u]:c.prototype[u]=r[u]);return c.DEFMETHOD=function(e,n){this.prototype[e]=n},t["AST_"+e]=c,c}function E(e,n){e.body instanceof ee?e.body._walk(n):e.body.forEach(function(e){e._walk(n)})}function C(e){this.visit=e,this.stack=[],this.directives=Object.create(null)}function S(e){return e>=97&&122>=e||e>=65&&90>=e||e>=170&&In.letter.test(String.fromCharCode(e))}function D(e){return e>=48&&57>=e}function F(e){return D(e)||S(e)}function x(e){return In.digit.test(String.fromCharCode(e))}function k(e){return In.non_spacing_mark.test(e)||In.space_combining_mark.test(e)}function B(e){return In.connector_punctuation.test(e)}function T(e){return!$n(e)&&/^[a-z_$][a-z0-9_$]*$/i.test(e)}function O(e){return 36==e||95==e||S(e)}function M(e){var n=e.charCodeAt(0);return O(n)||D(n)||8204==n||8205==n||k(e)||B(e)||x(n)}function $(e){return/^[a-z_$][a-z0-9_$]*$/i.test(e)}function R(e){if(Nn.test(e))return parseInt(e.substr(2),16);if(Pn.test(e))return parseInt(e.substr(1),8);var n=parseFloat(e);return n==e?n:void 0}function L(e,n,t,r,o){this.message=e,this.filename=n,this.line=t,this.col=r,this.pos=o,this.stack=(new Error).stack}function N(e,n,t,r,o){throw new L(e,n,t,r,o)}function P(e,n,t){return e.type==n&&(null==t||e.value==t)}function q(e,n,t,r){function o(){return S.text.charAt(S.pos)}function i(e,n){var t=S.text.charAt(S.pos++);if(e&&!t)throw Gn;return"\r\n\u2028\u2029".indexOf(t)>=0?(S.newline_before=S.newline_before||!n,++S.line,S.col=0,n||"\r"!=t||"\n"!=o()||(++S.pos,t="\n")):++S.col,t}function a(e){for(;e-- >0;)i()}function u(e){return S.text.substr(S.pos,e.length)==e}function s(e,n){var t=S.text.indexOf(e,S.pos);if(n&&-1==t)throw Gn;return t}function c(){S.tokline=S.line,S.tokcol=S.col,S.tokpos=S.pos}function l(t,r,o){S.regex_allowed="operator"==t&&!Wn(r)||"keyword"==t&&Rn(r)||"punc"==t&&zn(r),x="punc"==t&&"."==r;var i={type:t,value:r,line:S.tokline,col:S.tokcol,pos:S.tokpos,endline:S.line, -endcol:S.col,endpos:S.pos,nlb:S.newline_before,file:n};if(/^(?:num|string|regexp)$/i.test(t)&&(i.raw=e.substring(i.pos,i.endpos)),!o){i.comments_before=S.comments_before,S.comments_before=[];for(var a=0,u=i.comments_before.length;u>a;a++)i.nlb=i.nlb||i.comments_before[a].nlb}return S.newline_before=!1,new Z(i)}function f(){for(var e;jn(e=o())||"\u2028"==e||"\u2029"==e;)i()}function p(e){for(var n,t="",r=0;(n=o())&&e(n,r++);)t+=i();return t}function d(e){N(e,n,S.tokline,S.tokcol,S.tokpos)}function h(e){var n=!1,t=!1,r=!1,o="."==e,i=p(function(i,a){var u=i.charCodeAt(0);switch(u){case 120:case 88:return r?!1:r=!0;case 101:case 69:return r?!0:n?!1:n=t=!0;case 45:return t||0==a&&!e;case 43:return t;case t=!1,46:return o||r||n?!1:o=!0}return F(u)});e&&(i=e+i);var a=R(i);return isNaN(a)?void d("Invalid syntax: "+i):l("num",a)}function g(e){var n=i(!0,e);switch(n.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return" ";case 98:return"\b";case 118:return"\x0B";case 102:return"\f";case 48:return"\x00";case 120:return String.fromCharCode(m(2));case 117:return String.fromCharCode(m(4));case 10:return"";case 13:if("\n"==o())return i(!0,e),""}return n}function m(e){for(var n=0;e>0;--e){var t=parseInt(i(!0),16);isNaN(t)&&d("Invalid hex-character pattern in string"),n=n<<4|t}return n}function _(e){var n,t=S.regex_allowed,r=s("\n");return-1==r?(n=S.text.substr(S.pos),S.pos=S.text.length):(n=S.text.substring(S.pos,r),S.pos=r),S.col=S.tokcol+(S.pos-S.tokpos),S.comments_before.push(l(e,n,!0)),S.regex_allowed=t,C()}function v(){for(var e,n,t=!1,r="",a=!1;null!=(e=o());)if(t)"u"!=e&&d("Expecting UnicodeEscapeSequence -- uXXXX"),e=g(),M(e)||d("Unicode char: "+e.charCodeAt(0)+" is not valid in identifier"),r+=e,t=!1;else if("\\"==e)a=t=!0,i();else{if(!M(e))break;r+=i()}return On(r)&&a&&(n=r.charCodeAt(0).toString(16).toUpperCase(),r="\\u"+"0000".substr(n.length)+n+r.slice(1)),r}function y(e){function n(e){if(!o())return e;var t=e+o();return qn(t)?(i(),n(t)):e}return l("operator",n(e||i()))}function b(){switch(i(),o()){case"/":return i(),_("comment1");case"*":return i(),B()}return S.regex_allowed?T(""):y("/")}function A(){return i(),D(o().charCodeAt(0))?h("."):l("punc",".")}function w(){var e=v();return x?l("name",e):Mn(e)?l("atom",e):On(e)?qn(e)?l("operator",e):l("keyword",e):l("name",e)}function E(e,n){return function(t){try{return n(t)}catch(r){if(r!==Gn)throw r;d(e)}}}function C(e){if(null!=e)return T(e);if(f(),c(),t){if(u("")&&S.newline_before)return a(3),_("comment4")}var n=o();if(!n)return l("eof");var s=n.charCodeAt(0);switch(s){case 34:case 39:return k(n);case 46:return A();case 47:return b()}return D(s)?h():Hn(n)?l("punc",i()):Ln(n)?y():92==s||O(s)?w():r&&0==S.pos&&u("#!")?(a(2),_("comment5")):void d("Unexpected character '"+n+"'")}var S={text:e,filename:n,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:!1,regex_allowed:!1,comments_before:[]},x=!1,k=E("Unterminated string constant",function(e){for(var n=i(),t="";;){var r=i(!0,!0);if("\\"==r){var o=0,a=null;r=p(function(e){if(e>="0"&&"7">=e){if(!a)return a=e,++o;if("3">=a&&2>=o)return++o;if(a>="4"&&1>=o)return++o}return!1}),r=o>0?String.fromCharCode(parseInt(r,8)):g(!0)}else if("\r\n\u2028\u2029".indexOf(r)>=0)d("Unterminated string constant");else if(r==n)break;t+=r}var u=l("string",t);return u.quote=e,u}),B=E("Unterminated multiline comment",function(){var e=S.regex_allowed,n=s("*/",!0),t=S.text.substring(S.pos,n),r=t.split("\n"),o=r.length;S.pos=n+2,S.line+=o-1,o>1?S.col=r[o-1].length:S.col+=r[o-1].length,S.col+=2;var i=S.newline_before=S.newline_before||t.indexOf("\n")>=0;return S.comments_before.push(l("comment2",t,!0)),S.regex_allowed=e,S.newline_before=i,C()}),T=E("Unterminated regular expression",function(e){for(var n,t=!1,r=!1;n=i(!0);)if(t)e+="\\"+n,t=!1;else if("["==n)r=!0,e+=n;else if("]"==n&&r)r=!1,e+=n;else{if("/"==n&&!r)break;"\\"==n?t=!0:e+=n}var o=v();try{return l("regexp",new RegExp(e,o))}catch(a){d(a.message)}});return C.context=function(e){return e&&(S=e),S},C}function j(e,n){function t(e,n){return P(I.token,e,n)}function r(){return I.peeked||(I.peeked=I.input())}function o(){return I.prev=I.token,I.peeked?(I.token=I.peeked,I.peeked=null):I.token=I.input(),I.in_directives=I.in_directives&&("string"==I.token.type||t("punc",";")),I.token}function i(){return I.prev}function a(e,n,t,r){var o=I.input.context();N(e,o.filename,null!=n?n:o.tokline,null!=t?t:o.tokcol,null!=r?r:o.tokpos)}function s(e,n){a(n,e.line,e.col)}function c(e){null==e&&(e=I.token),s(e,"Unexpected token: "+e.type+" ("+e.value+")")}function f(e,n){return t(e,n)?o():void s(I.token,"Unexpected token "+I.token.type+" «"+I.token.value+"», expected "+e+" «"+n+"»")}function p(e){return f("punc",e)}function d(){return!n.strict&&(I.token.nlb||t("eof")||t("punc","}"))}function h(e){t("punc",";")?o():e||d()||c()}function g(){p("(");var e=me(!0);return p(")"),e}function m(e){return function(){var n=I.token,t=e(),r=i();return t.start=n,t.end=r,t}}function _(){(t("operator","/")||t("operator","/="))&&(I.peeked=null,I.token=I.input(I.token.value.substr(1)))}function v(){var e=R(gn);u(function(n){return n.name==e.name},I.labels)&&a("Label "+e.name+" defined twice"),p(":"),I.labels.push(e);var n=G();return I.labels.pop(),n instanceof ce||e.references.forEach(function(n){n instanceof xe&&(n=n.label.start,a("Continue label `"+e.name+"` refers to non-IterationStatement.",n.line,n.col,n.pos))}),new se({body:n,label:e})}function y(e){return new re({body:(e=me(!0),h(),e)})}function b(e){var n,t=null;d()||(t=R(_n,!0)),null!=t?(n=u(function(e){return e.name==t.name},I.labels),n||a("Undefined label "+t.name),t.thedef=n):0==I.in_loop&&a(e.TYPE+" not inside a loop or switch"),h();var r=new e({label:t});return n&&n.references.push(r),r}function A(){p("(");var e=null;return!t("punc",";")&&(e=t("keyword","var")?(o(),W(!0)):me(!0,!0),t("operator","in"))?(e instanceof Pe&&e.definitions.length>1&&a("Only one variable declaration allowed in for..in loop"),o(),E(e)):w(e)}function w(e){p(";");var n=t("punc",";")?null:me(!0);p(";");var r=t("punc",")")?null:me(!0);return p(")"),new de({init:e,condition:n,step:r,body:U(G)})}function E(e){var n=e instanceof Pe?e.definitions[0].name:null,t=me(!0);return p(")"),new he({init:e,name:n,object:t,body:U(G)})}function C(){var e=g(),n=G(),r=null;return t("keyword","else")&&(o(),r=G()),new ke({condition:e,body:n,alternative:r})}function S(){p("{");for(var e=[];!t("punc","}");)t("eof")&&c(),e.push(G());return o(),e}function D(){p("{");for(var e,n=[],r=null,a=null;!t("punc","}");)t("eof")&&c(),t("keyword","case")?(a&&(a.end=i()),r=[],a=new Me({start:(e=I.token,o(),e),expression:me(!0),body:r}),n.push(a),p(":")):t("keyword","default")?(a&&(a.end=i()),r=[],a=new Oe({start:(e=I.token,o(),p(":"),e),body:r}),n.push(a)):(r||c(),r.push(G()));return a&&(a.end=i()),o(),n}function F(){var e=S(),n=null,r=null;if(t("keyword","catch")){var u=I.token;o(),p("(");var s=R(hn);p(")"),n=new Re({start:u,argname:s,body:S(),end:i()})}if(t("keyword","finally")){var u=I.token;o(),r=new Le({start:u,body:S(),end:i()})}return n||r||a("Missing catch/finally blocks"),new $e({body:e,bcatch:n,bfinally:r})}function x(e,n){for(var r=[];r.push(new je({start:I.token,name:R(n?ln:cn),value:t("operator","=")?(o(),me(!1,e)):null,end:i()})),t("punc",",");)o();return r}function k(){var e,n=I.token;switch(n.type){case"name":case"keyword":e=M(mn);break;case"num":e=new An({start:n,end:n,value:n.value});break;case"string":e=new bn({start:n,end:n,value:n.value,quote:n.quote});break;case"regexp":e=new wn({start:n,end:n,value:n.value});break;case"atom":switch(n.value){case"false":e=new Bn({start:n,end:n});break;case"true":e=new Tn({start:n,end:n});break;case"null":e=new Cn({start:n,end:n})}break;case"operator":if(!$(n.value))throw new L("Invalid getter/setter name: "+n.value,n.file,n.line,n.col,n.pos);e=M(mn)}return o(),e}function B(e,n,r){for(var i=!0,a=[];!t("punc",e)&&(i?i=!1:p(","),!n||!t("punc",e));)t("punc",",")&&r?a.push(new Fn({start:I.token,end:I.token})):a.push(me(!1));return o(),a}function T(){var e=I.token;switch(o(),e.type){case"num":case"string":case"name":case"operator":case"keyword":case"atom":return e.value;default:c()}}function O(){var e=I.token;switch(o(),e.type){case"name":case"operator":case"keyword":case"atom":return e.value;default:c()}}function M(e){var n=I.token.value;return new("this"==n?vn:e)({name:String(n),start:I.token,end:I.token})}function R(e,n){if(!t("name"))return n||a("Name expected"),null;var r=M(e);return o(),r}function j(e,n,t){return"++"!=n&&"--"!=n||H(t)||a("Invalid use of "+n+" operator"),new e({operator:n,expression:t})}function z(e){return oe(ee(!0),0,e)}function H(e){return n.strict?e instanceof vn?!1:e instanceof Ie||e instanceof an:!0}function U(e){++I.in_loop;var n=e();return--I.in_loop,n}n=l(n,{strict:!1,filename:null,toplevel:null,expression:!1,html5_comments:!0,bare_returns:!1,shebang:!0});var I={input:"string"==typeof e?q(e,n.filename,n.html5_comments,n.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_directives:!0,in_loop:0,labels:[]};I.token=o();var G=m(function(){var e;switch(_(),I.token.type){case"string":var u=I.in_directives,s=y();return u&&s.body instanceof bn&&!t("punc",",")?new te({start:s.body.start,end:s.body.end,quote:s.body.quote,value:s.body.value}):s;case"num":case"regexp":case"operator":case"atom":return y();case"name":return P(r(),"punc",":")?v():y();case"punc":switch(I.token.value){case"{":return new ie({start:I.token,body:S(),end:i()});case"[":case"(":return y();case";":return o(),new ae;default:c()}case"keyword":switch(e=I.token.value,o(),e){case"break":return b(Fe);case"continue":return b(xe);case"debugger":return h(),new ne;case"do":return new fe({body:U(G),condition:(f("keyword","while"),e=g(),h(!0),e)});case"while":return new pe({condition:g(),body:U(G)});case"for":return A();case"function":return V(Ae);case"if":return C();case"return":return 0!=I.in_function||n.bare_returns||a("'return' outside of function"),new Ce({value:t("punc",";")?(o(),null):d()?null:(e=me(!0),h(),e)});case"switch":return new Be({expression:g(),body:U(D)});case"throw":return I.token.nlb&&a("Illegal newline after 'throw'"),new Se({value:(e=me(!0),h(),e)});case"try":return F();case"var":return e=W(),h(),e;case"const":return e=J(),h(),e;case"with":return new ge({expression:g(),body:G()});default:c()}}}),V=function(e){var n=e===Ae,r=t("name")?R(n?pn:dn):null;return n&&!r&&c(),p("("),new e({name:r,argnames:function(e,n){for(;!t("punc",")");)e?e=!1:p(","),n.push(R(fn));return o(),n}(!0,[]),body:function(e,n){++I.in_function,I.in_directives=!0,I.in_loop=0,I.labels=[];var t=S();return--I.in_function,I.in_loop=e,I.labels=n,t}(I.in_loop,I.labels)})},W=function(e){return new Pe({start:i(),definitions:x(e,!1),end:i()})},J=function(){return new qe({start:i(),definitions:x(!1,!0),end:i()})},Y=function(e){var n=I.token;f("operator","new");var r,a=X(!1);return t("punc","(")?(o(),r=B(")")):r=[],Q(new He({start:n,expression:a,args:r,end:i()}),e)},X=function(e){if(t("operator","new"))return Y(e);var n=I.token;if(t("punc")){switch(n.value){case"(":o();var r=me(!0);return r.start=n,r.end=I.token,p(")"),Q(r,e);case"[":return Q(K(),e);case"{":return Q(Z(),e)}c()}if(t("keyword","function")){o();var a=V(be);return a.start=n,a.end=i(),Q(a,e)}return Kn[I.token.type]?Q(k(),e):void c()},K=m(function(){return p("["),new Qe({elements:B("]",!n.strict,!0)})}),Z=m(function(){p("{");for(var e=!0,r=[];!t("punc","}")&&(e?e=!1:p(","),n.strict||!t("punc","}"));){var a=I.token,u=a.type,s=T();if("name"==u&&!t("punc",":")){if("get"==s){r.push(new on({start:a,key:k(),value:V(ye),end:i()}));continue}if("set"==s){r.push(new rn({start:a,key:k(),value:V(ye),end:i()}));continue}}p(":"),r.push(new tn({start:a,quote:a.quote,key:s,value:me(!1),end:i()}))}return o(),new en({properties:r})}),Q=function(e,n){var r=e.start;if(t("punc","."))return o(),Q(new Ge({start:r,expression:e,property:O(),end:i()}),n);if(t("punc","[")){o();var a=me(!0);return p("]"),Q(new Ve({start:r,expression:e,property:a,end:i()}),n)}return n&&t("punc","(")?(o(),Q(new ze({start:r,expression:e,args:B(")"),end:i()}),!0)):e},ee=function(e){var n=I.token;if(t("operator")&&Vn(n.value)){o(),_();var r=j(Je,n.value,ee(e));return r.start=n,r.end=i(),r}for(var a=X(e);t("operator")&&Wn(I.token.value)&&!I.token.nlb;)a=j(Ye,I.token.value,a),a.start=n,a.end=I.token,o();return a},oe=function(e,n,r){var i=t("operator")?I.token.value:null;"in"==i&&r&&(i=null);var a=null!=i?Yn[i]:null;if(null!=a&&a>n){o();var u=oe(ee(!0),a,r);return oe(new Xe({start:e.start,left:e,operator:i,right:u,end:u.end}),n,r)}return e},ue=function(e){var n=I.token,r=z(e);if(t("operator","?")){o();var a=me(!1);return p(":"),new Ke({start:n,condition:r,consequent:a,alternative:me(!1,e),end:i()})}return r},le=function(e){var n=I.token,r=ue(e),u=I.token.value;if(t("operator")&&Jn(u)){if(H(r))return o(),new Ze({start:n,left:r,operator:u,right:le(e),end:i()});a("Invalid assignment")}return r},me=function(e,n){var i=I.token,a=le(n);return e&&t("punc",",")?(o(),new Ue({start:i,car:a,cdr:me(!0,n),end:r()})):a};return n.expression?me(!0):function(){for(var e=I.token,r=[];!t("eof");)r.push(G());var o=i(),a=n.toplevel;return a?(a.body=a.body.concat(r),a.end=o):a=new _e({start:e,body:r,end:o}),a}()}function z(e,n){C.call(this),this.before=e,this.after=n}function H(e,n,t){this.name=t.name,this.orig=[t],this.scope=e,this.references=[],this.global=!1,this.mangled_name=null,this.undeclared=!1,this.constant=!1,this.index=n}function U(e){function n(e,n){return e.replace(/[\u0080-\uffff]/g,function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){for(;t.length<2;)t="0"+t;return"\\x"+t}for(;t.length<4;)t="0"+t;return"\\u"+t})}function t(t,r){function o(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function i(){return'"'+t.replace(/\x22/g,'\\"')+'"'}var a=0,u=0;switch(t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,function(n){switch(n){case"\\":return"\\\\";case"\b":return"\\b";case"\f":return"\\f";case"\n":return"\\n";case"\r":return"\\r";case"\x0B":return e.screw_ie8?"\\v":"\\x0B";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case'"':return++a,'"';case"'":return++u,"'";case"\x00":return"\\x00";case"\ufeff":return"\\ufeff"}return n}),e.ascii_only&&(t=n(t)),e.quote_style){case 1:return o();case 2:return i();case 3:return"'"==r?o():i();default:return a>u?o():i()}}function r(n,r){var o=t(n,r);return e.inline_script&&(o=o.replace(/<\x2fscript([>\/\t\n\f\r ])/gi,"<\\/script$1"),o=o.replace(/\x3c!--/g,"\\x3c!--"),o=o.replace(/--\x3e/g,"--\\x3e")),o}function o(t){return t=t.toString(),e.ascii_only&&(t=n(t,!0)),t}function i(n){return s(" ",e.indent_start+A-n*e.indent_level)}function a(){return x.charAt(x.length-1)}function u(){e.max_line_len&&w>e.max_line_len&&c("\n")}function c(n){n=String(n);var t=n.charAt(0);if(F&&(F=!1,t&&!(";}".indexOf(t)<0)||/[;]$/.test(x)||(e.semicolons||k(t)?(S+=";",w++,C++):(S+="\n",C++,E++,w=0,/^\s+$/.test(n)&&(F=!0)),e.beautify||(D=!1))),!e.beautify&&e.preserve_line&&N[N.length-1])for(var r=N[N.length-1].start.line;r>E;)S+="\n",C++,E++,w=0,D=!1;if(D){var o=a();(M(o)&&(M(t)||"\\"==t)||/^[\+\-\/]$/.test(t)&&t==o)&&(S+=" ",w++,C++),D=!1}var i=n.split(/\r?\n/),u=i.length-1;E+=u,0==u?w+=i[u].length:w=i[u].length,C+=n.length,x=n,S+=n}function f(){F=!1,c(";")}function d(){return A+e.indent_level}function h(e){var n;return c("{"),$(),O(d(),function(){n=e()}),T(),c("}"),n}function g(e){c("(");var n=e();return c(")"),n}function m(e){c("[");var n=e();return c("]"),n}function _(){c(","),B()}function v(){c(":"),e.space_colon&&B()}function b(){return S}e=l(e,{indent_start:0,indent_level:4,quote_keys:!1,space_colon:!0,ascii_only:!1,unescape_regexps:!1,inline_script:!1,width:80,max_line_len:32e3,beautify:!1,source_map:null,bracketize:!1,semicolons:!0,comments:!1,shebang:!0,preserve_line:!1,screw_ie8:!1,preamble:null,quote_style:0},!0);var A=0,w=0,E=1,C=0,S="",D=!1,F=!1,x=null,k=y("( [ + * / - , ."),B=e.beautify?function(){c(" ")}:function(){D=!0},T=e.beautify?function(n){e.beautify&&c(i(n?.5:0))}:p,O=e.beautify?function(e,n){e===!0&&(e=d());var t=A;A=e;var r=n();return A=t,r}:function(e,n){return n()},$=e.beautify?function(){c("\n")}:u,R=e.beautify?function(){c(";")}:function(){F=!0},L=e.source_map?function(n,t){try{n&&e.source_map.add(n.file||"?",E,w,n.line,n.col,t||"name"!=n.type?t:n.value)}catch(r){Q.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]",{file:n.file,line:n.line,col:n.col,cline:E,ccol:w,name:t||""})}}:p;e.preamble&&c(e.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"));var N=[];return{get:b,toString:b,indent:T,indentation:function(){return A},current_width:function(){return w-A},should_break:function(){return e.width&&this.current_width()>=e.width},newline:$,print:c,space:B,comma:_,colon:v,last:function(){return x},semicolon:R,force_semicolon:f,to_ascii:n,print_name:function(e){c(o(e))},print_string:function(e,n){c(r(e,n))},next_indent:d,with_indent:O,with_block:h,with_parens:g,with_square:m,add_mapping:L,option:function(n){return e[n]},line:function(){return E},col:function(){return w},pos:function(){return C},push_node:function(e){N.push(e)},pop_node:function(){return N.pop()},stack:function(){return N},parent:function(e){return N[N.length-2-(e||0)]}}}function I(e,n){return this instanceof I?(z.call(this,this.before,this.after),void(this.options=l(e,{sequences:!n,properties:!n,dead_code:!n,drop_debugger:!n,unsafe:!1,unsafe_comps:!1,conditionals:!n,comparisons:!n,evaluate:!n,booleans:!n,loops:!n,unused:!n,hoist_funs:!n,keep_fargs:!0,keep_fnames:!1,hoist_vars:!1,if_return:!n,join_vars:!n,collapse_vars:!1,cascade:!n,side_effects:!n,pure_getters:!1,pure_funcs:null,negate_iife:!n,screw_ie8:!1,drop_console:!1,angular:!1,warnings:!0,global_defs:{}},!0))):new I(e,n)}function G(e){function n(n,o,i,a,u,s){if(r){var c=r.originalPositionFor({line:a,column:u});if(null===c.source)return;n=c.source,a=c.line,u=c.column,s=c.name||s}t.addMapping({generated:{line:o+e.dest_line_diff,column:i},original:{line:a+e.orig_line_diff,column:u},source:n,name:s})}e=l(e,{file:null,root:null,orig:null,orig_line_diff:0,dest_line_diff:0});var t=new Y.SourceMapGenerator({file:e.file,sourceRoot:e.root}),r=e.orig&&new Y.SourceMapConsumer(e.orig);return{add:n,get:function(){return t},toString:function(){return JSON.stringify(t.toJSON())}}}function V(){function e(e){d(n,e)}var n=[];return[Object,Array,Function,Number,String,Boolean,Error,Math,Date,RegExp].forEach(function(n){Object.getOwnPropertyNames(n).map(e),n.prototype&&Object.getOwnPropertyNames(n.prototype).map(e)}),n}function W(e,n){function t(e){return h.indexOf(e)>=0?!1:s.indexOf(e)>=0?!1:n.only_cache?c.props.has(e):!/^[0-9.]+$/.test(e)}function r(e){return f&&!f.test(e)?!1:s.indexOf(e)>=0?!1:c.props.has(e)||p.indexOf(e)>=0}function o(e){t(e)&&d(p,e),r(e)||d(h,e)}function i(e){if(!r(e))return e;var n=c.props.get(e);if(!n){do n=Zn(++c.cname);while(!t(n));c.props.set(e,n)}return n}function a(e){var n={};try{!function r(e){e.walk(new C(function(e){if(e instanceof Ue)return r(e.cdr),!0;if(e instanceof bn)return o(e.value),!0;if(e instanceof Ke)return r(e.consequent),r(e.alternative),!0;throw n}))}(e)}catch(t){if(t!==n)throw t}}function u(e){return e.transform(new z(function(e){return e instanceof Ue?e.cdr=u(e.cdr):e instanceof bn?e.value=i(e.value):e instanceof Ke&&(e.consequent=u(e.consequent),e.alternative=u(e.alternative)),e}))}n=l(n,{reserved:null,cache:null,only_cache:!1,regex:null});var s=n.reserved;null==s&&(s=V());var c=n.cache;null==c&&(c={cname:-1,props:new A});var f=n.regex,p=[],h=[];return e.walk(new C(function(e){e instanceof tn?o(e.key):e instanceof nn?o(e.key.name):e instanceof Ge?this.parent()instanceof Ze&&o(e.property):e instanceof Ve&&this.parent()instanceof Ze&&a(e.property)})),e.transform(new z(function(e){e instanceof tn?e.key=i(e.key):e instanceof nn?e.key.name=i(e.key.name):e instanceof Ge?e.property=i(e.property):e instanceof Ve&&(e.property=u(e.property))}))}var J=e("util"),Y=e("source-map"),X=t;c.prototype=Object.create(Error.prototype),c.prototype.constructor=c,c.croak=function(e,n){throw new c(e,n)};var K=function(){function e(e,i,a){function u(){var u=i(e[s],s),f=u instanceof r;return f&&(u=u.v),u instanceof n?(u=u.v,u instanceof t?l.push.apply(l,a?u.v.slice().reverse():u.v):l.push(u)):u!==o&&(u instanceof t?c.push.apply(c,a?u.v.slice().reverse():u.v):c.push(u)),f}var s,c=[],l=[];if(e instanceof Array)if(a){for(s=e.length;--s>=0&&!u(););c.reverse(),l.reverse()}else for(s=0;s SymbolDef for all variables/functions defined in this scope",functions:"[Object/S] like `variables`, but only lists function declarations",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"}},oe),_e=w("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Object/S] a map of name -> SymbolDef for all undeclared names"},wrap_enclose:function(e){var n=this,t=[],r=[];e.forEach(function(e){var n=e.lastIndexOf(":");t.push(e.substr(0,n)),r.push(e.substr(n+1))});var o="(function("+r.join(",")+"){ '$ORIG'; })("+t.join(",")+")";return o=j(o),o=o.transform(new z(function(e){return e instanceof te&&"$ORIG"==e.value?K.splice(n.body):void 0}))},wrap_commonjs:function(e,n){var t=this,r=[];n&&(t.figure_out_scope(),t.walk(new C(function(e){e instanceof sn&&e.definition().global&&(u(function(n){return n.name==e.name},r)||r.push(e))})));var o="(function(exports, global){ '$ORIG'; '$EXPORTS'; global['"+e+"'] = exports; }({}, (function(){return this}())))";return o=j(o),o=o.transform(new z(function(e){if(e instanceof te)switch(e.value){case"$ORIG":return K.splice(t.body);case"$EXPORTS":var n=[];return r.forEach(function(e){n.push(new re({body:new Ze({left:new Ve({expression:new mn({name:"exports"}),property:new bn({value:e.name})}),operator:"=",right:new mn(e)})}))}),K.splice(n)}}))}},me),ve=w("Lambda","name argnames uses_arguments",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg*] array of function arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array"},_walk:function(e){return e._visit(this,function(){this.name&&this.name._walk(e),this.argnames.forEach(function(n){n._walk(e)}),E(this,e)})}},me),ye=w("Accessor",null,{$documentation:"A setter/getter function. The `name` property is always null."},ve),be=w("Function",null,{$documentation:"A function expression"},ve),Ae=w("Defun",null,{$documentation:"A function definition"},ve),we=w("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},ee),Ee=w("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})}},we),Ce=w("Return",null,{$documentation:"A `return` statement"},Ee),Se=w("Throw",null,{$documentation:"A `throw` statement"},Ee),De=w("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})}},we),Fe=w("Break",null,{$documentation:"A `break` statement"},De),xe=w("Continue",null,{$documentation:"A `continue` statement"},De),ke=w("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,function(){this.condition._walk(e),this.body._walk(e),this.alternative&&this.alternative._walk(e)})}},ue),Be=w("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e),E(this,e)})}},oe),Te=w("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},oe),Oe=w("Default",null,{$documentation:"A `default` switch branch"},Te),Me=w("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e),E(this,e)})}},Te),$e=w("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,function(){E(this,e),this.bcatch&&this.bcatch._walk(e),this.bfinally&&this.bfinally._walk(e)})}},oe),Re=w("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch] symbol for the exception"},_walk:function(e){return e._visit(this,function(){this.argname._walk(e),E(this,e)})}},oe),Le=w("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},oe),Ne=w("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,function(){this.definitions.forEach(function(n){n._walk(e)})})}},ee),Pe=w("Var",null,{$documentation:"A `var` statement"},Ne),qe=w("Const",null,{$documentation:"A `const` statement"},Ne),je=w("VarDef","name value",{$documentation:"A variable declaration; only appears in a AST_Definitions node",$propdoc:{name:"[AST_SymbolVar|AST_SymbolConst] name of the variable",value:"[AST_Node?] initializer, or null of there's no initializer"},_walk:function(e){return e._visit(this,function(){this.name._walk(e),this.value&&this.value._walk(e)})}}),ze=w("Call","expression args",{$documentation:"A function call expression",$propdoc:{expression:"[AST_Node] expression to invoke as function",args:"[AST_Node*] array of arguments"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e),this.args.forEach(function(n){n._walk(e)})})}}),He=w("New",null,{$documentation:"An object instantiation. Derives from a function call since it has exactly the same properties"},ze),Ue=w("Seq","car cdr",{$documentation:"A sequence expression (two comma-separated expressions)",$propdoc:{car:"[AST_Node] first element in sequence",cdr:"[AST_Node] second element in sequence"},$cons:function(e,n){ -var t=new Ue(e);return t.car=e,t.cdr=n,t},$from_array:function(e){if(0==e.length)return null;if(1==e.length)return e[0].clone();for(var n=null,t=e.length;--t>=0;)n=Ue.cons(e[t],n);for(var r=n;r;){if(r.cdr&&!r.cdr.cdr){r.cdr=r.cdr.car;break}r=r.cdr}return n},to_array:function(){for(var e=this,n=[];e;){if(n.push(e.car),e.cdr&&!(e.cdr instanceof Ue)){n.push(e.cdr);break}e=e.cdr}return n},add:function(e){for(var n=this;n;){if(!(n.cdr instanceof Ue)){var t=Ue.cons(n.cdr,e);return n.cdr=t}n=n.cdr}},_walk:function(e){return e._visit(this,function(){this.car._walk(e),this.cdr&&this.cdr._walk(e)})}}),Ie=w("PropAccess","expression property",{$documentation:'Base class for property access expressions, i.e. `a.foo` or `a["foo"]`',$propdoc:{expression:"[AST_Node] the “container” expression",property:"[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"}}),Ge=w("Dot",null,{$documentation:"A dotted property access expression",_walk:function(e){return e._visit(this,function(){this.expression._walk(e)})}},Ie),Ve=w("Sub",null,{$documentation:'Index-style property access, i.e. `a["foo"]`',_walk:function(e){return e._visit(this,function(){this.expression._walk(e),this.property._walk(e)})}},Ie),We=w("Unary","operator expression",{$documentation:"Base class for unary expressions",$propdoc:{operator:"[string] the operator",expression:"[AST_Node] expression that this unary operator applies to"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e)})}}),Je=w("UnaryPrefix",null,{$documentation:"Unary prefix expression, i.e. `typeof i` or `++i`"},We),Ye=w("UnaryPostfix",null,{$documentation:"Unary postfix expression, i.e. `i++`"},We),Xe=w("Binary","left operator right",{$documentation:"Binary expression, i.e. `a + b`",$propdoc:{left:"[AST_Node] left-hand side expression",operator:"[string] the operator",right:"[AST_Node] right-hand side expression"},_walk:function(e){return e._visit(this,function(){this.left._walk(e),this.right._walk(e)})}}),Ke=w("Conditional","condition consequent alternative",{$documentation:"Conditional expression using the ternary operator, i.e. `a ? b : c`",$propdoc:{condition:"[AST_Node]",consequent:"[AST_Node]",alternative:"[AST_Node]"},_walk:function(e){return e._visit(this,function(){this.condition._walk(e),this.consequent._walk(e),this.alternative._walk(e)})}}),Ze=w("Assign",null,{$documentation:"An assignment expression — `a = b + 5`"},Xe),Qe=w("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,function(){this.elements.forEach(function(n){n._walk(e)})})}}),en=w("Object","properties",{$documentation:"An object literal",$propdoc:{properties:"[AST_ObjectProperty*] array of properties"},_walk:function(e){return e._visit(this,function(){this.properties.forEach(function(n){n._walk(e)})})}}),nn=w("ObjectProperty","key value",{$documentation:"Base class for literal object properties",$propdoc:{key:"[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",value:"[AST_Node] property value. For setters and getters this is an AST_Function."},_walk:function(e){return e._visit(this,function(){this.value._walk(e)})}}),tn=w("ObjectKeyVal","quote",{$documentation:"A key: value object property",$propdoc:{quote:"[string] the original quote character"}},nn),rn=w("ObjectSetter",null,{$documentation:"An object setter property"},nn),on=w("ObjectGetter",null,{$documentation:"An object getter property"},nn),an=w("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"}),un=w("SymbolAccessor",null,{$documentation:"The name of a property accessor (setter/getter function)"},an),sn=w("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",$propdoc:{init:"[AST_Node*/S] array of initializers for this declaration."}},an),cn=w("SymbolVar",null,{$documentation:"Symbol defining a variable"},sn),ln=w("SymbolConst",null,{$documentation:"A constant declaration"},sn),fn=w("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},cn),pn=w("SymbolDefun",null,{$documentation:"Symbol defining a function"},sn),dn=w("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},sn),hn=w("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},sn),gn=w("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[],this.thedef=this}},an),mn=w("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},an),_n=w("LabelRef",null,{$documentation:"Reference to a label symbol"},an),vn=w("This",null,{$documentation:"The `this` symbol"},an),yn=w("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}}),bn=w("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},yn),An=w("Number","value literal",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",literal:"[string] numeric value as string (optional)"}},yn),wn=w("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},yn),En=w("Atom",null,{$documentation:"Base class for atoms"},yn),Cn=w("Null",null,{$documentation:"The `null` atom",value:null},En),Sn=w("NaN",null,{$documentation:"The impossible value",value:NaN},En),Dn=w("Undefined",null,{$documentation:"The `undefined` value",value:void 0},En),Fn=w("Hole",null,{$documentation:"A hole in an array",value:void 0},En),xn=w("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},En),kn=w("Boolean",null,{$documentation:"Base class for booleans"},En),Bn=w("False",null,{$documentation:"The `false` atom",value:!1},kn),Tn=w("True",null,{$documentation:"The `true` atom",value:!0},kn);C.prototype={_visit:function(e,n){this.push(e);var t=this.visit(e,n?function(){n.call(e)}:p);return!t&&n&&n.call(e),this.pop(e),t},parent:function(e){return this.stack[this.stack.length-2-(e||0)]},push:function(e){e instanceof ve?this.directives=Object.create(this.directives):e instanceof te&&(this.directives[e.value]=this.directives[e.value]?"up":!0),this.stack.push(e)},pop:function(e){this.stack.pop(),e instanceof ve&&(this.directives=Object.getPrototypeOf(this.directives))},self:function(){return this.stack[this.stack.length-1]},find_parent:function(e){for(var n=this.stack,t=n.length;--t>=0;){var r=n[t];if(r instanceof e)return r}},has_directive:function(e){var n=this.directives[e];if(n)return n;var t=this.stack[this.stack.length-1];if(t instanceof me)for(var r=0;r0;){var r=e[--n];if(r instanceof ke&&r.condition===t||r instanceof Ke&&r.condition===t||r instanceof le&&r.condition===t||r instanceof de&&r.condition===t||r instanceof Je&&"!"==r.operator&&r.expression===t)return!0;if(!(r instanceof Xe)||"&&"!=r.operator&&"||"!=r.operator)return!1;t=r}},loopcontrol_target:function(e){var n=this.stack;if(e)for(var t=n.length;--t>=0;){var r=n[t];if(r instanceof se&&r.label.name==e.name)return r.body}else for(var t=n.length;--t>=0;){var r=n[t];if(r instanceof Be||r instanceof ce)return r}}};var On="break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with",Mn="false null true",$n="abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield "+Mn+" "+On,Rn="return new delete throw else case";On=y(On),$n=y($n),Rn=y(Rn),Mn=y(Mn);var Ln=y(i("+-*&%=<>!?|~^")),Nn=/^0x[0-9a-f]+$/i,Pn=/^0[0-7]+$/,qn=y(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","/=","*=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","||"]),jn=y(i("  \n\r \f\x0B​᠎              \ufeff")),zn=y(i("[{(,.;:")),Hn=y(i("[]{}(),;:")),Un=y(i("gmsiy")),In={letter:new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),digit:new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"),non_spacing_mark:new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),space_combining_mark:new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),connector_punctuation:new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")};L.prototype.toString=function(){return this.message+" (line: "+this.line+", col: "+this.col+", pos: "+this.pos+")\n\n"+this.stack};var Gn={},Vn=y(["typeof","void","delete","--","++","!","~","-","+"]),Wn=y(["--","++"]),Jn=y(["=","+=","-=","/=","*=","%=",">>=","<<=",">>>=","|=","^=","&="]),Yn=function(e,n){for(var t=0;t","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],{}),Xn=r(["for","do","while","switch"]),Kn=r(["atom","num","string","regexp","name"]);z.prototype=new C,function(e){function n(n,t){n.DEFMETHOD("transform",function(n,r){var o,i;return n.push(this),n.before&&(o=n.before(this,t,r)),o===e&&(n.after?(n.stack[n.stack.length-1]=o=this,t(o,n),i=n.after(o,r),i!==e&&(o=i)):(o=this,t(o,n))),n.pop(this),o})}function t(e,n){return K(e,function(e){return e.transform(n,!0)})}n(Q,p),n(se,function(e,n){e.label=e.label.transform(n),e.body=e.body.transform(n)}),n(re,function(e,n){e.body=e.body.transform(n)}),n(oe,function(e,n){e.body=t(e.body,n)}),n(le,function(e,n){e.condition=e.condition.transform(n),e.body=e.body.transform(n)}),n(de,function(e,n){e.init&&(e.init=e.init.transform(n)),e.condition&&(e.condition=e.condition.transform(n)),e.step&&(e.step=e.step.transform(n)),e.body=e.body.transform(n)}),n(he,function(e,n){e.init=e.init.transform(n),e.object=e.object.transform(n),e.body=e.body.transform(n)}),n(ge,function(e,n){e.expression=e.expression.transform(n),e.body=e.body.transform(n)}),n(Ee,function(e,n){e.value&&(e.value=e.value.transform(n))}),n(De,function(e,n){e.label&&(e.label=e.label.transform(n))}),n(ke,function(e,n){e.condition=e.condition.transform(n),e.body=e.body.transform(n),e.alternative&&(e.alternative=e.alternative.transform(n))}),n(Be,function(e,n){e.expression=e.expression.transform(n),e.body=t(e.body,n)}),n(Me,function(e,n){e.expression=e.expression.transform(n),e.body=t(e.body,n)}),n($e,function(e,n){e.body=t(e.body,n),e.bcatch&&(e.bcatch=e.bcatch.transform(n)),e.bfinally&&(e.bfinally=e.bfinally.transform(n))}),n(Re,function(e,n){e.argname=e.argname.transform(n),e.body=t(e.body,n)}),n(Ne,function(e,n){e.definitions=t(e.definitions,n)}),n(je,function(e,n){e.name=e.name.transform(n),e.value&&(e.value=e.value.transform(n))}),n(ve,function(e,n){e.name&&(e.name=e.name.transform(n)),e.argnames=t(e.argnames,n),e.body=t(e.body,n)}),n(ze,function(e,n){e.expression=e.expression.transform(n),e.args=t(e.args,n)}),n(Ue,function(e,n){e.car=e.car.transform(n),e.cdr=e.cdr.transform(n)}),n(Ge,function(e,n){e.expression=e.expression.transform(n)}),n(Ve,function(e,n){e.expression=e.expression.transform(n),e.property=e.property.transform(n)}),n(We,function(e,n){e.expression=e.expression.transform(n)}),n(Xe,function(e,n){e.left=e.left.transform(n),e.right=e.right.transform(n)}),n(Ke,function(e,n){e.condition=e.condition.transform(n),e.consequent=e.consequent.transform(n),e.alternative=e.alternative.transform(n)}),n(Qe,function(e,n){e.elements=t(e.elements,n)}),n(en,function(e,n){e.properties=t(e.properties,n)}),n(nn,function(e,n){e.value=e.value.transform(n)})}(),H.prototype={unmangleable:function(e){return e||(e={}),this.global&&!e.toplevel||this.undeclared||!e.eval&&(this.scope.uses_eval||this.scope.uses_with)||e.keep_fnames&&(this.orig[0]instanceof dn||this.orig[0]instanceof pn)},mangle:function(e){var n=e.cache&&e.cache.props;if(this.global&&n&&n.has(this.name))this.mangled_name=n.get(this.name);else if(!this.mangled_name&&!this.unmangleable(e)){var t=this.scope;!e.screw_ie8&&this.orig[0]instanceof dn&&(t=t.parent_scope),this.mangled_name=t.next_mangled(e,this),this.global&&n&&n.set(this.name,this.mangled_name)}}},_e.DEFMETHOD("figure_out_scope",function(e){e=l(e,{screw_ie8:!1,cache:null});var n=this,t=n.parent_scope=null,r=new A,o=null,i=!1,a=0,u=new C(function(n,s){if(e.screw_ie8&&n instanceof Re){var c=t;return t=new me(n),t.init_scope_vars(a),t.parent_scope=c,s(),t=c,!0}if(n instanceof me){n.init_scope_vars(a);var c=n.parent_scope=t,l=o,f=r;return o=t=n,r=new A,++a,s(),--a,t=c,o=l,r=f,!0}if(n instanceof se){var p=n.label;if(r.has(p.name))throw new Error(h("Label {name} defined twice",p));return r.set(p.name,p),s(),r.del(p.name),!0}if(n instanceof ge)for(var d=t;d;d=d.parent_scope)d.uses_with=!0;else if(n instanceof an&&(n.scope=t),n instanceof gn&&(n.thedef=n,n.references=[]),n instanceof dn)o.def_function(n);else if(n instanceof pn)(n.scope=o.parent_scope).def_function(n);else if(n instanceof Pe)i=n.has_const_pragma();else if(n instanceof cn||n instanceof ln){var g=o.def_variable(n);g.constant=n instanceof ln||i,g.init=u.parent().value}else if(n instanceof hn)(e.screw_ie8?t:o).def_variable(n);else if(n instanceof _n){var m=r.get(n.name);if(!m)throw new Error(h("Undefined label {name} [{line},{col}]",{name:n.name,line:n.start.line,col:n.start.col}));n.thedef=m}});n.walk(u);var s=null,c=n.globals=new A,u=new C(function(e,t){if(e instanceof ve){var r=s;return s=e,t(),s=r,!0}if(e instanceof De&&e.label)return e.label.thedef.references.push(e),!0;if(e instanceof mn){var o=e.name;if("eval"==o&&u.parent()instanceof ze)for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope)i.uses_eval=!0;var a=e.scope.find_variable(o);if(a)e.thedef=a;else{var l;c.has(o)?l=c.get(o):(l=new H(n,c.size(),e),l.undeclared=!0,l.global=!0,c.set(o,l)),e.thedef=l,s&&"arguments"==o&&(s.uses_arguments=!0)}return e.reference(),!0}});n.walk(u),e.cache&&(this.cname=e.cache.cname)}),me.DEFMETHOD("init_scope_vars",function(e){this.variables=new A,this.functions=new A,this.uses_with=!1,this.uses_eval=!1,this.parent_scope=null,this.enclosed=[],this.cname=-1,this.nesting=e}),ve.DEFMETHOD("init_scope_vars",function(){me.prototype.init_scope_vars.apply(this,arguments),this.uses_arguments=!1;var e=new je({name:"arguments",start:this.start,end:this.end}),n=new H(this,this.variables.size(),e);this.variables.set(e.name,n)}),mn.DEFMETHOD("reference",function(){var e=this.definition();e.references.push(this);for(var n=this.scope;n&&(d(n.enclosed,e),n!==e.scope);)n=n.parent_scope;this.frame=this.scope.nesting-e.scope.nesting}),me.DEFMETHOD("find_variable",function(e){return e instanceof an&&(e=e.name),this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)}),me.DEFMETHOD("def_function",function(e){this.functions.set(e.name,this.def_variable(e))}),me.DEFMETHOD("def_variable",function(e){var n;return this.variables.has(e.name)?(n=this.variables.get(e.name),n.orig.push(e)):(n=new H(this,this.variables.size(),e),this.variables.set(e.name,n),n.global=!this.parent_scope),e.thedef=n}),me.DEFMETHOD("next_mangled",function(e){var n=this.enclosed;e:for(;;){var t=Zn(++this.cname);if(T(t)&&!(e.except.indexOf(t)>=0)){for(var r=n.length;--r>=0;){var o=n[r],i=o.mangled_name||o.unmangleable(e)&&o.name;if(t==i)continue e}return t}}}),be.DEFMETHOD("next_mangled",function(e,n){for(var t=n.orig[0]instanceof fn&&this.name&&this.name.definition();;){var r=ve.prototype.next_mangled.call(this,e,n);if(!t||t.mangled_name!=r)return r}}),me.DEFMETHOD("references",function(e){return e instanceof an&&(e=e.definition()),this.enclosed.indexOf(e)<0?null:e}),an.DEFMETHOD("unmangleable",function(e){return this.definition().unmangleable(e)}),un.DEFMETHOD("unmangleable",function(){return!0}),gn.DEFMETHOD("unmangleable",function(){return!1}),an.DEFMETHOD("unreferenced",function(){return 0==this.definition().references.length&&!(this.scope.uses_eval||this.scope.uses_with)}),an.DEFMETHOD("undeclared",function(){return this.definition().undeclared}),_n.DEFMETHOD("undeclared",function(){return!1}),gn.DEFMETHOD("undeclared",function(){return!1}),an.DEFMETHOD("definition",function(){return this.thedef}),an.DEFMETHOD("global",function(){return this.definition().global}),Pe.DEFMETHOD("has_const_pragma",function(){var e=this.start&&this.start.comments_before,n=e&&e[e.length-1];return n&&/@const\b/.test(n.value)}),_e.DEFMETHOD("_default_mangler_options",function(e){return l(e,{except:[],eval:!1,sort:!1,toplevel:!1,screw_ie8:!1,keep_fnames:!1})}),_e.DEFMETHOD("mangle_names",function(e){e=this._default_mangler_options(e),e.except.push("arguments");var n=-1,t=[];e.cache&&this.globals.each(function(n){e.except.indexOf(n.name)<0&&t.push(n)});var r=new C(function(o,i){if(o instanceof se){var a=n;return i(),n=a,!0}if(o instanceof me){var u=(r.parent(),[]);return o.variables.each(function(n){e.except.indexOf(n.name)<0&&u.push(n)}),e.sort&&u.sort(function(e,n){return n.references.length-e.references.length}),void t.push.apply(t,u)}if(o instanceof gn){var s;do s=Zn(++n);while(!T(s));return o.mangled_name=s,!0}return e.screw_ie8&&o instanceof hn?void t.push(o.definition()):void 0});this.walk(r),t.forEach(function(n){n.mangle(e)}),e.cache&&(e.cache.cname=this.cname)}),_e.DEFMETHOD("compute_char_frequency",function(e){e=this._default_mangler_options(e);var n=new C(function(n){n instanceof yn?Zn.consider(n.print_to_string()):n instanceof Ce?Zn.consider("return"):n instanceof Se?Zn.consider("throw"):n instanceof xe?Zn.consider("continue"):n instanceof Fe?Zn.consider("break"):n instanceof ne?Zn.consider("debugger"):n instanceof te?Zn.consider(n.value):n instanceof pe?Zn.consider("while"):n instanceof fe?Zn.consider("do while"):n instanceof ke?(Zn.consider("if"),n.alternative&&Zn.consider("else")):n instanceof Pe?Zn.consider("var"):n instanceof qe?Zn.consider("const"):n instanceof ve?Zn.consider("function"):n instanceof de?Zn.consider("for"):n instanceof he?Zn.consider("for in"):n instanceof Be?Zn.consider("switch"):n instanceof Me?Zn.consider("case"):n instanceof Oe?Zn.consider("default"):n instanceof ge?Zn.consider("with"):n instanceof rn?Zn.consider("set"+n.key):n instanceof on?Zn.consider("get"+n.key):n instanceof tn?Zn.consider(n.key):n instanceof He?Zn.consider("new"):n instanceof vn?Zn.consider("this"):n instanceof $e?Zn.consider("try"):n instanceof Re?Zn.consider("catch"):n instanceof Le?Zn.consider("finally"):n instanceof an&&n.unmangleable(e)?Zn.consider(n.name):n instanceof We||n instanceof Xe?Zn.consider(n.operator):n instanceof Ge&&Zn.consider(n.property)});this.walk(n),Zn.sort()});var Zn=function(){function e(){r=Object.create(null),t=o.split("").map(function(e){return e.charCodeAt(0)}),t.forEach(function(e){r[e]=0})}function n(e){var n="",r=54;e++;do e--,n+=String.fromCharCode(t[e%r]),e=Math.floor(e/r),r=64;while(e>0);return n}var t,r,o="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";return n.consider=function(e){for(var n=e.length;--n>=0;){var t=e.charCodeAt(n);t in r&&++r[t]}},n.sort=function(){t=m(t,function(e,n){return D(e)&&!D(n)?1:D(n)&&!D(e)?-1:r[n]-r[e]})},n.reset=e,e(),n.get=function(){return t},n.freq=function(){return r},n}();_e.DEFMETHOD("scope_warnings",function(e){e=l(e,{undeclared:!1,unreferenced:!0,assign_to_global:!0,func_arguments:!0,nested_defuns:!0,eval:!0});var n=new C(function(t){if(e.undeclared&&t instanceof mn&&t.undeclared()&&Q.warn("Undeclared symbol: {name} [{file}:{line},{col}]",{name:t.name,file:t.start.file,line:t.start.line,col:t.start.col}),e.assign_to_global){var r=null;t instanceof Ze&&t.left instanceof mn?r=t.left:t instanceof he&&t.init instanceof mn&&(r=t.init),r&&(r.undeclared()||r.global()&&r.scope!==r.definition().scope)&&Q.warn("{msg}: {name} [{file}:{line},{col}]",{msg:r.undeclared()?"Accidental global?":"Assignment to global",name:r.name,file:r.start.file,line:r.start.line,col:r.start.col})}e.eval&&t instanceof mn&&t.undeclared()&&"eval"==t.name&&Q.warn("Eval is used [{file}:{line},{col}]",t.start),e.unreferenced&&(t instanceof sn||t instanceof gn)&&!(t instanceof hn)&&t.unreferenced()&&Q.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]",{type:t instanceof gn?"Label":"Symbol",name:t.name,file:t.start.file,line:t.start.line,col:t.start.col}),e.func_arguments&&t instanceof ve&&t.uses_arguments&&Q.warn("arguments used in function {name} [{file}:{line},{col}]",{name:t.name?t.name.name:"anonymous",file:t.start.file,line:t.start.line,col:t.start.col}),e.nested_defuns&&t instanceof Ae&&!(n.parent()instanceof me)&&Q.warn('Function {name} declared in nested statement "{type}" [{file}:{line},{col}]',{name:t.name.name,type:n.parent().TYPE,file:t.start.file,line:t.start.line,col:t.start.col})});this.walk(n)}),function(){function e(e,n){e.DEFMETHOD("_codegen",n)}function n(e,t){Array.isArray(e)?e.forEach(function(e){n(e,t)}):e.DEFMETHOD("needs_parens",t)}function t(e,n,t){var r=e.length-1;e.forEach(function(e,o){e instanceof ae||(t.indent(),e.print(t),o==r&&n||(t.newline(),n&&t.newline()))})}function r(e,n){e.length>0?n.with_block(function(){t(e,!1,n)}):n.print("{}")}function o(e,n){if(n.option("bracketize"))return void d(e.body,n);if(!e.body)return n.force_semicolon();if(e.body instanceof fe&&!n.option("screw_ie8"))return void d(e.body,n);for(var t=e.body;;)if(t instanceof ke){if(!t.alternative)return void d(e.body,n);t=t.alternative}else{if(!(t instanceof ue))break;t=t.body}u(e.body,n)}function i(e,n,t){if(t)try{e.walk(new C(function(e){if(e instanceof Xe&&"in"==e.operator)throw n})),e.print(n)}catch(r){if(r!==n)throw r;e.print(n,!0)}else e.print(n)}function a(e){return[92,47,46,43,42,63,40,41,91,93,123,125,36,94,58,124,33,10,13,0,65279,8232,8233].indexOf(e)<0}function u(e,n){n.option("bracketize")?!e||e instanceof ae?n.print("{}"):e instanceof ie?e.print(n):n.with_block(function(){n.indent(),e.print(n),n.newline()}):!e||e instanceof ae?n.force_semicolon():e.print(n)}function s(e){for(var n=e.stack(),t=n.length,r=n[--t],o=n[--t];t>0;){if(o instanceof ee&&o.body===r)return!0;if(!(o instanceof Ue&&o.car===r||o instanceof ze&&o.expression===r&&!(o instanceof He)||o instanceof Ge&&o.expression===r||o instanceof Ve&&o.expression===r||o instanceof Ke&&o.condition===r||o instanceof Xe&&o.left===r||o instanceof Ye&&o.expression===r))return!1;r=o,o=n[--t]}}function c(e,n){return 0==e.args.length&&!n.option("beautify")}function l(e){for(var n=e[0],t=n.length,r=1;r=0?r.push("0x"+e.toString(16).toLowerCase(),"0"+e.toString(8)):r.push("-0x"+(-e).toString(16).toLowerCase(),"-0"+(-e).toString(8)), -(n=/^(.*?)(0+)$/.exec(e))&&r.push(n[1]+"e"+n[2].length)):(n=/^0?\.(0+)(.*)$/.exec(e))&&r.push(n[2]+"e-"+(n[1].length+n[2].length),t.substr(t.indexOf("."))),l(r)}function d(e,n){return e instanceof ie?void e.print(n):void n.with_block(function(){n.indent(),e.print(n),n.newline()})}function h(e,n){e.DEFMETHOD("add_source_map",function(e){n(this,e)})}function g(e,n){n.add_mapping(e.start)}var m=!1;Q.DEFMETHOD("print",function(e,n){function t(){r.add_comments(e),r.add_source_map(e),o(r,e)}var r=this,o=r._codegen,i=m;r instanceof te&&"use asm"==r.value&&(m=!0),e.push_node(r),n||r.needs_parens(e)?e.with_parens(t):t(),e.pop_node(),r instanceof ve&&(m=i)}),Q.DEFMETHOD("print_to_string",function(e){var n=U(e);return this.print(n),n.get()}),Q.DEFMETHOD("add_comments",function(e){var n=e.option("comments"),t=this,r=t.start;if(r&&!r._comments_dumped){r._comments_dumped=!0;var o=r.comments_before||[];t instanceof Ee&&t.value&&t.value.walk(new C(function(e){return e.start&&e.start.comments_before&&(o=o.concat(e.start.comments_before),e.start.comments_before=[]),e instanceof be||e instanceof Qe||e instanceof en?!0:void 0})),n?n.test?o=o.filter(function(e){return"comment5"==e.type||n.test(e.value)}):"function"==typeof n&&(o=o.filter(function(e){return"comment5"==e.type||n(t,e)})):o=o.filter(function(e){return"comment5"==e.type}),!e.option("beautify")&&o.length>0&&/comment[134]/.test(o[0].type)&&0!==e.col()&&o[0].nlb&&e.print("\n"),o.forEach(function(n){/comment[134]/.test(n.type)?(e.print("//"+n.value+"\n"),e.indent()):"comment2"==n.type?(e.print("/*"+n.value+"*/"),r.nlb?(e.print("\n"),e.indent()):e.space()):0===e.pos()&&"comment5"==n.type&&e.option("shebang")&&(e.print("#!"+n.value+"\n"),e.indent())})}}),n(Q,function(){return!1}),n(be,function(e){return s(e)}),n(en,function(e){return s(e)}),n([We,Dn],function(e){var n=e.parent();return n instanceof Ie&&n.expression===this}),n(Ue,function(e){var n=e.parent();return n instanceof ze||n instanceof We||n instanceof Xe||n instanceof je||n instanceof Ie||n instanceof Qe||n instanceof nn||n instanceof Ke}),n(Xe,function(e){var n=e.parent();if(n instanceof ze&&n.expression===this)return!0;if(n instanceof We)return!0;if(n instanceof Ie&&n.expression===this)return!0;if(n instanceof Xe){var t=n.operator,r=Yn[t],o=this.operator,i=Yn[o];if(r>i||r==i&&this===n.right)return!0}}),n(Ie,function(e){var n=e.parent();if(n instanceof He&&n.expression===this)try{this.walk(new C(function(e){if(e instanceof ze)throw n}))}catch(t){if(t!==n)throw t;return!0}}),n(ze,function(e){var n,t=e.parent();return t instanceof He&&t.expression===this?!0:this.expression instanceof be&&t instanceof Ie&&t.expression===this&&(n=e.parent(1))instanceof Ze&&n.left===t}),n(He,function(e){var n=e.parent();return c(this,e)&&(n instanceof Ie||n instanceof ze&&n.expression===this)?!0:void 0}),n(An,function(e){var n=e.parent();return this.getValue()<0&&n instanceof Ie&&n.expression===this?!0:void 0}),n([Ze,Ke],function(e){var n=e.parent();return n instanceof We?!0:n instanceof Xe&&!(n instanceof Ze)?!0:n instanceof ze&&n.expression===this?!0:n instanceof Ke&&n.condition===this?!0:n instanceof Ie&&n.expression===this?!0:void 0}),e(te,function(e,n){n.print_string(e.value,e.quote),n.semicolon()}),e(ne,function(e,n){n.print("debugger"),n.semicolon()}),ue.DEFMETHOD("_do_print_body",function(e){u(this.body,e)}),e(ee,function(e,n){e.body.print(n),n.semicolon()}),e(_e,function(e,n){t(e.body,!0,n),n.print("")}),e(se,function(e,n){e.label.print(n),n.colon(),e.body.print(n)}),e(re,function(e,n){e.body.print(n),n.semicolon()}),e(ie,function(e,n){r(e.body,n)}),e(ae,function(e,n){n.semicolon()}),e(fe,function(e,n){n.print("do"),n.space(),e._do_print_body(n),n.space(),n.print("while"),n.space(),n.with_parens(function(){e.condition.print(n)}),n.semicolon()}),e(pe,function(e,n){n.print("while"),n.space(),n.with_parens(function(){e.condition.print(n)}),n.space(),e._do_print_body(n)}),e(de,function(e,n){n.print("for"),n.space(),n.with_parens(function(){!e.init||e.init instanceof ae?n.print(";"):(e.init instanceof Ne?e.init.print(n):i(e.init,n,!0),n.print(";"),n.space()),e.condition?(e.condition.print(n),n.print(";"),n.space()):n.print(";"),e.step&&e.step.print(n)}),n.space(),e._do_print_body(n)}),e(he,function(e,n){n.print("for"),n.space(),n.with_parens(function(){e.init.print(n),n.space(),n.print("in"),n.space(),e.object.print(n)}),n.space(),e._do_print_body(n)}),e(ge,function(e,n){n.print("with"),n.space(),n.with_parens(function(){e.expression.print(n)}),n.space(),e._do_print_body(n)}),ve.DEFMETHOD("_do_print",function(e,n){var t=this;n||e.print("function"),t.name&&(e.space(),t.name.print(e)),e.with_parens(function(){t.argnames.forEach(function(n,t){t&&e.comma(),n.print(e)})}),e.space(),r(t.body,e)}),e(ve,function(e,n){e._do_print(n)}),Ee.DEFMETHOD("_do_print",function(e,n){e.print(n),this.value&&(e.space(),this.value.print(e)),e.semicolon()}),e(Ce,function(e,n){e._do_print(n,"return")}),e(Se,function(e,n){e._do_print(n,"throw")}),De.DEFMETHOD("_do_print",function(e,n){e.print(n),this.label&&(e.space(),this.label.print(e)),e.semicolon()}),e(Fe,function(e,n){e._do_print(n,"break")}),e(xe,function(e,n){e._do_print(n,"continue")}),e(ke,function(e,n){n.print("if"),n.space(),n.with_parens(function(){e.condition.print(n)}),n.space(),e.alternative?(o(e,n),n.space(),n.print("else"),n.space(),u(e.alternative,n)):e._do_print_body(n)}),e(Be,function(e,n){n.print("switch"),n.space(),n.with_parens(function(){e.expression.print(n)}),n.space(),e.body.length>0?n.with_block(function(){e.body.forEach(function(e,t){t&&n.newline(),n.indent(!0),e.print(n)})}):n.print("{}")}),Te.DEFMETHOD("_do_print_body",function(e){this.body.length>0&&(e.newline(),this.body.forEach(function(n){e.indent(),n.print(e),e.newline()}))}),e(Oe,function(e,n){n.print("default:"),e._do_print_body(n)}),e(Me,function(e,n){n.print("case"),n.space(),e.expression.print(n),n.print(":"),e._do_print_body(n)}),e($e,function(e,n){n.print("try"),n.space(),r(e.body,n),e.bcatch&&(n.space(),e.bcatch.print(n)),e.bfinally&&(n.space(),e.bfinally.print(n))}),e(Re,function(e,n){n.print("catch"),n.space(),n.with_parens(function(){e.argname.print(n)}),n.space(),r(e.body,n)}),e(Le,function(e,n){n.print("finally"),n.space(),r(e.body,n)}),Ne.DEFMETHOD("_do_print",function(e,n){e.print(n),e.space(),this.definitions.forEach(function(n,t){t&&e.comma(),n.print(e)});var t=e.parent(),r=t instanceof de||t instanceof he,o=r&&t.init===this;o||e.semicolon()}),e(Pe,function(e,n){e._do_print(n,"var")}),e(qe,function(e,n){e._do_print(n,"const")}),e(je,function(e,n){if(e.name.print(n),e.value){n.space(),n.print("="),n.space();var t=n.parent(1),r=t instanceof de||t instanceof he;i(e.value,n,r)}}),e(ze,function(e,n){e.expression.print(n),e instanceof He&&c(e,n)||n.with_parens(function(){e.args.forEach(function(e,t){t&&n.comma(),e.print(n)})})}),e(He,function(e,n){n.print("new"),n.space(),ze.prototype._codegen(e,n)}),Ue.DEFMETHOD("_do_print",function(e){this.car.print(e),this.cdr&&(e.comma(),e.should_break()&&(e.newline(),e.indent()),this.cdr.print(e))}),e(Ue,function(e,n){e._do_print(n)}),e(Ge,function(e,n){var t=e.expression;t.print(n),t instanceof An&&t.getValue()>=0&&(/[xa-f.]/i.test(n.last())||n.print(".")),n.print("."),n.add_mapping(e.end),n.print_name(e.property)}),e(Ve,function(e,n){e.expression.print(n),n.print("["),e.property.print(n),n.print("]")}),e(Je,function(e,n){var t=e.operator;n.print(t),(/^[a-z]/i.test(t)||/[+-]$/.test(t)&&e.expression instanceof Je&&/^[+-]/.test(e.expression.operator))&&n.space(),e.expression.print(n)}),e(Ye,function(e,n){e.expression.print(n),n.print(e.operator)}),e(Xe,function(e,n){var t=e.operator;e.left.print(n),">"==t[0]&&e.left instanceof Ye&&"--"==e.left.operator?n.print(" "):n.space(),n.print(t),("<"==t||"<<"==t)&&e.right instanceof Je&&"!"==e.right.operator&&e.right.expression instanceof Je&&"--"==e.right.expression.operator?n.print(" "):n.space(),e.right.print(n)}),e(Ke,function(e,n){e.condition.print(n),n.space(),n.print("?"),n.space(),e.consequent.print(n),n.space(),n.colon(),e.alternative.print(n)}),e(Qe,function(e,n){n.with_square(function(){var t=e.elements,r=t.length;r>0&&n.space(),t.forEach(function(e,t){t&&n.comma(),e.print(n),t===r-1&&e instanceof Fn&&n.comma()}),r>0&&n.space()})}),e(en,function(e,n){e.properties.length>0?n.with_block(function(){e.properties.forEach(function(e,t){t&&(n.print(","),n.newline()),n.indent(),e.print(n)}),n.newline()}):n.print("{}")}),e(tn,function(e,n){var t=e.key,r=e.quote;n.option("quote_keys")?n.print_string(t+""):("number"==typeof t||!n.option("beautify")&&+t+""==t)&&parseFloat(t)>=0?n.print(f(t)):($n(t)?n.option("screw_ie8"):$(t))?n.print_name(t):n.print_string(t,r),n.colon(),e.value.print(n)}),e(rn,function(e,n){n.print("set"),n.space(),e.key.print(n),e.value._do_print(n,!0)}),e(on,function(e,n){n.print("get"),n.space(),e.key.print(n),e.value._do_print(n,!0)}),e(an,function(e,n){var t=e.definition();n.print_name(t?t.mangled_name||t.name:e.name)}),e(Dn,function(e,n){n.print("void 0")}),e(Fn,p),e(xn,function(e,n){n.print("Infinity")}),e(Sn,function(e,n){n.print("NaN")}),e(vn,function(e,n){n.print("this")}),e(yn,function(e,n){n.print(e.getValue())}),e(bn,function(e,n){n.print_string(e.getValue(),e.quote)}),e(An,function(e,n){m&&null!=e.start.raw?n.print(e.start.raw):n.print(f(e.getValue()))}),e(wn,function(e,n){var t=e.getValue().toString();n.option("ascii_only")?t=n.to_ascii(t):n.option("unescape_regexps")&&(t=t.split("\\\\").map(function(e){return e.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g,function(e){var n=parseInt(e.substr(2),16);return a(n)?String.fromCharCode(n):e})}).join("\\\\")),n.print(t);var r=n.parent();r instanceof Xe&&/^in/.test(r.operator)&&r.left===e&&n.print(" ")}),h(Q,p),h(te,g),h(ne,g),h(an,g),h(we,g),h(ue,g),h(se,p),h(ve,g),h(Be,g),h(Te,g),h(ie,g),h(_e,p),h(He,g),h($e,g),h(Re,g),h(Le,g),h(Ne,g),h(yn,g),h(rn,function(e,n){n.add_mapping(e.start,e.key.name)}),h(on,function(e,n){n.add_mapping(e.start,e.key.name)}),h(nn,function(e,n){n.add_mapping(e.start,e.key)})}(),I.prototype=new z,f(I.prototype,{option:function(e){return this.options[e]},warn:function(){this.options.warnings&&Q.warn.apply(Q,arguments)},before:function(e,n,t){if(e._squeezed)return e;var r=!1;return e instanceof me&&(e=e.hoist_declarations(this),r=!0),n(e,this),e=e.optimize(this),r&&e instanceof me&&(e.drop_unused(this),n(e,this)),e._squeezed=!0,e}}),function(){function e(e,n){e.DEFMETHOD("optimize",function(e){var t=this;if(t._optimized)return t;if(e.has_directive("use asm"))return t;var r=n(t,e);return r._optimized=!0,r===t?r:r.transform(e)})}function n(e,n,t){return t||(t={}),n&&(t.start||(t.start=n.start),t.end||(t.end=n.end)),new e(t)}function t(e,t,r){if(t instanceof Q)return t.transform(e);switch(typeof t){case"string":return n(bn,r,{value:t}).optimize(e);case"number":return n(isNaN(t)?Sn:An,r,{value:t}).optimize(e);case"boolean":return n(t?Tn:Bn,r).optimize(e);case"undefined":return n(Dn,r).optimize(e);default:if(null===t)return n(Cn,r,{value:null}).optimize(e);if(t instanceof RegExp)return n(wn,r,{value:t}).optimize(e);throw new Error(h("Can't handle constant of type: {type}",{type:typeof t}))}}function r(e,t,r){return e instanceof ze&&e.expression===t&&(r instanceof Ie||r instanceof mn&&"eval"===r.name)?n(Ue,t,{car:n(An,t,{value:0}),cdr:r}):r}function o(e){if(null===e)return[];if(e instanceof ie)return e.body;if(e instanceof ae)return[];if(e instanceof ee)return[e];throw new Error("Can't convert thing to statement array")}function i(e){return null===e?!0:e instanceof ae?!0:e instanceof ie?0==e.body.length:!1}function s(e){return e instanceof Be?e:(e instanceof de||e instanceof he||e instanceof le)&&e.body instanceof ie?e.body:e}function c(e,t){function i(e,t){function o(e,n){return e instanceof mn&&(n instanceof Ze&&e===n.left||n instanceof We&&n.expression===e&&("++"==n.operator||"--"==n.operator))}function a(i,a,c){if(o(i,a))return i;var p=r(a,i,b.value);return b.value=null,d.splice(y,1),0===d.length&&(e[f]=n(ae,u),s=!0),l.walk(new C(function(e){delete e._squeezed,delete e._optimized})),t.warn("Replacing "+(c?"constant":"variable")+" "+A+" [{file}:{line},{col}]",i.start),v=!0,p}for(var u=t.self(),s=!1,c=e.length;--c>=0;){var l=e[c];if(!(l instanceof Ne)){if([l,l.body,l.alternative,l.bcatch,l.bfinally].forEach(function(e){e&&e.body&&i(e.body,t)}),0>=c)break;var f=c-1,p=e[f];if(p instanceof Ne){var d=p.definitions;if(null!=d)for(var h={},g=!1,m=!1,_={},y=d.length;--y>=0;){var b=d[y];if(null==b.value)break;var A=b.name.name;if(!A||!A.length)break;if(A in h)break;h[A]=!0;var w=u.find_variable&&u.find_variable(A);if(w&&w.references&&1===w.references.length&&"arguments"!=A){var E=w.references[0];if(E.scope.uses_eval||E.scope.uses_with)break;if(b.value.is_constant(t)){var S=new z(function(e){return e===E?a(e,S.parent(),!0):void 0});l.transform(S)}else if(!(g|=m))if(E.scope===u){var D=new C(function(e){e instanceof mn&&o(e,D.parent())&&(_[e.name]=m=!0)});b.value.walk(D);var F=!1,x=new z(function(e){if(F)return e;var n=x.parent();return e instanceof ve||e instanceof $e||e instanceof ge||e instanceof Me||e instanceof ce||n instanceof ke&&e!==n.condition||n instanceof Ke&&e!==n.condition||n instanceof Xe&&("&&"==n.operator||"||"==n.operator)&&e===n.right||n instanceof Be&&e!==n.expression?(g=F=!0,e):void 0},function(e){return F?e:e===E?(F=!0,a(e,x.parent(),!1)):(g|=e.has_side_effects(t))?(F=!0,e):m&&e instanceof mn&&e.name in _?(g=!0,F=!0,e):void 0});l.transform(x)}else g|=b.value.has_side_effects(t)}else g=!0}}}}if(s)for(var k=e.length;--k>=0;)e.length>1&&e[k]instanceof ae&&e.splice(k,1);return e}function a(e){function r(e){return/@ngInject/.test(e.value)}function o(e){return e.argnames.map(function(e){return n(bn,e,{value:e.name})})}function i(e,t){return n(Qe,e,{elements:t})}function a(e,t){return n(re,e,{body:n(Ze,e,{operator:"=",left:n(Ge,t,{expression:n(mn,t,t),property:"$inject"}),right:i(e,o(e))})})}function u(e){e&&e.args&&(e.args.forEach(function(e,n,t){var a=e.start.comments_before;e instanceof ve&&a.length&&r(a[0])&&(t[n]=i(e,o(e).concat(e)))}),e.expression&&e.expression.expression&&u(e.expression.expression))}return e.reduce(function(e,n){if(e.push(n),n.body&&n.body.args)u(n.body);else{var o=n.start,i=o.comments_before;if(i&&i.length>0){var s=i.pop();r(s)&&(n instanceof Ae?e.push(a(n,n.name)):n instanceof Ne?n.definitions.forEach(function(n){n.value&&n.value instanceof ve&&e.push(a(n.value,n.name))}):t.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]",o))}}return e},[])}function u(e){var n=[];return e.reduce(function(e,t){return t instanceof ie?(v=!0,e.push.apply(e,u(t.body))):t instanceof ae?v=!0:t instanceof te?n.indexOf(t.value)<0?(e.push(t),n.push(t.value)):v=!0:e.push(t),e},[])}function c(e,t){var r=t.self(),i=r instanceof ve,a=[];e:for(var u=e.length;--u>=0;){var c=e[u];switch(!0){case i&&c instanceof Ce&&!c.value&&0==a.length:v=!0;continue e;case c instanceof ke:if(c.body instanceof Ce){if((i&&0==a.length||a[0]instanceof Ce&&!a[0].value)&&!c.body.value&&!c.alternative){v=!0;var l=n(re,c.condition,{body:c.condition});a.unshift(l);continue e}if(a[0]instanceof Ce&&c.body.value&&a[0].value&&!c.alternative){v=!0,c=c.clone(),c.alternative=a[0],a[0]=c.transform(t);continue e}if((0==a.length||a[0]instanceof Ce)&&c.body.value&&!c.alternative&&i){v=!0,c=c.clone(),c.alternative=a[0]||n(Ce,c,{value:n(Dn,c)}),a[0]=c.transform(t);continue e}if(!c.body.value&&i){v=!0,c=c.clone(),c.condition=c.condition.negate(t),c.body=n(ie,c,{body:o(c.alternative).concat(a)}),c.alternative=null,a=[c.transform(t)];continue e}if(t.option("sequences")&&1==a.length&&i&&a[0]instanceof re&&(!c.alternative||c.alternative instanceof re)){v=!0,a.push(n(Ce,a[0],{value:n(Dn,a[0])}).transform(t)),a=o(c.alternative).concat(a),a.unshift(c);continue e}}var f=p(c.body),d=f instanceof De?t.loopcontrol_target(f.label):null;if(f&&(f instanceof Ce&&!f.value&&i||f instanceof xe&&r===s(d)||f instanceof Fe&&d instanceof ie&&r===d)){f.label&&g(f.label.thedef.references,f),v=!0;var h=o(c.body).slice(0,-1);c=c.clone(),c.condition=c.condition.negate(t),c.body=n(ie,c,{body:o(c.alternative).concat(a)}),c.alternative=n(ie,c,{body:h}),a=[c.transform(t)];continue e}var f=p(c.alternative),d=f instanceof De?t.loopcontrol_target(f.label):null;if(f&&(f instanceof Ce&&!f.value&&i||f instanceof xe&&r===s(d)||f instanceof Fe&&d instanceof ie&&r===d)){f.label&&g(f.label.thedef.references,f),v=!0,c=c.clone(),c.body=n(ie,c.body,{body:o(c.body).concat(a)}),c.alternative=n(ie,c.alternative,{body:o(c.alternative).slice(0,-1)}),a=[c.transform(t)];continue e}a.unshift(c);break;default:a.unshift(c)}}return a}function f(e,n){var t=!1,r=e.length,o=n.self();return e=e.reduce(function(e,r){if(t)l(n,r,e);else{if(r instanceof De){var i=n.loopcontrol_target(r.label);r instanceof Fe&&i instanceof ie&&s(i)===o||r instanceof xe&&s(i)===o?r.label&&g(r.label.thedef.references,r):e.push(r)}else e.push(r);p(r)&&(t=!0)}return e},[]),v=e.length!=r,e}function d(e,t){function r(){o=Ue.from_array(o),o&&i.push(n(re,o,{body:o})),o=[]}if(e.length<2)return e;var o=[],i=[];return e.forEach(function(e){e instanceof re&&o.length<2e3?o.push(e.body):(r(),i.push(e))}),r(),i=h(i,t),v=i.length!=e.length,i}function h(e,t){function r(e){o.pop();var n=i.body;return n instanceof Ue?n.add(e):n=Ue.cons(n,e),n.transform(t)}var o=[],i=null;return e.forEach(function(e){if(i)if(e instanceof de){var t={};try{i.body.walk(new C(function(e){if(e instanceof Xe&&"in"==e.operator)throw t})),!e.init||e.init instanceof Ne?e.init||(e.init=i.body,o.pop()):e.init=r(e.init)}catch(a){if(a!==t)throw a}}else e instanceof ke?e.condition=r(e.condition):e instanceof ge?e.expression=r(e.expression):e instanceof Ee&&e.value?e.value=r(e.value):e instanceof Ee?e.value=r(n(Dn,e)):e instanceof Be&&(e.expression=r(e.expression));o.push(e),i=e instanceof re?e:null}),o}function m(e,n){var t=null;return e.reduce(function(e,n){return n instanceof Ne&&t&&t.TYPE==n.TYPE?(t.definitions=t.definitions.concat(n.definitions),v=!0):n instanceof de&&t instanceof Ne&&(!n.init||n.init.TYPE==t.TYPE)?(v=!0,e.pop(),n.init?n.init.definitions=t.definitions.concat(n.init.definitions):n.init=t,e.push(n),t=n):(t=n,e.push(n)),e},[])}function _(e,t){e.forEach(function(e){e instanceof re&&(e.body=function t(e){return e.transform(new z(function(e){if(e instanceof ze&&e.expression instanceof be)return n(Je,e,{operator:"!",expression:e});if(e instanceof ze)e.expression=t(e.expression);else if(e instanceof Ue)e.car=t(e.car);else if(e instanceof Ke){var r=t(e.condition);if(r!==e.condition){e.condition=r;var o=e.consequent;e.consequent=e.alternative,e.alternative=o}}return e}))}(e.body))})}var v,y=10;do v=!1,t.option("angular")&&(e=a(e)),e=u(e),t.option("dead_code")&&(e=f(e,t)),t.option("if_return")&&(e=c(e,t)),t.option("sequences")&&(e=d(e,t)),t.option("join_vars")&&(e=m(e,t)),t.option("collapse_vars")&&(e=i(e,t));while(v&&y-- >0);return t.option("negate_iife")&&_(e,t),e}function l(e,n,t){e.warn("Dropping unreachable code [{file}:{line},{col}]",n.start),n.walk(new C(function(n){return n instanceof Ne?(e.warn("Declarations in unreachable code! [{file}:{line},{col}]",n.start),n.remove_initializers(),t.push(n),!0):n instanceof Ae?(t.push(n),!0):n instanceof me?!0:void 0}))}function f(e,n){return e.print_to_string().length>n.print_to_string().length?n:e}function p(e){return e&&e.aborts()}function _(e,t){function r(r){r=o(r),e.body instanceof ie?(e.body=e.body.clone(),e.body.body=r.concat(e.body.body.slice(1)),e.body=e.body.transform(t)):e.body=n(ie,e.body,{body:r}).transform(t),_(e,t)}var i=e.body instanceof ie?e.body.body[0]:e.body;i instanceof ke&&(i.body instanceof Fe&&t.loopcontrol_target(i.body.label)===e?(e.condition?e.condition=n(Xe,e.condition,{left:e.condition,operator:"&&",right:i.condition.negate(t)}):e.condition=i.condition.negate(t),r(i.alternative)):i.alternative instanceof Fe&&t.loopcontrol_target(i.alternative.label)===e&&(e.condition?e.condition=n(Xe,e.condition,{left:e.condition,operator:"&&",right:i.condition}):e.condition=i.condition,r(i.body)))}function v(e,n){var t=n.option("pure_getters");n.options.pure_getters=!1;var r=e.has_side_effects(n);return n.options.pure_getters=t,r}function w(e,t){return t.option("booleans")&&t.in_boolean_context()&&!e.has_side_effects(t)?n(Tn,e):e}e(Q,function(e,n){return e}),Q.DEFMETHOD("equivalent_to",function(e){return this.print_to_string()==e.print_to_string()}),function(e){var n=["!","delete"],t=["in","instanceof","==","!=","===","!==","<","<=",">=",">"];e(Q,function(){return!1}),e(Je,function(){return a(this.operator,n)}),e(Xe,function(){return a(this.operator,t)||("&&"==this.operator||"||"==this.operator)&&this.left.is_boolean()&&this.right.is_boolean()}),e(Ke,function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()}),e(Ze,function(){return"="==this.operator&&this.right.is_boolean()}),e(Ue,function(){return this.cdr.is_boolean()}),e(Tn,function(){return!0}),e(Bn,function(){return!0})}(function(e,n){e.DEFMETHOD("is_boolean",n)}),function(e){e(Q,function(){return!1}),e(bn,function(){return!0}),e(Je,function(){return"typeof"==this.operator}),e(Xe,function(e){return"+"==this.operator&&(this.left.is_string(e)||this.right.is_string(e))}),e(Ze,function(e){return("="==this.operator||"+="==this.operator)&&this.right.is_string(e)}),e(Ue,function(e){return this.cdr.is_string(e)}),e(Ke,function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)}),e(ze,function(e){return e.option("unsafe")&&this.expression instanceof mn&&"String"==this.expression.name&&this.expression.undeclared()})}(function(e,n){e.DEFMETHOD("is_string",n)}),function(e){function n(e,n){if(!n)throw new Error("Compressor must be passed");return e._eval(n)}Q.DEFMETHOD("evaluate",function(n){if(!n.option("evaluate"))return[this];try{var r=this._eval(n);return[f(t(n,r,this),this),r]}catch(o){if(o!==e)throw o;return[this]}}),Q.DEFMETHOD("is_constant",function(e){return this instanceof yn||this instanceof Je&&"!"==this.operator&&this.expression instanceof yn||this.evaluate(e).length>1}),Q.DEFMETHOD("constant_value",function(e){if(this instanceof yn)return this.value;if(this instanceof Je&&"!"==this.operator&&this.expression instanceof yn)return!this.expression.value;var n=this.evaluate(e);return n.length>1?n[1]:void 0}),e(ee,function(){throw new Error(h("Cannot evaluate a statement [{file}:{line},{col}]",this.start))}),e(be,function(){throw e}),e(Q,function(){throw e}),e(yn,function(){return this.getValue()}),e(Je,function(t){var r=this.expression;switch(this.operator){case"!":return!n(r,t);case"typeof":if(r instanceof be)return"function";if(r=n(r,t),r instanceof RegExp)throw e;return typeof r;case"void":return void n(r,t);case"~":return~n(r,t);case"-":if(r=n(r,t),0===r)throw e;return-r;case"+":return+n(r,t)}throw e}),e(Xe,function(t){var r=this.left,o=this.right;switch(this.operator){case"&&":return n(r,t)&&n(o,t);case"||":return n(r,t)||n(o,t);case"|":return n(r,t)|n(o,t);case"&":return n(r,t)&n(o,t);case"^":return n(r,t)^n(o,t);case"+":return n(r,t)+n(o,t);case"*":return n(r,t)*n(o,t);case"/":return n(r,t)/n(o,t);case"%":return n(r,t)%n(o,t);case"-":return n(r,t)-n(o,t);case"<<":return n(r,t)<>":return n(r,t)>>n(o,t);case">>>":return n(r,t)>>>n(o,t);case"==":return n(r,t)==n(o,t);case"===":return n(r,t)===n(o,t);case"!=":return n(r,t)!=n(o,t);case"!==":return n(r,t)!==n(o,t);case"<":return n(r,t)":return n(r,t)>n(o,t);case">=":return n(r,t)>=n(o,t);case"in":return n(r,t)in n(o,t);case"instanceof":return n(r,t)instanceof n(o,t)}throw e}),e(Ke,function(e){return n(this.condition,e)?n(this.consequent,e):n(this.alternative,e)}),e(mn,function(t){var r=this.definition();if(r&&r.constant&&r.init)return n(r.init,t);throw e}),e(Ge,function(t){if(t.option("unsafe")&&"length"==this.property){var r=n(this.expression,t);if("string"==typeof r)return r.length}throw e})}(function(e,n){e.DEFMETHOD("_eval",n)}),function(e){function t(e){return n(Je,e,{operator:"!",expression:e})}e(Q,function(){return t(this)}),e(ee,function(){throw new Error("Cannot negate a statement")}),e(be,function(){return t(this)}),e(Je,function(){return"!"==this.operator?this.expression:t(this)}),e(Ue,function(e){var n=this.clone();return n.cdr=n.cdr.negate(e),n}),e(Ke,function(e){var n=this.clone();return n.consequent=n.consequent.negate(e),n.alternative=n.alternative.negate(e),f(t(this),n)}),e(Xe,function(e){var n=this.clone(),r=this.operator;if(e.option("unsafe_comps"))switch(r){case"<=":return n.operator=">",n;case"<":return n.operator=">=",n;case">=":return n.operator="<",n;case">":return n.operator="<=",n}switch(r){case"==":return n.operator="!=",n;case"!=":return n.operator="==",n;case"===":return n.operator="!==",n;case"!==":return n.operator="===",n;case"&&":return n.operator="||",n.left=n.left.negate(e),n.right=n.right.negate(e),f(t(this),n);case"||":return n.operator="&&",n.left=n.left.negate(e),n.right=n.right.negate(e),f(t(this),n)}return t(this)})}(function(e,n){e.DEFMETHOD("negate",function(e){return n.call(this,e)})}),function(e){e(Q,function(e){return!0}),e(ae,function(e){return!1}),e(yn,function(e){return!1}),e(vn,function(e){return!1}),e(ze,function(e){var n=e.option("pure_funcs");return n?"function"==typeof n?n(this):n.indexOf(this.expression.print_to_string())<0:!0}),e(oe,function(e){for(var n=this.body.length;--n>=0;)if(this.body[n].has_side_effects(e))return!0;return!1}),e(re,function(e){return this.body.has_side_effects(e)}),e(Ae,function(e){return!0}),e(be,function(e){return!1}),e(Xe,function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)}),e(Ze,function(e){return!0}),e(Ke,function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)}),e(We,function(e){return"delete"==this.operator||"++"==this.operator||"--"==this.operator||this.expression.has_side_effects(e)}),e(mn,function(e){return this.global()&&this.undeclared()}),e(en,function(e){for(var n=this.properties.length;--n>=0;)if(this.properties[n].has_side_effects(e))return!0;return!1}),e(nn,function(e){return this.value.has_side_effects(e)}),e(Qe,function(e){for(var n=this.elements.length;--n>=0;)if(this.elements[n].has_side_effects(e))return!0;return!1}),e(Ge,function(e){return e.option("pure_getters")?this.expression.has_side_effects(e):!0}),e(Ve,function(e){return e.option("pure_getters")?this.expression.has_side_effects(e)||this.property.has_side_effects(e):!0}),e(Ie,function(e){return!e.option("pure_getters")}),e(Ue,function(e){return this.car.has_side_effects(e)||this.cdr.has_side_effects(e)})}(function(e,n){e.DEFMETHOD("has_side_effects",n)}),function(e){function n(){var e=this.body.length;return e>0&&p(this.body[e-1])}e(ee,function(){return null}),e(we,function(){return this}),e(ie,n),e(Te,n),e(ke,function(){return this.alternative&&p(this.body)&&p(this.alternative)&&this})}(function(e,n){e.DEFMETHOD("aborts",n)}),e(te,function(e,t){return"up"===t.has_directive(e.value)?n(ae,e):e}),e(ne,function(e,t){return t.option("drop_debugger")?n(ae,e):e}),e(se,function(e,t){return e.body instanceof Fe&&t.loopcontrol_target(e.body.label)===e.body?n(ae,e):0==e.label.references.length?e.body:e}),e(oe,function(e,n){return e.body=c(e.body,n),e}),e(ie,function(e,t){switch(e.body=c(e.body,t),e.body.length){case 1:return e.body[0];case 0:return n(ae,e)}return e}),me.DEFMETHOD("drop_unused",function(e){var t=this;if(e.has_directive("use asm"))return t;if(e.option("unused")&&!(t instanceof _e)&&!t.uses_eval){var r=[],o=new A,i=this,u=new C(function(n,a){if(n!==t){if(n instanceof Ae)return o.add(n.name.name,n),!0;if(n instanceof Ne&&i===t)return n.definitions.forEach(function(n){n.value&&(o.add(n.name.name,n.value),n.value.has_side_effects(e)&&n.value.walk(u))}),!0;if(n instanceof mn)return d(r,n.definition()),!0;if(n instanceof me){var s=i;return i=n,a(),i=s,!0}}});t.walk(u);for(var s=0;s=0;){var f=s[l];if(!f.unreferenced())break;s.pop(),e.warn("Dropping unused function argument {name} [{file}:{line},{col}]",{name:f.name,file:f.start.file,line:f.start.line,col:f.start.col})}if(o instanceof Ae&&o!==t)return a(o.name.definition(),r)?o:(e.warn("Dropping unused function {name} [{file}:{line},{col}]",{name:o.name.name,file:o.name.start.file,line:o.name.start.line,col:o.name.start.col}),n(ae,o));if(o instanceof Ne&&!(c.parent()instanceof he)){var p=o.definitions.filter(function(n){if(a(n.name.definition(),r))return!0;var t={name:n.name.name,file:n.name.start.file,line:n.name.start.line,col:n.name.start.col};return n.value&&n.value.has_side_effects(e)?(n._unused_side_effects=!0,e.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]",t),!0):(e.warn("Dropping unused variable {name} [{file}:{line},{col}]",t),!1)});p=m(p,function(e,n){return!e.value&&n.value?-1:!n.value&&e.value?1:0});for(var d=[],l=0;l0&&(d.push(h.value),h.value=Ue.from_array(d),d=[]),++l)}return d=d.length>0?n(ie,o,{body:[n(re,o,{body:Ue.from_array(d)})]}):null,0!=p.length||d?0==p.length?u?K.splice(d.body):d:(o.definitions=p,d?(d.body.unshift(o),u?K.splice(d.body):d):o):n(ae,o)}if(o instanceof de&&(i(o,this),o.init instanceof ie)){var g=o.init.body.slice(0,-1);return o.init=o.init.body.slice(-1)[0].body,g.push(o),u?K.splice(g):n(ie,o,{body:g})}return o instanceof me&&o!==t?o:void 0});t.transform(c)}}),me.DEFMETHOD("hoist_declarations",function(e){var t=this;if(e.has_directive("use asm"))return t;var r=e.option("hoist_funs"),o=e.option("hoist_vars");if(r||o){var i=[],a=[],s=new A,c=0,l=0;t.walk(new C(function(e){return e instanceof me&&e!==t?!0:e instanceof Pe?(++l,!0):void 0})),o=o&&l>1;var f=new z(function(e){if(e!==t){if(e instanceof te)return i.push(e),n(ae,e);if(e instanceof Ae&&r)return a.push(e),n(ae,e);if(e instanceof Pe&&o){e.definitions.forEach(function(e){s.set(e.name.name,e),++c});var u=e.to_assignments(),l=f.parent();if(l instanceof he&&l.init===e){if(null==u){var p=e.definitions[0].name;return n(mn,p,p)}return u}return l instanceof de&&l.init===e?u:u?n(re,e,{body:u}):n(ae,e)}if(e instanceof me)return e}});if(t=t.transform(f),c>0){var p=[];if(s.each(function(e,n){t instanceof ve&&u(function(n){return n.name==e.name.name},t.argnames)?s.del(n):(e=e.clone(),e.value=null,p.push(e),s.set(n,e))}),p.length>0){for(var d=0;d1){if(r[1])return n(de,e,{body:e.body});if(e instanceof pe&&t.option("dead_code")){var o=[];return l(t,e.body,o),n(ie,e,{body:o})}}return e}),e(pe,function(e,t){return t.option("loops")?(e=le.prototype.optimize.call(e,t),e instanceof pe&&(_(e,t),e=n(de,e,e).transform(t)),e):e}),e(de,function(e,t){var r=e.condition;if(r&&(r=r.evaluate(t), -e.condition=r[0]),!t.option("loops"))return e;if(r&&r.length>1&&!r[1]&&t.option("dead_code")){var o=[];return e.init instanceof ee?o.push(e.init):e.init&&o.push(n(re,e.init,{body:e.init})),l(t,e.body,o),n(ie,e,{body:o})}return _(e,t),e}),e(ke,function(e,t){if(!t.option("conditionals"))return e;var r=e.condition.evaluate(t);if(e.condition=r[0],r.length>1)if(r[1]){if(t.warn("Condition always true [{file}:{line},{col}]",e.condition.start),t.option("dead_code")){var o=[];return e.alternative&&l(t,e.alternative,o),o.push(e.body),n(ie,e,{body:o}).transform(t)}}else if(t.warn("Condition always false [{file}:{line},{col}]",e.condition.start),t.option("dead_code")){var o=[];return l(t,e.body,o),e.alternative&&o.push(e.alternative),n(ie,e,{body:o}).transform(t)}i(e.alternative)&&(e.alternative=null);var a=e.condition.negate(t),u=e.condition.print_to_string().length,s=a.print_to_string().length,c=u>s;if(e.alternative&&c){c=!1,e.condition=a;var f=e.body;e.body=e.alternative||n(ae),e.alternative=f}if(i(e.body)&&i(e.alternative))return n(re,e.condition,{body:e.condition}).transform(t);if(e.body instanceof re&&e.alternative instanceof re)return n(re,e,{body:n(Ke,e,{condition:e.condition,consequent:e.body.body,alternative:e.alternative.body})}).transform(t);if(i(e.alternative)&&e.body instanceof re)return u===s&&!c&&e.condition instanceof Xe&&"||"==e.condition.operator&&(c=!0),c?n(re,e,{body:n(Xe,e,{operator:"||",left:a,right:e.body.body})}).transform(t):n(re,e,{body:n(Xe,e,{operator:"&&",left:e.condition,right:e.body.body})}).transform(t);if(e.body instanceof ae&&e.alternative&&e.alternative instanceof re)return n(re,e,{body:n(Xe,e,{operator:"||",left:e.condition,right:e.alternative.body})}).transform(t);if(e.body instanceof Ee&&e.alternative instanceof Ee&&e.body.TYPE==e.alternative.TYPE)return n(e.body.CTOR,e,{value:n(Ke,e,{condition:e.condition,consequent:e.body.value||n(Dn,e.body).optimize(t),alternative:e.alternative.value||n(Dn,e.alternative).optimize(t)})}).transform(t);if(e.body instanceof ke&&!e.body.alternative&&!e.alternative&&(e.condition=n(Xe,e.condition,{operator:"&&",left:e.condition,right:e.body.condition}).transform(t),e.body=e.body.body),p(e.body)&&e.alternative){var d=e.alternative;return e.alternative=null,n(ie,e,{body:[e,d]}).transform(t)}if(p(e.alternative)){var h=e.body;return e.body=e.alternative,e.condition=c?a:e.condition.negate(t),e.alternative=null,n(ie,e,{body:[e,h]}).transform(t)}return e}),e(Be,function(e,t){if(0==e.body.length&&t.option("conditionals"))return n(re,e,{body:e.expression}).transform(t);for(;;){var r=e.body[e.body.length-1];if(r){var o=r.body[r.body.length-1];if(o instanceof Fe&&s(t.loopcontrol_target(o.label))===e&&r.body.pop(),r instanceof Oe&&0==r.body.length){e.body.pop();continue}}break}var i=e.expression.evaluate(t);e:if(2==i.length)try{if(e.expression=i[0],!t.option("dead_code"))break e;var a=i[1],u=!1,c=!1,l=!1,f=!1,d=!1,h=new z(function(r,o,i){if(r instanceof ve||r instanceof re)return r;if(r instanceof Be&&r===e)return r=r.clone(),o(r,this),d?r:n(ie,r,{body:r.body.reduce(function(e,n){return e.concat(n.body)},[])}).transform(t);if(r instanceof ke||r instanceof $e){var s=u;return u=!c,o(r,this),u=s,r}if(r instanceof ue||r instanceof Be){var s=c;return c=!0,o(r,this),c=s,r}if(r instanceof Fe&&this.loopcontrol_target(r.label)===e)return u?(d=!0,r):c?r:(f=!0,i?K.skip:n(ae,r));if(r instanceof Te&&this.parent()===e){if(f)return K.skip;if(r instanceof Me){var h=r.expression.evaluate(t);if(h.length<2)throw e;return h[1]===a||l?(l=!0,p(r)&&(f=!0),o(r,this),r):K.skip}return o(r,this),r}});h.stack=t.stack.slice(),e=e.transform(h)}catch(g){if(g!==e)throw g}return e}),e(Me,function(e,n){return e.body=c(e.body,n),e}),e($e,function(e,n){return e.body=c(e.body,n),e}),Ne.DEFMETHOD("remove_initializers",function(){this.definitions.forEach(function(e){e.value=null})}),Ne.DEFMETHOD("to_assignments",function(){var e=this.definitions.reduce(function(e,t){if(t.value){var r=n(mn,t.name,t.name);e.push(n(Ze,t,{operator:"=",left:r,right:t.value}))}return e},[]);return 0==e.length?null:Ue.from_array(e)}),e(Ne,function(e,t){return 0==e.definitions.length?n(ae,e):e}),e(be,function(e,n){return e=ve.prototype.optimize.call(e,n),n.option("unused")&&!n.option("keep_fnames")&&e.name&&e.name.unreferenced()&&(e.name=null),e}),e(ze,function(e,r){if(r.option("unsafe")){var o=e.expression;if(o instanceof mn&&o.undeclared())switch(o.name){case"Array":if(1!=e.args.length)return n(Qe,e,{elements:e.args}).transform(r);break;case"Object":if(0==e.args.length)return n(en,e,{properties:[]});break;case"String":if(0==e.args.length)return n(bn,e,{value:""});if(e.args.length<=1)return n(Xe,e,{left:e.args[0],operator:"+",right:n(bn,e,{value:""})}).transform(r);break;case"Number":if(0==e.args.length)return n(An,e,{value:0});if(1==e.args.length)return n(Je,e,{expression:e.args[0],operator:"+"}).transform(r);case"Boolean":if(0==e.args.length)return n(Bn,e);if(1==e.args.length)return n(Je,e,{expression:n(Je,null,{expression:e.args[0],operator:"!"}),operator:"!"}).transform(r);break;case"Function":if(0==e.args.length)return n(be,e,{argnames:[],body:[]});if(b(e.args,function(e){return e instanceof bn}))try{var i="(function("+e.args.slice(0,-1).map(function(e){return e.value}).join(",")+"){"+e.args[e.args.length-1].value+"})()",a=j(i);a.figure_out_scope({screw_ie8:r.option("screw_ie8")});var u=new I(r.options);a=a.transform(u),a.figure_out_scope({screw_ie8:r.option("screw_ie8")}),a.mangle_names();var s;try{a.walk(new C(function(e){if(e instanceof ve)throw s=e,a}))}catch(c){if(c!==a)throw c}if(!s)return e;var l=s.argnames.map(function(t,r){return n(bn,e.args[r],{value:t.print_to_string()})}),i=U();return ie.prototype._codegen.call(s,s,i),i=i.toString().replace(/^\{|\}$/g,""),l.push(n(bn,e.args[e.args.length-1],{value:i})),e.args=l,e}catch(c){if(!(c instanceof L))throw console.log(c),c;r.warn("Error parsing code passed to new Function [{file}:{line},{col}]",e.args[e.args.length-1].start),r.warn(c.toString())}}else{if(o instanceof Ge&&"toString"==o.property&&0==e.args.length)return n(Xe,e,{left:n(bn,e,{value:""}),operator:"+",right:o.expression}).transform(r);if(o instanceof Ge&&o.expression instanceof Qe&&"join"==o.property){var p=0==e.args.length?",":e.args[0].evaluate(r)[1];if(null!=p){var d=o.expression.elements.reduce(function(e,n){if(n=n.evaluate(r),0==e.length||1==n.length)e.push(n);else{var o=e[e.length-1];if(2==o.length){var i=""+o[1]+p+n[1];e[e.length-1]=[t(r,i,o[0]),i]}else e.push(n)}return e},[]);if(0==d.length)return n(bn,e,{value:""});if(1==d.length)return d[0][0];if(""==p){var h;return h=d[0][0]instanceof bn||d[1][0]instanceof bn?d.shift()[0]:n(bn,e,{value:""}),d.reduce(function(e,t){return n(Xe,t[0],{operator:"+",left:e,right:t[0]})},h).transform(r)}var g=e.clone();return g.expression=g.expression.clone(),g.expression.expression=g.expression.expression.clone(),g.expression.expression.elements=d.map(function(e){return e[0]}),f(e,g)}}}}if(r.option("side_effects")&&e.expression instanceof be&&0==e.args.length&&!oe.prototype.has_side_effects.call(e.expression,r))return n(Dn,e).transform(r);if(r.option("drop_console")&&e.expression instanceof Ie){for(var m=e.expression.expression;m.expression;)m=m.expression;if(m instanceof mn&&"console"==m.name&&m.undeclared())return n(Dn,e).transform(r)}return e.evaluate(r)[0]}),e(He,function(e,t){if(t.option("unsafe")){var r=e.expression;if(r instanceof mn&&r.undeclared())switch(r.name){case"Object":case"RegExp":case"Function":case"Error":case"Array":return n(ze,e,e).transform(t)}}return e}),e(Ue,function(e,t){if(!t.option("side_effects"))return e;if(!e.car.has_side_effects(t))return r(t.parent(),e,e.cdr);if(t.option("cascade")){if(e.car instanceof Ze&&!e.car.left.has_side_effects(t)){if(e.car.left.equivalent_to(e.cdr))return e.car;if(e.cdr instanceof ze&&e.cdr.expression.equivalent_to(e.car.left))return e.cdr.expression=e.car,e.cdr}if(!e.car.has_side_effects(t)&&!e.cdr.has_side_effects(t)&&e.car.equivalent_to(e.cdr))return e.car}return e.cdr instanceof Je&&"void"==e.cdr.operator&&!e.cdr.expression.has_side_effects(t)?(e.cdr.expression=e.car,e.cdr):e.cdr instanceof Dn?n(Je,e,{operator:"void",expression:e.car}):e}),We.DEFMETHOD("lift_sequences",function(e){if(e.option("sequences")&&this.expression instanceof Ue){var n=this.expression,t=n.to_array();return this.expression=t.pop(),t.push(this),n=Ue.from_array(t).transform(e)}return this}),e(Ye,function(e,n){return e.lift_sequences(n)}),e(Je,function(e,t){e=e.lift_sequences(t);var r=e.expression;if(t.option("booleans")&&t.in_boolean_context()){switch(e.operator){case"!":if(r instanceof Je&&"!"==r.operator)return r.expression;break;case"typeof":return t.warn("Boolean expression always true [{file}:{line},{col}]",e.start),n(Tn,e)}r instanceof Xe&&"!"==e.operator&&(e=f(e,r.negate(t)))}return e.evaluate(t)[0]}),Xe.DEFMETHOD("lift_sequences",function(e){if(e.option("sequences")){if(this.left instanceof Ue){var n=this.left,t=n.to_array();return this.left=t.pop(),t.push(this),n=Ue.from_array(t).transform(e)}if(this.right instanceof Ue&&this instanceof Ze&&!v(this.left,e)){var n=this.right,t=n.to_array();return this.right=t.pop(),t.push(this),n=Ue.from_array(t).transform(e)}}return this});var E=y("== === != !== * & | ^");e(Xe,function(e,t){function o(n,r){if(r||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)){n&&(e.operator=n);var o=e.left;e.left=e.right,e.right=o}}if(E(e.operator)&&(e.right instanceof yn&&!(e.left instanceof yn)&&(e.left instanceof Xe&&Yn[e.left.operator]>=Yn[e.operator]||o(null,!0)),/^[!=]==?$/.test(e.operator))){if(e.left instanceof mn&&e.right instanceof Ke){if(e.right.consequent instanceof mn&&e.right.consequent.definition()===e.left.definition()){if(/^==/.test(e.operator))return e.right.condition;if(/^!=/.test(e.operator))return e.right.condition.negate(t)}if(e.right.alternative instanceof mn&&e.right.alternative.definition()===e.left.definition()){if(/^==/.test(e.operator))return e.right.condition.negate(t);if(/^!=/.test(e.operator))return e.right.condition}}if(e.right instanceof mn&&e.left instanceof Ke){if(e.left.consequent instanceof mn&&e.left.consequent.definition()===e.right.definition()){if(/^==/.test(e.operator))return e.left.condition;if(/^!=/.test(e.operator))return e.left.condition.negate(t)}if(e.left.alternative instanceof mn&&e.left.alternative.definition()===e.right.definition()){if(/^==/.test(e.operator))return e.left.condition.negate(t);if(/^!=/.test(e.operator))return e.left.condition}}}if(e=e.lift_sequences(t),t.option("comparisons"))switch(e.operator){case"===":case"!==":(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_boolean()&&e.right.is_boolean())&&(e.operator=e.operator.substr(0,2));case"==":case"!=":e.left instanceof bn&&"undefined"==e.left.value&&e.right instanceof Je&&"typeof"==e.right.operator&&t.option("unsafe")&&(e.right.expression instanceof mn&&e.right.expression.undeclared()||(e.right=e.right.expression,e.left=n(Dn,e.left).optimize(t),2==e.operator.length&&(e.operator+="=")))}if(t.option("conditionals"))if("&&"==e.operator){var i=e.left.evaluate(t);if(i.length>1)return i[1]?(t.warn("Condition left of && always true [{file}:{line},{col}]",e.start),r(t.parent(),e,e.right.evaluate(t)[0])):(t.warn("Condition left of && always false [{file}:{line},{col}]",e.start),r(t.parent(),e,i[0]))}else if("||"==e.operator){var i=e.left.evaluate(t);if(i.length>1)return i[1]?(t.warn("Condition left of || always true [{file}:{line},{col}]",e.start),r(t.parent(),e,i[0])):(t.warn("Condition left of || always false [{file}:{line},{col}]",e.start),r(t.parent(),e,e.right.evaluate(t)[0]))}if(t.option("booleans")&&t.in_boolean_context())switch(e.operator){case"&&":var i=e.left.evaluate(t),a=e.right.evaluate(t);if(i.length>1&&!i[1]||a.length>1&&!a[1])return t.warn("Boolean && always false [{file}:{line},{col}]",e.start),e.left.has_side_effects(t)?n(Ue,e,{car:e.left,cdr:n(Bn)}).optimize(t):n(Bn,e);if(i.length>1&&i[1])return a[0];if(a.length>1&&a[1])return i[0];break;case"||":var i=e.left.evaluate(t),a=e.right.evaluate(t);if(i.length>1&&i[1]||a.length>1&&a[1])return t.warn("Boolean || always true [{file}:{line},{col}]",e.start),e.left.has_side_effects(t)?n(Ue,e,{car:e.left,cdr:n(Tn)}).optimize(t):n(Tn,e);if(i.length>1&&!i[1])return a[0];if(a.length>1&&!a[1])return i[0];break;case"+":var i=e.left.evaluate(t),a=e.right.evaluate(t);if(i.length>1&&i[0]instanceof bn&&i[1]||a.length>1&&a[0]instanceof bn&&a[1])return t.warn("+ in boolean context always true [{file}:{line},{col}]",e.start),n(Tn,e)}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Xe)||t.parent()instanceof Ze){var u=n(Je,e,{operator:"!",expression:e.negate(t)});e=f(e,u)}switch(e.operator){case"<":o(">");break;case"<=":o(">=")}}return"+"==e.operator&&e.right instanceof bn&&""===e.right.getValue()&&e.left instanceof Xe&&"+"==e.left.operator&&e.left.is_string(t)?e.left:(t.option("evaluate")&&"+"==e.operator&&(e.left instanceof yn&&e.right instanceof Xe&&"+"==e.right.operator&&e.right.left instanceof yn&&e.right.is_string(t)&&(e=n(Xe,e,{operator:"+",left:n(bn,null,{value:""+e.left.getValue()+e.right.left.getValue(),start:e.left.start,end:e.right.left.end}),right:e.right.right})),e.right instanceof yn&&e.left instanceof Xe&&"+"==e.left.operator&&e.left.right instanceof yn&&e.left.is_string(t)&&(e=n(Xe,e,{operator:"+",left:e.left.left,right:n(bn,null,{value:""+e.left.right.getValue()+e.right.getValue(),start:e.left.right.start,end:e.right.end})})),e.left instanceof Xe&&"+"==e.left.operator&&e.left.is_string(t)&&e.left.right instanceof yn&&e.right instanceof Xe&&"+"==e.right.operator&&e.right.left instanceof yn&&e.right.is_string(t)&&(e=n(Xe,e,{operator:"+",left:n(Xe,e.left,{operator:"+",left:e.left.left,right:n(bn,null,{value:""+e.left.right.getValue()+e.right.left.getValue(),start:e.left.right.start,end:e.right.left.end})}),right:e.right.right}))),e.right instanceof Xe&&e.right.operator==e.operator&&("&&"==e.operator||"||"==e.operator)?(e.left=n(Xe,e.left,{operator:e.operator,left:e.left,right:e.right.left}),e.right=e.right.right,e.transform(t)):e.evaluate(t)[0])}),e(mn,function(e,r){function o(e,n){return n instanceof Xe&&"="===n.operator&&n.left===e}if(e.undeclared()&&!o(e,r.parent())){var i=r.option("global_defs");if(i&&i.hasOwnProperty(e.name))return t(r,i[e.name],e);switch(e.name){case"undefined":return n(Dn,e);case"NaN":return n(Sn,e).transform(r);case"Infinity":return n(xn,e).transform(r)}}return e}),e(xn,function(e,t){return n(Xe,e,{operator:"/",left:n(An,e,{value:1}),right:n(An,e,{value:0})})}),e(Dn,function(e,t){if(t.option("unsafe")){var r=t.find_parent(me),o=r.find_variable("undefined");if(o){var i=n(mn,e,{name:"undefined",scope:r,thedef:o});return i.reference(),i}}return e});var S=["+","-","/","*","%",">>","<<",">>>","|","^","&"];e(Ze,function(e,n){return e=e.lift_sequences(n),"="==e.operator&&e.left instanceof mn&&e.right instanceof Xe&&e.right.left instanceof mn&&e.right.left.name==e.left.name&&a(e.right.operator,S)&&(e.operator=e.right.operator+"=",e.right=e.right.right),e}),e(Ke,function(e,o){function i(e){return e instanceof Tn||e instanceof Je&&"!"==e.operator&&e.expression instanceof yn&&!e.expression.value}function a(e){return e instanceof Bn||e instanceof Je&&"!"==e.operator&&e.expression instanceof yn&&!!e.expression.value}if(!o.option("conditionals"))return e;if(e.condition instanceof Ue){var u=e.condition.car;return e.condition=e.condition.cdr,Ue.cons(u,e)}var s=e.condition.evaluate(o);if(s.length>1)return s[1]?(o.warn("Condition always true [{file}:{line},{col}]",e.start),r(o.parent(),e,e.consequent)):(o.warn("Condition always false [{file}:{line},{col}]",e.start),r(o.parent(),e,e.alternative));var c=s[0].negate(o);f(s[0],c)===c&&(e=n(Ke,e,{condition:c,consequent:e.alternative,alternative:e.consequent}));var l=e.consequent,p=e.alternative;if(l instanceof Ze&&p instanceof Ze&&l.operator==p.operator&&l.left.equivalent_to(p.left)&&!l.left.has_side_effects(o))return n(Ze,e,{operator:l.operator,left:l.left,right:n(Ke,e,{condition:e.condition,consequent:l.right,alternative:p.right})});if(l instanceof ze&&p.TYPE===l.TYPE&&l.args.length==p.args.length&&!l.expression.has_side_effects(o)&&l.expression.equivalent_to(p.expression)){if(0==l.args.length)return n(Ue,e,{car:e.condition,cdr:l});if(1==l.args.length)return l.args[0]=n(Ke,e,{condition:e.condition,consequent:l.args[0],alternative:p.args[0]}),l}if(l instanceof Ke&&l.alternative.equivalent_to(p))return n(Ke,e,{condition:n(Xe,e,{left:e.condition,operator:"&&",right:l.condition}),consequent:l.consequent,alternative:p});if(l.is_constant(o)&&p.is_constant(o)&&l.equivalent_to(p)){var d=l.constant_value();return e.condition.has_side_effects(o)?Ue.from_array([e.condition,t(o,d,e)]):t(o,d,e)}return i(l)&&a(p)?e.condition.is_boolean()?e.condition:(e.condition=e.condition.negate(o),n(Je,e.condition,{operator:"!",expression:e.condition})):a(l)&&i(p)?e.condition.negate(o):e}),e(kn,function(e,t){if(t.option("booleans")){var r=t.parent();return r instanceof Xe&&("=="==r.operator||"!="==r.operator)?(t.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]",{operator:r.operator,value:e.value,file:r.start.file,line:r.start.line,col:r.start.col}),n(An,e,{value:+e.value})):n(Je,e,{operator:"!",expression:n(An,e,{value:1-e.value})})}return e}),e(Ve,function(e,t){var r=e.property;if(r instanceof bn&&t.option("properties")){if(r=r.getValue(),$n(r)?t.option("screw_ie8"):$(r))return n(Ge,e,{expression:e.expression,property:r}).optimize(t);var o=parseFloat(r);isNaN(o)||o.toString()!=r||(e.property=n(An,e.property,{value:o}))}return e}),e(Ge,function(e,t){var r=e.property;return $n(r)&&!t.option("screw_ie8")?n(Ve,e,{expression:e.expression,property:n(bn,e,{value:r})}).optimize(t):e.evaluate(t)[0]}),e(Qe,w),e(en,w),e(wn,w),e(Ce,function(e,n){return e.value instanceof Dn&&(e.value=null),e})}(),function(){function e(e){return"Literal"==e.type?null!=e.raw?e.raw:e.value+"":void 0}function n(n){var t=n.loc,r=t&&t.start,o=n.range;return new Z({file:t&&t.source,line:r&&r.line,col:r&&r.column,pos:o?o[0]:n.start,endline:r&&r.line,endcol:r&&r.column,endpos:o?o[0]:n.start,raw:e(n)})}function r(n){var t=n.loc,r=t&&t.end,o=n.range;return new Z({file:t&&t.source,line:r&&r.line,col:r&&r.column,pos:o?o[1]:n.end,endline:r&&r.line,endcol:r&&r.column,endpos:o?o[1]:n.end,raw:e(n)})}function o(e,o,a){var f="function From_Moz_"+e+"(M){\n";f+="return new U2."+o.name+"({\nstart: my_start_token(M),\nend: my_end_token(M)";var p="function To_Moz_"+e+"(M){\n";p+="return {\ntype: "+JSON.stringify(e),a&&a.split(/\s*,\s*/).forEach(function(e){var n=/([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(e);if(!n)throw new Error("Can't understand property map: "+e);var t=n[1],r=n[2],o=n[3];switch(f+=",\n"+o+": ",p+=",\n"+t+": ",r){case"@":f+="M."+t+".map(from_moz)",p+="M."+o+".map(to_moz)";break;case">":f+="from_moz(M."+t+")",p+="to_moz(M."+o+")";break;case"=":f+="M."+t,p+="M."+o;break;case"%":f+="from_moz(M."+t+").body",p+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}}),f+="\n})\n}",p+="\n}\n}",f=new Function("U2","my_start_token","my_end_token","from_moz","return("+f+")")(t,n,r,i),p=new Function("to_moz","to_moz_block","return("+p+")")(s,c),l[e]=f,u(o,p)}function i(e){f.push(e);var n=null!=e?l[e.type](e):null;return f.pop(),n}function a(e,n,t){var r=e.start,o=e.end;return null!=r.pos&&null!=o.endpos&&(n.range=[r.pos,o.endpos]),r.line&&(n.loc={start:{line:r.line,column:r.col},end:o.endline?{line:o.endline,column:o.endcol}:null},r.file&&(n.loc.source=r.file)),n}function u(e,n){e.DEFMETHOD("to_mozilla_ast",function(){return a(this,n(this))})}function s(e){return null!=e?e.to_mozilla_ast():null}function c(e){return{type:"BlockStatement",body:e.body.map(s)}}var l={ExpressionStatement:function(e){var t=e.expression;return"Literal"===t.type&&"string"==typeof t.value?new te({start:n(e),end:r(e),value:t.value}):new re({start:n(e),end:r(e),body:i(t)})},TryStatement:function(e){var t=e.handlers||[e.handler];if(t.length>1||e.guardedHandlers&&e.guardedHandlers.length)throw new Error("Multiple catch clauses are not supported.");return new $e({start:n(e),end:r(e),body:i(e.block).body,bcatch:i(t[0]),bfinally:e.finalizer?new Le(i(e.finalizer)):null})},Property:function(e){var t=e.key,o="Identifier"==t.type?t.name:t.value,a={start:n(t),end:r(e.value),key:o,value:i(e.value)};switch(e.kind){case"init":return new tn(a);case"set":return a.value.name=i(t),new rn(a);case"get":return a.value.name=i(t),new on(a)}},ObjectExpression:function(e){return new en({start:n(e),end:r(e),properties:e.properties.map(function(e){return e.type="Property",i(e)})})},SequenceExpression:function(e){return Ue.from_array(e.expressions.map(i))},MemberExpression:function(e){return new(e.computed?Ve:Ge)({start:n(e),end:r(e),property:e.computed?i(e.property):e.property.name,expression:i(e.object)})},SwitchCase:function(e){return new(e.test?Me:Oe)({start:n(e),end:r(e),expression:i(e.test),body:e.consequent.map(i)})},VariableDeclaration:function(e){return new("const"===e.kind?qe:Pe)({start:n(e),end:r(e),definitions:e.declarations.map(i)})},Literal:function(e){var t=e.value,o={start:n(e),end:r(e)};if(null===t)return new Cn(o);switch(typeof t){case"string":return o.value=t,new bn(o);case"number":return o.value=t,new An(o);case"boolean":return new(t?Tn:Bn)(o);default:var i=e.regex;return i&&i.pattern?o.value=new RegExp(i.pattern,i.flags).toString():o.value=e.regex&&e.raw?e.raw:t,new wn(o)}},Identifier:function(e){var t=f[f.length-2];return new("LabeledStatement"==t.type?gn:"VariableDeclarator"==t.type&&t.id===e?"const"==t.kind?ln:cn:"FunctionExpression"==t.type?t.id===e?dn:fn:"FunctionDeclaration"==t.type?t.id===e?pn:fn:"CatchClause"==t.type?hn:"BreakStatement"==t.type||"ContinueStatement"==t.type?_n:mn)({start:n(e),end:r(e),name:e.name})}};l.UpdateExpression=l.UnaryExpression=function(e){var t="prefix"in e?e.prefix:"UnaryExpression"==e.type;return new(t?Je:Ye)({start:n(e),end:r(e),operator:e.operator,expression:i(e.argument)})},o("Program",_e,"body@body"),o("EmptyStatement",ae),o("BlockStatement",ie,"body@body"),o("IfStatement",ke,"test>condition, consequent>body, alternate>alternative"),o("LabeledStatement",se,"label>label, body>body"),o("BreakStatement",Fe,"label>label"),o("ContinueStatement",xe,"label>label"),o("WithStatement",ge,"object>expression, body>body"),o("SwitchStatement",Be,"discriminant>expression, cases@body"),o("ReturnStatement",Ce,"argument>value"),o("ThrowStatement",Se,"argument>value"),o("WhileStatement",pe,"test>condition, body>body"),o("DoWhileStatement",fe,"test>condition, body>body"),o("ForStatement",de,"init>init, test>condition, update>step, body>body"),o("ForInStatement",he,"left>init, right>object, body>body"),o("DebuggerStatement",ne),o("FunctionDeclaration",Ae,"id>name, params@argnames, body%body"),o("VariableDeclarator",je,"id>name, init>value"),o("CatchClause",Re,"param>argname, body%body"),o("ThisExpression",vn),o("ArrayExpression",Qe,"elements@elements"),o("FunctionExpression",be,"id>name, params@argnames, body%body"),o("BinaryExpression",Xe,"operator=operator, left>left, right>right"),o("LogicalExpression",Xe,"operator=operator, left>left, right>right"),o("AssignmentExpression",Ze,"operator=operator, left>left, right>right"),o("ConditionalExpression",Ke,"test>condition, consequent>consequent, alternate>alternative"),o("NewExpression",He,"callee>expression, arguments@args"),o("CallExpression",ze,"callee>expression, arguments@args"),u(te,function(e){return{type:"ExpressionStatement",expression:{type:"Literal",value:e.value}}}),u(re,function(e){return{type:"ExpressionStatement",expression:s(e.body)}}),u(Te,function(e){return{type:"SwitchCase",test:s(e.expression),consequent:e.body.map(s)}}),u($e,function(e){return{type:"TryStatement",block:c(e),handler:s(e.bcatch),guardedHandlers:[],finalizer:s(e.bfinally)}}),u(Re,function(e){return{type:"CatchClause",param:s(e.argname),guard:null,body:c(e)}}),u(Ne,function(e){return{type:"VariableDeclaration",kind:e instanceof qe?"const":"var",declarations:e.definitions.map(s)}}),u(Ue,function(e){return{type:"SequenceExpression",expressions:e.to_array().map(s)}}),u(Ie,function(e){var n=e instanceof Ve;return{type:"MemberExpression",object:s(e.expression),computed:n,property:n?s(e.property):{type:"Identifier",name:e.property}}}),u(We,function(e){return{type:"++"==e.operator||"--"==e.operator?"UpdateExpression":"UnaryExpression",operator:e.operator,prefix:e instanceof Je,argument:s(e.expression)}}),u(Xe,function(e){return{type:"&&"==e.operator||"||"==e.operator?"LogicalExpression":"BinaryExpression",left:s(e.left),operator:e.operator,right:s(e.right)}}),u(en,function(e){return{type:"ObjectExpression",properties:e.properties.map(s)}}),u(nn,function(e){var n,t=T(e.key)?{type:"Identifier",name:e.key}:{type:"Literal",value:e.key};return e instanceof tn?n="init":e instanceof on?n="get":e instanceof rn&&(n="set"),{type:"Property",kind:n,key:t,value:s(e.value)}}),u(an,function(e){var n=e.definition();return{type:"Identifier",name:n?n.mangled_name||n.name:e.name}}),u(wn,function(e){var n=e.value;return{type:"Literal",value:n,raw:n.toString(),regex:{pattern:n.source,flags:n.toString().match(/[gimuy]*$/)[0]}}}),u(yn,function(e){var n=e.value;return"number"==typeof n&&(0>n||0===n&&0>1/n)?{type:"UnaryExpression",operator:"-",prefix:!0,argument:{type:"Literal",value:-n,raw:e.start.raw}}:{type:"Literal",value:n,raw:e.start.raw}}),u(En,function(e){return{type:"Identifier",name:String(e.value)}}),kn.DEFMETHOD("to_mozilla_ast",yn.prototype.to_mozilla_ast),Cn.DEFMETHOD("to_mozilla_ast",yn.prototype.to_mozilla_ast),Fn.DEFMETHOD("to_mozilla_ast",function(){return null}),oe.DEFMETHOD("to_mozilla_ast",ie.prototype.to_mozilla_ast),ve.DEFMETHOD("to_mozilla_ast",be.prototype.to_mozilla_ast);var f=null;Q.from_mozilla_ast=function(e){var n=f;f=[];var t=i(e);return f=n,t}}(),t.Compressor=I,t.DefaultsError=c,t.Dictionary=A,t.JS_Parse_Error=L,t.MAP=K,t.OutputStream=U,t.SourceMap=G,t.TreeTransformer=z,t.TreeWalker=C,t.base54=Zn,t.defaults=l,t.mangle_properties=W,t.merge=f,t.parse=j,t.push_uniq=d,t.string_template=h,t.is_identifier=T,t.SymbolDef=H,t.sys=J,t.MOZ_SourceMap=Y,t.UglifyJS=X,t.array_to_hash=r,t.slice=o,t.characters=i,t.member=a,t.find_if=u,t.repeat_string=s,t.DefaultsError=c,t.defaults=l,t.merge=f,t.noop=p,t.MAP=K,t.push_uniq=d,t.string_template=h,t.remove=g,t.mergeSort=m,t.set_difference=_,t.set_intersection=v,t.makePredicate=y,t.all=b,t.Dictionary=A,t.DEFNODE=w,t.AST_Token=Z,t.AST_Node=Q,t.AST_Statement=ee,t.AST_Debugger=ne,t.AST_Directive=te,t.AST_SimpleStatement=re,t.walk_body=E,t.AST_Block=oe,t.AST_BlockStatement=ie,t.AST_EmptyStatement=ae,t.AST_StatementWithBody=ue,t.AST_LabeledStatement=se,t.AST_IterationStatement=ce,t.AST_DWLoop=le,t.AST_Do=fe,t.AST_While=pe,t.AST_For=de,t.AST_ForIn=he,t.AST_With=ge,t.AST_Scope=me,t.AST_Toplevel=_e,t.AST_Lambda=ve,t.AST_Accessor=ye,t.AST_Function=be,t.AST_Defun=Ae,t.AST_Jump=we,t.AST_Exit=Ee,t.AST_Return=Ce,t.AST_Throw=Se,t.AST_LoopControl=De,t.AST_Break=Fe,t.AST_Continue=xe,t.AST_If=ke,t.AST_Switch=Be,t.AST_SwitchBranch=Te,t.AST_Default=Oe,t.AST_Case=Me,t.AST_Try=$e,t.AST_Catch=Re,t.AST_Finally=Le,t.AST_Definitions=Ne,t.AST_Var=Pe,t.AST_Const=qe,t.AST_VarDef=je,t.AST_Call=ze,t.AST_New=He,t.AST_Seq=Ue,t.AST_PropAccess=Ie,t.AST_Dot=Ge,t.AST_Sub=Ve,t.AST_Unary=We,t.AST_UnaryPrefix=Je,t.AST_UnaryPostfix=Ye,t.AST_Binary=Xe,t.AST_Conditional=Ke,t.AST_Assign=Ze,t.AST_Array=Qe,t.AST_Object=en,t.AST_ObjectProperty=nn,t.AST_ObjectKeyVal=tn,t.AST_ObjectSetter=rn,t.AST_ObjectGetter=on,t.AST_Symbol=an,t.AST_SymbolAccessor=un,t.AST_SymbolDeclaration=sn,t.AST_SymbolVar=cn,t.AST_SymbolConst=ln,t.AST_SymbolFunarg=fn,t.AST_SymbolDefun=pn,t.AST_SymbolLambda=dn,t.AST_SymbolCatch=hn,t.AST_Label=gn,t.AST_SymbolRef=mn,t.AST_LabelRef=_n,t.AST_This=vn,t.AST_Constant=yn,t.AST_String=bn,t.AST_Number=An,t.AST_RegExp=wn,t.AST_Atom=En,t.AST_Null=Cn,t.AST_NaN=Sn,t.AST_Undefined=Dn,t.AST_Hole=Fn,t.AST_Infinity=xn,t.AST_Boolean=kn,t.AST_False=Bn,t.AST_True=Tn,t.TreeWalker=C,t.KEYWORDS=On,t.KEYWORDS_ATOM=Mn,t.RESERVED_WORDS=$n,t.KEYWORDS_BEFORE_EXPRESSION=Rn,t.OPERATOR_CHARS=Ln,t.RE_HEX_NUMBER=Nn,t.RE_OCT_NUMBER=Pn,t.OPERATORS=qn,t.WHITESPACE_CHARS=jn,t.PUNC_BEFORE_EXPRESSION=zn,t.PUNC_CHARS=Hn,t.REGEXP_MODIFIERS=Un,t.UNICODE=In,t.is_letter=S,t.is_digit=D,t.is_alphanumeric_char=F,t.is_unicode_digit=x,t.is_unicode_combining_mark=k,t.is_unicode_connector_punctuation=B,t.is_identifier=T,t.is_identifier_start=O,t.is_identifier_char=M,t.is_identifier_string=$,t.parse_js_number=R,t.JS_Parse_Error=L,t.js_error=N,t.is_token=P,t.EX_EOF=Gn,t.tokenizer=q,t.UNARY_PREFIX=Vn,t.UNARY_POSTFIX=Wn,t.ASSIGNMENT=Jn,t.PRECEDENCE=Yn,t.STATEMENTS_WITH_LABELS=Xn,t.ATOMIC_START_TOKEN=Kn,t.parse=j,t.TreeTransformer=z,t.SymbolDef=H,t.base54=Zn,t.OutputStream=U,t.Compressor=I,t.SourceMap=G,t.find_builtins=V,t.mangle_properties=W,t.AST_Node.warn_function=function(e){"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(e)},t.minify=function(e,n){n=X.defaults(n,{spidermonkey:!1,outSourceMap:null,sourceRoot:null,inSourceMap:null,fromString:!1,warnings:!1,mangle:{},mangleProperties:!1,nameCache:null,output:null,compress:{},parse:{}}),X.base54.reset();var t=null,r={};if(n.spidermonkey?t=X.AST_Node.from_mozilla_ast(e):("string"==typeof e&&(e=[e]),e.forEach(function(e,o){var i=n.fromString?e:fs.readFileSync(e,"utf8");r[e]=i,t=X.parse(i,{filename:n.fromString?o:e,toplevel:t,bare_returns:n.parse?n.parse.bare_returns:void 0})})),n.wrap&&(t=t.wrap_commonjs(n.wrap,n.exportAll)),n.compress){var o={warnings:n.warnings};X.merge(o,n.compress),t.figure_out_scope();var i=X.Compressor(o);t=t.transform(i)}(n.mangleProperties||n.nameCache)&&(n.mangleProperties.cache=X.readNameCache(n.nameCache,"props"),t=X.mangle_properties(t,n.mangleProperties),X.writeNameCache(n.nameCache,"props",n.mangleProperties.cache)),n.mangle&&(t.figure_out_scope(n.mangle),t.compute_char_frequency(n.mangle),t.mangle_names(n.mangle));var a=n.inSourceMap,u={};if("string"==typeof n.inSourceMap&&(a=fs.readFileSync(n.inSourceMap,"utf8")),n.outSourceMap&&(u.source_map=X.SourceMap({file:n.outSourceMap,orig:a,root:n.sourceRoot}),n.sourceMapIncludeSources))for(var s in r)r.hasOwnProperty(s)&&u.source_map.get().setSourceContent(s,r[s]);n.output&&X.merge(u,n.output);var c=X.OutputStream(u);t.print(c),n.outSourceMap&&"string"==typeof n.outSourceMap&&(c+="\n//# sourceMappingURL="+n.outSourceMap);var l=u.source_map;return l&&(l+=""),{code:c+"",map:l}},t.describe_ast=function(){function e(t){n.print("AST_"+t.TYPE);var r=t.SELF_PROPS.filter(function(e){return!/^\$/.test(e)});r.length>0&&(n.space(),n.with_parens(function(){r.forEach(function(e,t){t&&n.space(),n.print(e)})})),t.documentation&&(n.space(),n.print_string(t.documentation)),t.SUBCLASSES.length>0&&(n.space(),n.with_block(function(){t.SUBCLASSES.forEach(function(t,r){n.indent(),e(t),n.newline()})}))}var n=X.OutputStream({beautify:!0});return e(X.AST_Node),n+""}},{"source-map":13,util:16}],15:[function(e,n,t){n.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],16:[function(e,n,t){(function(n,r){function o(e,n){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),g(n)?r.showHidden=n:n&&t._extend(r,n),A(r.showHidden)&&(r.showHidden=!1),A(r.depth)&&(r.depth=2),A(r.colors)&&(r.colors=!1),A(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=i),s(r,e,r.depth)}function i(e,n){var t=o.styles[n];return t?"["+o.colors[t][0]+"m"+e+"["+o.colors[t][1]+"m":e}function a(e,n){return e}function u(e){var n={};return e.forEach(function(e,t){n[e]=!0}),n}function s(e,n,r){if(e.customInspect&&n&&D(n.inspect)&&n.inspect!==t.inspect&&(!n.constructor||n.constructor.prototype!==n)){var o=n.inspect(r,e);return y(o)||(o=s(e,o,r)),o}var i=c(e,n);if(i)return i;var a=Object.keys(n),g=u(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(n)), -S(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(n);if(0===a.length){if(D(n)){var m=n.name?": "+n.name:"";return e.stylize("[Function"+m+"]","special")}if(w(n))return e.stylize(RegExp.prototype.toString.call(n),"regexp");if(C(n))return e.stylize(Date.prototype.toString.call(n),"date");if(S(n))return l(n)}var _="",v=!1,b=["{","}"];if(h(n)&&(v=!0,b=["[","]"]),D(n)){var A=n.name?": "+n.name:"";_=" [Function"+A+"]"}if(w(n)&&(_=" "+RegExp.prototype.toString.call(n)),C(n)&&(_=" "+Date.prototype.toUTCString.call(n)),S(n)&&(_=" "+l(n)),0===a.length&&(!v||0==n.length))return b[0]+_+b[1];if(0>r)return w(n)?e.stylize(RegExp.prototype.toString.call(n),"regexp"):e.stylize("[Object]","special");e.seen.push(n);var E;return E=v?f(e,n,r,g,a):a.map(function(t){return p(e,n,r,g,t,v)}),e.seen.pop(),d(E,_,b)}function c(e,n){if(A(n))return e.stylize("undefined","undefined");if(y(n)){var t="'"+JSON.stringify(n).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(t,"string")}return v(n)?e.stylize(""+n,"number"):g(n)?e.stylize(""+n,"boolean"):m(n)?e.stylize("null","null"):void 0}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,n,t,r,o){for(var i=[],a=0,u=n.length;u>a;++a)T(n,String(a))?i.push(p(e,n,t,r,String(a),!0)):i.push("");return o.forEach(function(o){o.match(/^\d+$/)||i.push(p(e,n,t,r,o,!0))}),i}function p(e,n,t,r,o,i){var a,u,c;if(c=Object.getOwnPropertyDescriptor(n,o)||{value:n[o]},c.get?u=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(u=e.stylize("[Setter]","special")),T(r,o)||(a="["+o+"]"),u||(e.seen.indexOf(c.value)<0?(u=m(t)?s(e,c.value,null):s(e,c.value,t-1),u.indexOf("\n")>-1&&(u=i?u.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+u.split("\n").map(function(e){return" "+e}).join("\n"))):u=e.stylize("[Circular]","special")),A(a)){if(i&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+u}function d(e,n,t){var r=0,o=e.reduce(function(e,n){return r++,n.indexOf("\n")>=0&&r++,e+n.replace(/\u001b\[\d\d?m/g,"").length+1},0);return o>60?t[0]+(""===n?"":n+"\n ")+" "+e.join(",\n ")+" "+t[1]:t[0]+n+" "+e.join(", ")+" "+t[1]}function h(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function m(e){return null===e}function _(e){return null==e}function v(e){return"number"==typeof e}function y(e){return"string"==typeof e}function b(e){return"symbol"==typeof e}function A(e){return void 0===e}function w(e){return E(e)&&"[object RegExp]"===x(e)}function E(e){return"object"==typeof e&&null!==e}function C(e){return E(e)&&"[object Date]"===x(e)}function S(e){return E(e)&&("[object Error]"===x(e)||e instanceof Error)}function D(e){return"function"==typeof e}function F(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function x(e){return Object.prototype.toString.call(e)}function k(e){return 10>e?"0"+e.toString(10):e.toString(10)}function B(){var e=new Date,n=[k(e.getHours()),k(e.getMinutes()),k(e.getSeconds())].join(":");return[e.getDate(),R[e.getMonth()],n].join(" ")}function T(e,n){return Object.prototype.hasOwnProperty.call(e,n)}var O=/%[sdj%]/g;t.format=function(e){if(!y(e)){for(var n=[],t=0;t=i)return e;switch(e){case"%s":return String(r[t++]);case"%d":return Number(r[t++]);case"%j":try{return JSON.stringify(r[t++])}catch(n){return"[Circular]"}default:return e}}),u=r[t];i>t;u=r[++t])a+=m(u)||!E(u)?" "+u:" "+o(u);return a},t.deprecate=function(e,o){function i(){if(!a){if(n.throwDeprecation)throw new Error(o);n.traceDeprecation?console.trace(o):console.error(o),a=!0}return e.apply(this,arguments)}if(A(r.process))return function(){return t.deprecate(e,o).apply(this,arguments)};if(n.noDeprecation===!0)return e;var a=!1;return i};var M,$={};t.debuglog=function(e){if(A(M)&&(M=n.env.NODE_DEBUG||""),e=e.toUpperCase(),!$[e])if(new RegExp("\\b"+e+"\\b","i").test(M)){var r=n.pid;$[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else $[e]=function(){};return $[e]},t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=h,t.isBoolean=g,t.isNull=m,t.isNullOrUndefined=_,t.isNumber=v,t.isString=y,t.isSymbol=b,t.isUndefined=A,t.isRegExp=w,t.isObject=E,t.isDate=C,t.isError=S,t.isFunction=D,t.isPrimitive=F,t.isBuffer=e("./support/isBuffer");var R=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];t.log=function(){console.log("%s - %s",B(),t.format.apply(t,arguments))},t.inherits=e("inherits"),t._extend=function(e,n){if(!n||!E(n))return e;for(var t=Object.keys(n),r=t.length;r--;)e[t[r]]=n[t[r]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":15,_process:2,inherits:1}]},{},[14])(14)}); \ No newline at end of file diff --git a/dist/htmlminifier.js b/dist/htmlminifier.js index ed27bc2..e15c6c3 100644 --- a/dist/htmlminifier.js +++ b/dist/htmlminifier.js @@ -3,1890 +3,32892 @@ * Copyright 2010-2016 Juriy "kangax" Zaytsev * Licensed under the MIT license */ -/*! - * HTML Parser By John Resig (ejohn.org) - * Modified by Juriy "kangax" Zaytsev - * Original code by Erik Arvidsson, Mozilla Public License - * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js - */ -/* - * // Use like so: - * HTMLParser(htmlString, { - * start: function(tag, attrs, unary) {}, - * end: function(tag) {}, - * chars: function(text) {}, - * comment: function(text) {} - * }); - * - * // or to get an XML string: - * HTMLtoXML(htmlString); - * - * // or to get an XML DOM Document - * HTMLtoDOM(htmlString); - * - * // or to inject into an existing document/DOM node - * HTMLtoDOM(htmlString, document); - * HTMLtoDOM(htmlString, document.body); - * +require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o\/=]+)/, - singleAttrAssign = /=/, - singleAttrAssigns = [ singleAttrAssign ], - singleAttrValues = [ - // attr value double quotes - /"([^"]*)"+/.source, - // attr value, single quotes - /'([^']*)'+/.source, - // attr value, no quotes - /([^\s"'=<>`]+)/.source - ], - // https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName - qnameCapture = (function() { - var ncname; - if (typeof require === 'function') { - ncname = require('ncname'); - } - else { - ncname = global.NCName; - } - if (ncname) { - ncname = ncname.source.slice(1, -1); - } - else { - ncname = '[:A-Za-z_][:\\w\\-\\.]*'; - } - return '((?:' + ncname + '\\:)?' + ncname + ')'; - })(), - startTagOpen = new RegExp('^<' + qnameCapture), - startTagClose = /^\s*(\/?)>/, - endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'), - doctype = /^]+>/i; - - var IS_REGEX_CAPTURING_BROKEN = false; - 'x'.replace(/x(.)?/g, function(m, g) { - IS_REGEX_CAPTURING_BROKEN = g === ''; - }); +/** + * Creates a define for node. + * @param {Object} module the "module" object that is defined by Node for the + * current module. + * @param {Function} [requireFn]. Node's require function for the current module. + * It only needs to be passed in Node versions before 0.5, when module.require + * did not exist. + * @returns {Function} a define function that is usable for the current node + * module. + */ +function amdefine(module, requireFn) { + 'use strict'; + var defineCache = {}, + loaderCache = {}, + alreadyCalled = false, + path = require('path'), + makeRequire, stringRequire; - // Empty Elements - var empty = makeMap('area,base,basefont,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr'); - - // Inline Elements - var inline = makeMap('a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,noscript,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,svg,textarea,tt,u,var'); - - // Elements that you can, intentionally, leave open - // (and which close themselves) - var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'); - - // Attributes that have their values filled in disabled='disabled' - var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); - - // Special Elements (can contain anything) - var special = makeMap('script,style'); - - // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 - // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content - var nonPhrasing = makeMap('address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track'); - - var reCache = {}; - - function attrForHandler(handler) { - var pattern = singleAttrIdentifier.source - + '(?:\\s*(' + joinSingleAttrAssigns(handler) + ')' - + '\\s*(?:' + singleAttrValues.join('|') + '))?'; - if (handler.customAttrSurround) { - var attrClauses = []; - for ( var i = handler.customAttrSurround.length - 1; i >= 0; i-- ) { - attrClauses[i] = '(?:' - + '(' + handler.customAttrSurround[i][0].source + ')\\s*' - + pattern - + '\\s*(' + handler.customAttrSurround[i][1].source + ')' - + ')'; - } - attrClauses.push('(?:' + pattern + ')'); - pattern = '(?:' + attrClauses.join('|') + ')'; - } - return new RegExp('^\\s*' + pattern); - } - - function joinSingleAttrAssigns( handler ) { - return singleAttrAssigns.concat( - handler.customAttrAssign || [] - ).map(function (assign) { - return '(?:' + assign.source + ')'; - }).join('|'); - } - - var HTMLParser = global.HTMLParser = function( html, handler ) { - var stack = [], lastTag; - var attribute = attrForHandler(handler); - var last, prevTag, nextTag; - while ( html ) { - last = html; - // Make sure we're not in a script or style element - if ( !lastTag || !special[ lastTag ] ) { - var textEnd = html.indexOf('<'); - if (textEnd === 0) { - // Comment: - if ( /^'); - - if ( commentEnd >= 0 ) { - if ( handler.comment ) { - handler.comment( html.substring( 4, commentEnd ) ); - } - html = html.substring( commentEnd + 3 ); - prevTag = ''; - continue; + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; ary[i]; i+= 1) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { + //End of the line. Keep at least one non-dot + //path segment at the front so it can be mapped + //correctly to disk. Otherwise, there is likely + //no path mapping for a path starting with '..'. + //This can still fail, but catches the most reasonable + //uses of .. + break; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } } - } - - // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment - if ( /^'); + } + } - if (conditionalEnd >= 0) { - if ( handler.comment ) { - handler.comment( html.substring(2, conditionalEnd + 1 ), true /* non-standard */ ); - } - html = html.substring( conditionalEnd + 2 ); - prevTag = ''; - continue; - } - } + function normalize(name, baseName) { + var baseParts; - // Doctype: - var doctypeMatch = html.match( doctype ); - if ( doctypeMatch ) { - if ( handler.doctype ) { - handler.doctype( doctypeMatch[0] ); + //Adjust any relative paths. + if (name && name.charAt(0) === '.') { + //If have a base name, try to normalize against it, + //otherwise, assume it is a top-level require that will + //be relative to baseUrl in the end. + if (baseName) { + baseParts = baseName.split('/'); + baseParts = baseParts.slice(0, baseParts.length - 1); + baseParts = baseParts.concat(name.split('/')); + trimDots(baseParts); + name = baseParts.join('/'); } - html = html.substring( doctypeMatch[0].length ); - prevTag = ''; - continue; - } - - // End tag: - var endTagMatch = html.match( endTag ); - if ( endTagMatch ) { - html = html.substring( endTagMatch[0].length ); - endTagMatch[0].replace( endTag, parseEndTag ); - prevTag = '/' + endTagMatch[1].toLowerCase(); - continue; - } - - // Start tag: - var startTagMatch = parseStartTag(html); - if ( startTagMatch ) { - html = startTagMatch.rest; - handleStartTag(startTagMatch); - prevTag = startTagMatch.tagName.toLowerCase(); - continue; - } } - var text; - if (textEnd >= 0) { - text = html.substring( 0, textEnd ); - html = html.substring( textEnd ); - } - else { - text = html; - html = ''; - } + return name; + } - // next tag - var nextTagMatch = parseStartTag(html); - if (nextTagMatch) { - nextTag = nextTagMatch.tagName; - } - else { - nextTagMatch = html.match( endTag ); - if (nextTagMatch) { - nextTag = '/' + nextTagMatch[1]; - } - else { - nextTag = ''; - } - } + /** + * Create the normalize() function passed to a loader plugin's + * normalize method. + */ + function makeNormalize(relName) { + return function (name) { + return normalize(name, relName); + }; + } - if ( handler.chars ) { - handler.chars(text, prevTag, nextTag); + function makeLoad(id) { + function load(value) { + loaderCache[id] = value; } - prevTag = ''; - - } - else { - var stackedTag = lastTag.toLowerCase(); - var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)<\/' + stackedTag + '[^>]*>', 'i')); - - html = html.replace(reStackedTag, function(all, text) { - if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') { - text = text - .replace(//g, '$1') - .replace(//g, '$1'); - } - if ( handler.chars ) { - handler.chars( text ); - } + load.fromText = function (id, text) { + //This one is difficult because the text can/probably uses + //define, and any relative paths and requires should be relative + //to that id was it would be found on disk. But this would require + //bootstrapping a module/require fairly deeply from node core. + //Not sure how best to go about that yet. + throw new Error('amdefine does not implement load.fromText'); + }; - return ''; - }); + return load; + } - parseEndTag( '', stackedTag ); - } + makeRequire = function (systemRequire, exports, module, relId) { + function amdRequire(deps, callback) { + if (typeof deps === 'string') { + //Synchronous, single module require('') + return stringRequire(systemRequire, exports, module, deps, relId); + } else { + //Array of dependencies with a callback. - if ( html === last ) { - throw new Error('Parse Error: ' + html); - } - } + //Convert the dependencies to modules. + deps = deps.map(function (depName) { + return stringRequire(systemRequire, exports, module, depName, relId); + }); - if (!handler.partialMarkup) { - // Clean up any remaining tags - parseEndTag(); - } + //Wait for next tick to call back the require call. + if (callback) { + process.nextTick(function () { + callback.apply(null, deps); + }); + } + } + } - function parseStartTag(input) { - var start = input.match(startTagOpen); - if (start) { - var match = { - tagName: start[1], - attrs: [] + amdRequire.toUrl = function (filePath) { + if (filePath.indexOf('.') === 0) { + return normalize(filePath, path.dirname(module.filename)); + } else { + return filePath; + } }; - input = input.slice(start[0].length); - var end, attr; - while (!(end = input.match(startTagClose)) && (attr = input.match(attribute))) { - input = input.slice(attr[0].length); - match.attrs.push(attr); - } - if (end) { - match.unarySlash = end[1]; - match.rest = input.slice(end[0].length); - return match; - } - } - } - function handleStartTag(match) { - var tagName = match.tagName; - var unarySlash = match.unarySlash; + return amdRequire; + }; - if (handler.html5 && lastTag === 'p' && nonPhrasing[tagName]) { - parseEndTag( '', lastTag ); - } + //Favor explicit value, passed in if the module wants to support Node 0.4. + requireFn = requireFn || function req() { + return module.require.apply(module, arguments); + }; - if (!handler.html5) { - while (lastTag && inline[ lastTag ]) { - parseEndTag( '', lastTag ); - } - } + function runFactory(id, deps, factory) { + var r, e, m, result; - if ( closeSelf[ tagName ] && lastTag === tagName ) { - parseEndTag( '', tagName ); - } + if (id) { + e = loaderCache[id] = {}; + m = { + id: id, + uri: __filename, + exports: e + }; + r = makeRequire(requireFn, e, m, id); + } else { + //Only support one define call per file + if (alreadyCalled) { + throw new Error('amdefine with no module ID cannot be called more than once per file.'); + } + alreadyCalled = true; - var unary = empty[ tagName ] || tagName === 'html' && lastTag === 'head' || !!unarySlash; + //Use the real variables from node + //Use module.exports for exports, since + //the exports in here is amdefine exports. + e = module.exports; + m = module; + r = makeRequire(requireFn, e, m, module.id); + } - var attrs = match.attrs.map(function(args) { - var name, value, fallbackValue, customOpen, customClose, customAssign, quote; - var ncp = 7; // number of captured parts, scalar + //If there are dependencies, they are strings, so need + //to convert them to dependency values. + if (deps) { + deps = deps.map(function (depName) { + return r(depName); + }); + } - // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 - if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { - if (args[3] === '') { args[3] = undefined; } - if (args[4] === '') { args[4] = undefined; } - if (args[5] === '') { args[5] = undefined; } + //Call the factory with the right dependencies. + if (typeof factory === 'function') { + result = factory.apply(m.exports, deps); + } else { + result = factory; } - var j = 1; - if (handler.customAttrSurround) { - for (var i = 0, l = handler.customAttrSurround.length; i < l; i++, j += ncp) { - name = args[j + 1]; - customAssign = args[j + 2]; - if (name) { - fallbackValue = args[j + 3]; - value = fallbackValue || args[j + 4] || args[j + 5]; - quote = fallbackValue ? '"' : value ? '\'' : ''; - customOpen = args[j]; - customClose = args[j + 6]; - break; + if (result !== undefined) { + m.exports = result; + if (id) { + loaderCache[id] = m.exports; } - } } + } - if (!name && (name = args[j])) { - customAssign = args[j + 1]; - fallbackValue = args[j + 2]; - value = fallbackValue || args[j + 3] || args[j + 4]; - quote = fallbackValue ? '"' : value ? '\'' : ''; - } + stringRequire = function (systemRequire, exports, module, id, relId) { + //Split the ID by a ! so that + var index = id.indexOf('!'), + originalId = id, + prefix, plugin; - if (value === undefined) { - value = fillAttrs[name] ? name : fallbackValue; - } + if (index === -1) { + id = normalize(id, relId); - return { - name: name, - value: value, - customAssign: customAssign || '=', - customOpen: customOpen || '', - customClose: customClose || '', - quote: quote || '' - }; - }); + //Straight module lookup. If it is one of the special dependencies, + //deal with it, otherwise, delegate to node. + if (id === 'require') { + return makeRequire(systemRequire, exports, module, relId); + } else if (id === 'exports') { + return exports; + } else if (id === 'module') { + return module; + } else if (loaderCache.hasOwnProperty(id)) { + return loaderCache[id]; + } else if (defineCache[id]) { + runFactory.apply(null, defineCache[id]); + return loaderCache[id]; + } else { + if(systemRequire) { + return systemRequire(originalId); + } else { + throw new Error('No module with ID: ' + id); + } + } + } else { + //There is a plugin in play. + prefix = id.substring(0, index); + id = id.substring(index + 1, id.length); - if ( !unary ) { - stack.push( { tag: tagName, attrs: attrs } ); - lastTag = tagName; - unarySlash = ''; - } + plugin = stringRequire(systemRequire, exports, module, prefix, relId); - if ( handler.start ) { - handler.start( tagName, attrs, unary, unarySlash ); - } - } + if (plugin.normalize) { + id = plugin.normalize(id, makeNormalize(relId)); + } else { + //Normalize the ID normally. + id = normalize(id, relId); + } - function parseEndTag( tag, tagName ) { - var pos; + if (loaderCache[id]) { + return loaderCache[id]; + } else { + plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); - // If no tag name is provided, clean shop - if ( !tagName ) { - pos = 0; - } - else { - // Find the closest opened tag of the same type - var needle = tagName.toLowerCase(); - for ( pos = stack.length - 1; pos >= 0; pos-- ) { - if ( stack[ pos ].tag.toLowerCase() === needle ) { - break; - } + return loaderCache[id]; + } } - } + }; - if ( pos >= 0 ) { - // Close all the open elements, up the stack - for ( var i = stack.length - 1; i >= pos; i-- ) { - if ( handler.end ) { - handler.end( stack[ i ].tag, stack[ i ].attrs, i > pos || !tag ); - } + //Create a define function specific to the module asking for amdefine. + function define(id, deps, factory) { + if (Array.isArray(id)) { + factory = deps; + deps = id; + id = undefined; + } else if (typeof id !== 'string') { + factory = id; + id = deps = undefined; } - // Remove the open elements from the stack - stack.length = pos; - lastTag = pos && stack[ pos - 1 ].tag; - } - else if (tagName.toLowerCase() === 'br') { - if (handler.start) { - handler.start(tagName, [], true, ''); + if (deps && !Array.isArray(deps)) { + factory = deps; + deps = undefined; } - } - else if (tagName.toLowerCase() === 'p') { - if (handler.start) { - handler.start(tagName, [], false, '', true); + + if (!deps) { + deps = ['require', 'exports', 'module']; } - if (handler.end) { - handler.end(tagName, []); + + //Set up properties for this module. If an ID, then use + //internal cache. If no ID, then use the external variables + //for this node module. + if (id) { + //Put the module in deep freeze until there is a + //require call for it. + defineCache[id] = [id, deps, factory]; + } else { + runFactory(id, deps, factory); } - } } - }; - - global.HTMLtoXML = function( html ) { - var results = ''; - new HTMLParser(html, { - start: function( tag, attrs, unary ) { - results += '<' + tag; + //define.require, which has access to all the values in the + //cache. Useful for AMD modules that all have IDs in the file, + //but need to finally export a value to node based on one of those + //IDs. + define.require = function (id) { + if (loaderCache[id]) { + return loaderCache[id]; + } - for ( var i = 0; i < attrs.length; i++ ) { - results += ' ' + attrs[i].name + '="' + (attrs[i].value || '').replace(/"/g, '"') + '"'; + if (defineCache[id]) { + runFactory.apply(null, defineCache[id]); + return loaderCache[id]; } + }; - results += (unary ? '/' : '') + '>'; - }, - end: function( tag ) { - results += ''; - }, - chars: function( text ) { - results += text; - }, - comment: function( text ) { - results += ''; - }, - ignore: function(text) { - results += text; - } - }); + define.amd = {}; - return results; - }; + return define; +} - global.HTMLtoDOM = function( html, doc ) { - // There can be only one of these elements - var one = makeMap('html,head,body,title'); +module.exports = amdefine; - // Enforce a structure for the document - var structure = { - link: 'head', - base: 'head' - }; +}).call(this,require('_process'),"/node_modules\\amdefine\\amdefine.js") +},{"_process":78,"path":76}],2:[function(require,module,exports){ +'use strict' - if ( !doc ) { - if ( typeof DOMDocument !== 'undefined' ) { - doc = new DOMDocument(); - } - else if ( typeof document !== 'undefined' && document.implementation && document.implementation.createDocument ) { - doc = document.implementation.createDocument('', '', null); - } - else if ( typeof ActiveX !== 'undefined' ) { - doc = new ActiveXObject('Msxml.DOMDocument'); - } +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray - } - else { - doc = doc.ownerDocument || - doc.getOwnerDocument && doc.getOwnerDocument() || - doc; - } +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - var elems = [], - documentElement = doc.documentElement || - doc.getDocumentElement && doc.getDocumentElement(); +function init () { + var i + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + var len = code.length - // If we're dealing with an empty document then we - // need to pre-populate it with the HTML document structure - if ( !documentElement && doc.createElement ) { - (function() { - var html = doc.createElement('html'); - var head = doc.createElement('head'); - head.appendChild( doc.createElement('title') ); - html.appendChild( head ); - html.appendChild( doc.createElement('body') ); - doc.appendChild( html ); - })(); - } + for (i = 0; i < len; i++) { + lookup[i] = code[i] + } - // Find all the unique elements - if ( doc.getElementsByTagName ) { - for ( var i in one ) { - one[ i ] = doc.getElementsByTagName( i )[0]; - } - } + for (i = 0; i < len; ++i) { + revLookup[code.charCodeAt(i)] = i + } + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 +} - // If we're working with a document, inject contents into - // the body element - var curParentNode = one.body; +init() - new HTMLParser( html, { - start: function( tagName, attrs, unary ) { - // If it's a pre-built element, then we can ignore - // its construction - if ( one[ tagName ] ) { - curParentNode = one[ tagName ]; - return; - } +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length - var elem = doc.createElement( tagName ); + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - for ( var attr in attrs ) { - elem.setAttribute( attrs[ attr ].name, attrs[ attr ].value ); - } + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 - if ( structure[ tagName ] && typeof one[ structure[ tagName ] ] !== 'boolean' ) { - one[ structure[ tagName ] ].appendChild( elem ); - } - else if ( curParentNode && curParentNode.appendChild ) { - curParentNode.appendChild( elem ); - } + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders) - if ( !unary ) { - elems.push( elem ); - curParentNode = elem; - } - }, - end: function( /* tag */ ) { - elems.length -= 1; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len - // Init the new parentNode - curParentNode = elems[ elems.length - 1 ]; - }, - chars: function( text ) { - curParentNode.appendChild( doc.createTextNode( text ) ); - }, - comment: function( /* text */ ) { - // create comment node - }, - ignore: function( /* text */ ) { - // What to do here? - } - }); + var L = 0 - return doc; - }; + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp & 0xFF0000) >> 16 + arr[L++] = (tmp & 0xFF00) >> 8 + arr[L++] = tmp & 0xFF + } - function makeMap(str) { - var obj = {}, items = str.split(','); - for ( var i = 0; i < items.length; i++ ) { - obj[ items[i] ] = true; - obj[ items[i].toUpperCase() ] = true; - } - return obj; + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF } -})(typeof exports === 'undefined' ? this : exports); -(function(global) { - 'use strict'; + return arr +} - var log, HTMLParser; - if (global.console && global.console.log) { - log = function(message) { - // "preserving" `this` - global.console.log(message); - }; - } - else { - log = function() {}; +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 - if (global.HTMLParser) { - HTMLParser = global.HTMLParser; + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } - else if (typeof require === 'function') { - HTMLParser = require('./htmlparser').HTMLParser; + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' } - var trimWhitespace = function(str) { - if (typeof str !== 'string') { - return str; - } - return str.replace(/^\s+/, '').replace(/\s+$/, ''); - }; - if (String.prototype.trim) { - trimWhitespace = function(str) { - if (typeof str !== 'string') { - return str; - } - return str.trim(); - }; + parts.push(output) + + return parts.join('') +} + +},{}],3:[function(require,module,exports){ + +},{}],4:[function(require,module,exports){ +arguments[4][3][0].apply(exports,arguments) +},{"dup":3}],5:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var rootParent = {} + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.foo = function () { return 42 } + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} - function compressWhitespace(spaces) { - return spaces === '\t' ? spaces : ' '; +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ +function Buffer (arg) { + if (!(this instanceof Buffer)) { + // Avoid going through an ArgumentsAdaptorTrampoline in the common case. + if (arguments.length > 1) return new Buffer(arg, arguments[1]) + return new Buffer(arg) } - function collapseWhitespaceAll(str) { - return str ? str.replace(/[\t\n\r ]+/g, compressWhitespace) : str; + if (!Buffer.TYPED_ARRAY_SUPPORT) { + this.length = 0 + this.parent = undefined } - function createMap(values) { - var map = {}; - values.forEach(function(value) { - map[value] = 1; - }); - return function(value) { - return map[value] === 1; - }; + // Common case. + if (typeof arg === 'number') { + return fromNumber(this, arg) } - function createMapFromString(values) { - return createMap(values.split(/,/)); + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } - function collapseWhitespace(str, options, trimLeft, trimRight, collapseAll) { - var lineBreakBefore = '', lineBreakAfter = ''; + // Unusual. + return fromObject(this, arg) +} - if (options.preserveLineBreaks) { - str = str.replace(/^[\t ]*[\n\r][\t\n\r ]*/, function() { - lineBreakBefore = '\n'; - return ''; - }).replace(/[\t\n\r ]*[\n\r][\t ]*$/, function() { - lineBreakAfter = '\n'; - return ''; - }); - } +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} - if (trimLeft) { - str = str.replace(/^\s+/, !lineBreakBefore && options.conservativeCollapse ? compressWhitespace : ''); +function fromNumber (that, length) { + that = allocate(that, length < 0 ? 0 : checked(length) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < length; i++) { + that[i] = 0 } + } + return that +} - if (trimRight) { - str = str.replace(/\s+$/, !lineBreakAfter && options.conservativeCollapse ? compressWhitespace : ''); - } +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' - if (collapseAll) { - // strip non space whitespace then compress spaces to one - str = collapseWhitespaceAll(str); - } + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) - return lineBreakBefore + str + lineBreakAfter; - } + that.write(string, encoding) + return that +} + +function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) + + if (isArray(object)) return fromArray(that, object) - // non-empty tags that will maintain whitespace around them - var inlineTags = createMapFromString('a,abbr,acronym,b,bdi,bdo,big,button,cite,code,del,dfn,em,font,i,ins,kbd,mark,math,q,rt,rp,s,samp,small,span,strike,strong,sub,sup,svg,time,tt,u,var'); - // non-empty tags that will maintain whitespace within them - var inlineTextTags = createMapFromString('a,abbr,acronym,b,big,del,em,font,i,ins,kbd,mark,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var'); - // self-closing tags that will maintain whitespace around them - var selfClosingInlineTags = createMapFromString('comment,img,input'); + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') + } - function collapseWhitespaceSmart(str, prevTag, nextTag, options) { - var trimLeft = prevTag && !selfClosingInlineTags(prevTag); - if (trimLeft && !options.collapseInlineTagWhitespace) { - trimLeft = prevTag.charAt(0) === '/' ? !inlineTags(prevTag.slice(1)) : !inlineTextTags(prevTag); + if (typeof ArrayBuffer !== 'undefined') { + if (object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) } - var trimRight = nextTag && !selfClosingInlineTags(nextTag); - if (trimRight && !options.collapseInlineTagWhitespace) { - trimRight = nextTag.charAt(0) === '/' ? !inlineTextTags(nextTag.slice(1)) : !inlineTags(nextTag); + if (object instanceof ArrayBuffer) { + return fromArrayBuffer(that, object) } - return collapseWhitespace(str, options, trimLeft, trimRight, prevTag && nextTag); } - function isConditionalComment(text) { - return /^\[if\s[^\]]+\]|\[endif\]$/.test(text); - } + if (object.length) return fromArrayLike(that, object) - function isIgnoredComment(text, options) { - if (/^!/.test(text)) { - return true; - } + return fromJsonObject(that, object) +} - if (options.ignoreCustomComments) { - for (var i = 0, len = options.ignoreCustomComments.length; i < len; i++) { - if (options.ignoreCustomComments[i].test(text)) { - return true; - } - } - } +function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that +} - return false; +function fromArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } + return that +} - function isEventAttribute(attrName, options) { - var patterns = options.customEventAttributes; - if (patterns) { - for (var i = patterns.length; i--;) { - if (patterns[i].test(attrName)) { - return true; - } - } - return false; - } - else { - return (/^on[a-z]{3,}$/).test(attrName); - } +// Duplicate of fromArray() to keep fromArray() monomorphic. +function fromTypedArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + // Truncating the elements is probably not what people expect from typed + // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior + // of the old Buffer constructor. + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } + return that +} - function canRemoveAttributeQuotes(value) { - // http://mathiasbynens.be/notes/unquoted-attribute-values - return (/^[^\x20\t\n\f\r"'`=<>]+$/).test(value); +function fromArrayBuffer (that, array) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(array) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromTypedArray(that, new Uint8Array(array)) } + return that +} - function attributesInclude(attributes, attribute) { - for (var i = attributes.length; i--;) { - if (attributes[i].name.toLowerCase() === attribute) { - return true; - } - } - return false; +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } + return that +} - function isAttributeRedundant(tag, attrName, attrValue, attrs) { - attrValue = attrValue ? trimWhitespace(attrValue.toLowerCase()) : ''; +// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. +// Returns a zero-length buffer for inputs that don't conform to the spec. +function fromJsonObject (that, object) { + var array + var length = 0 - return ( - (tag === 'script' && - attrName === 'language' && - attrValue === 'javascript') || + if (object.type === 'Buffer' && isArray(object.data)) { + array = object.data + length = checked(array.length) | 0 + } + that = allocate(that, length) + + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} - (tag === 'form' && - attrName === 'method' && - attrValue === 'get') || +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} else { + // pre-set for values that may exist in the future + Buffer.prototype.length = undefined + Buffer.prototype.parent = undefined +} - (tag === 'input' && - attrName === 'type' && - attrValue === 'text') || +function allocate (that, length) { + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that.length = length + } - (tag === 'script' && - attrName === 'charset' && - !attributesInclude(attrs, 'src')) || + var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 + if (fromPool) that.parent = rootParent - (tag === 'a' && - attrName === 'name' && - attributesInclude(attrs, 'id')) || + return that +} - (tag === 'area' && - attrName === 'shape' && - attrValue === 'rect') - ); +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } + return length | 0 +} - // https://mathiasbynens.be/demo/javascript-mime-type - // https://developer.mozilla.org/en/docs/Web/HTML/Element/script#attr-type - var executableScriptsMimetypes = createMap([ - 'text/javascript', - 'text/ecmascript', - 'text/jscript', - 'application/javascript', - 'application/x-javascript', - 'application/ecmascript' - ]); +function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) - function isScriptTypeAttribute(tag, attrName, attrValue) { - return ( - tag === 'script' && - attrName === 'type' && - executableScriptsMimetypes(trimWhitespace(attrValue.toLowerCase())) - ); + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - function isExecutableScript(tag, attrs) { - if (tag !== 'script') { - return false; - } - for (var i = 0, len = attrs.length; i < len; i++) { - var attrName = attrs[i].name.toLowerCase(); - if (attrName === 'type') { - var attrValue = trimWhitespace(attrs[i].value.split(/;/, 2)[0]).toLowerCase(); - return attrValue === '' || executableScriptsMimetypes(attrValue); - } - } - return true; + if (a === b) return 0 + + var x = a.length + var y = b.length + + var i = 0 + var len = Math.min(x, y) + while (i < len) { + if (a[i] !== b[i]) break + + ++i } - function isStyleLinkTypeAttribute(tag, attrName, attrValue) { - return ( - (tag === 'style' || tag === 'link') && - attrName === 'type' && - trimWhitespace(attrValue.toLowerCase()) === 'text/css' - ); + if (i !== len) { + x = a[i] + y = b[i] } - var isSimpleBoolean = createMapFromString('allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,truespeed,typemustmatch,visible'); - var isBooleanValue = createMapFromString('true,false'); + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - function isBooleanAttribute(attrName, attrValue) { - return isSimpleBoolean(attrName) || attrName === 'draggable' && !isBooleanValue(attrValue); +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false } +} - function isUriTypeAttribute(attrName, tag) { - return ( - ((/^(?:a|area|link|base)$/).test(tag) && attrName === 'href') || - (tag === 'img' && (/^(?:src|longdesc|usemap)$/).test(attrName)) || - (tag === 'object' && (/^(?:classid|codebase|data|usemap)$/).test(attrName)) || - (tag === 'q' && attrName === 'cite') || - (tag === 'blockquote' && attrName === 'cite') || - ((tag === 'ins' || tag === 'del') && attrName === 'cite') || - (tag === 'form' && attrName === 'action') || - (tag === 'input' && (attrName === 'src' || attrName === 'usemap')) || - (tag === 'head' && attrName === 'profile') || - (tag === 'script' && (attrName === 'src' || attrName === 'for')) - ); - } +Buffer.concat = function concat (list, length) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') - function isNumberTypeAttribute(attrName, tag) { - return ( - ((/^(?:a|area|object|button)$/).test(tag) && attrName === 'tabindex') || - (tag === 'input' && (attrName === 'maxlength' || attrName === 'tabindex')) || - (tag === 'select' && (attrName === 'size' || attrName === 'tabindex')) || - (tag === 'textarea' && (/^(?:rows|cols|tabindex)$/).test(attrName)) || - (tag === 'colgroup' && attrName === 'span') || - (tag === 'col' && attrName === 'span') || - ((tag === 'th' || tag === 'td') && (attrName === 'rowspan' || attrName === 'colspan')) - ); + if (list.length === 0) { + return new Buffer(0) } - function isCanonicalURL(tag, attrs) { - if (tag !== 'link') { - return false; - } - for (var i = 0, len = attrs.length; i < len; i++) { - if (attrs[i].name === 'rel' && attrs[i].value === 'canonical') { - return true; - } + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length } } - var fnPrefix = '!function(){'; - var fnSuffix = '}();'; + var buf = new Buffer(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} - function cleanAttributeValue(tag, attrName, attrValue, options, attrs) { - if (attrValue && isEventAttribute(attrName, options)) { - attrValue = trimWhitespace(attrValue).replace(/^javascript:\s*/i, '').replace(/\s*;$/, ''); - if (options.minifyJS) { - var minified = minifyJS(fnPrefix + attrValue + fnSuffix, options.minifyJS); - return minified.slice(fnPrefix.length, -fnSuffix.length); +function byteLength (string, encoding) { + if (typeof string !== 'string') string = '' + string + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 + + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'binary': + return binarySlice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return 0 + return Buffer.compare(this, b) +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 + + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 + + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + if (val.length === 0) return -1 // special case: looking for empty string always fails + return String.prototype.indexOf.call(this, val, byteOffset) + } + if (Buffer.isBuffer(val)) { + return arrayIndexOf(this, val, byteOffset) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + } + return arrayIndexOf(this, [ val ], byteOffset) + } + + function arrayIndexOf (arr, val, byteOffset) { + var foundIndex = -1 + for (var i = 0; byteOffset + i < arr.length; i++) { + if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + } else { + foundIndex = -1 + } + } + return -1 + } + + throw new TypeError('val must be string, number or Buffer') +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) throw new Error('Invalid hex string') + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + var swap = encoding + encoding = offset + offset = length | 0 + length = swap + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'binary': + return binaryWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + } + + if (newBuf.length) newBuf.parent = this.parent || this + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (end < start) throw new RangeError('end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":2,"ieee754":70,"isarray":73}],6:[function(require,module,exports){ +module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} + +},{}],7:[function(require,module,exports){ +module.exports = require('./lib/clean'); + +},{"./lib/clean":8}],8:[function(require,module,exports){ +(function (process){ +/** + * Clean-css - https://github.com/jakubpawlowicz/clean-css + * Released under the terms of MIT license + * + * Copyright (C) 2015 JakubPawlowicz.com + */ + +var ImportInliner = require('./imports/inliner'); +var rebaseUrls = require('./urls/rebase'); + +var tokenize = require('./tokenizer/tokenize'); +var simpleOptimize = require('./selectors/simple'); +var advancedOptimize = require('./selectors/advanced'); + +var simpleStringify = require('./stringifier/simple'); +var sourceMapStringify = require('./stringifier/source-maps'); + +var CommentsProcessor = require('./text/comments-processor'); +var ExpressionsProcessor = require('./text/expressions-processor'); +var FreeTextProcessor = require('./text/free-text-processor'); +var UrlsProcessor = require('./text/urls-processor'); + +var Compatibility = require('./utils/compatibility'); +var InputSourceMapTracker = require('./utils/input-source-map-tracker'); +var SourceTracker = require('./utils/source-tracker'); +var SourceReader = require('./utils/source-reader'); +var Validator = require('./properties/validator'); + +var fs = require('fs'); +var path = require('path'); +var url = require('url'); + +var override = require('./utils/object').override; + +var DEFAULT_TIMEOUT = 5000; + +var CleanCSS = module.exports = function CleanCSS(options) { + options = options || {}; + + this.options = { + advanced: undefined === options.advanced ? true : !!options.advanced, + aggressiveMerging: undefined === options.aggressiveMerging ? true : !!options.aggressiveMerging, + benchmark: options.benchmark, + compatibility: new Compatibility(options.compatibility).toOptions(), + debug: options.debug, + explicitRoot: !!options.root, + explicitTarget: !!options.target, + inliner: options.inliner || {}, + keepBreaks: options.keepBreaks || false, + keepSpecialComments: 'keepSpecialComments' in options ? options.keepSpecialComments : '*', + mediaMerging: undefined === options.mediaMerging ? true : !!options.mediaMerging, + processImport: undefined === options.processImport ? true : !!options.processImport, + processImportFrom: importOptionsFrom(options.processImportFrom), + rebase: undefined === options.rebase ? true : !!options.rebase, + relativeTo: options.relativeTo, + restructuring: undefined === options.restructuring ? true : !!options.restructuring, + root: options.root || process.cwd(), + roundingPrecision: options.roundingPrecision, + semanticMerging: undefined === options.semanticMerging ? false : !!options.semanticMerging, + shorthandCompacting: undefined === options.shorthandCompacting ? true : !!options.shorthandCompacting, + sourceMap: options.sourceMap, + sourceMapInlineSources: !!options.sourceMapInlineSources, + target: !options.target || missingDirectory(options.target) || presentDirectory(options.target) ? options.target : path.dirname(options.target) + }; + + this.options.inliner.timeout = this.options.inliner.timeout || DEFAULT_TIMEOUT; + this.options.inliner.request = override( + /* jshint camelcase: false */ + proxyOptionsFrom(process.env.HTTP_PROXY || process.env.http_proxy), + this.options.inliner.request || {} + ); +}; + +function importOptionsFrom(rules) { + return undefined === rules ? ['all'] : rules; +} + +function missingDirectory(filepath) { + return !fs.existsSync(filepath) && !/\.css$/.test(filepath); +} + +function presentDirectory(filepath) { + return fs.existsSync(filepath) && fs.statSync(filepath).isDirectory(); +} + +function proxyOptionsFrom(httpProxy) { + return httpProxy ? + { + hostname: url.parse(httpProxy).hostname, + port: parseInt(url.parse(httpProxy).port) + } : + {}; +} + +CleanCSS.prototype.minify = function (data, callback) { + var context = { + stats: {}, + errors: [], + warnings: [], + options: this.options, + debug: this.options.debug, + localOnly: !callback, + sourceTracker: new SourceTracker(), + validator: new Validator(this.options.compatibility) + }; + + if (context.options.sourceMap) + context.inputSourceMapTracker = new InputSourceMapTracker(context); + + context.sourceReader = new SourceReader(context, data); + data = context.sourceReader.toString(); + + if (context.options.processImport || data.indexOf('@shallow') > 0) { + // inline all imports + var runner = callback ? + process.nextTick : + function (callback) { return callback(); }; + + return runner(function () { + return new ImportInliner(context).process(data, { + localOnly: context.localOnly, + imports: context.options.processImportFrom, + whenDone: runMinifier(callback, context) + }); + }); + } else { + return runMinifier(callback, context)(data); + } +}; + +function runMinifier(callback, context) { + function whenSourceMapReady (data) { + data = context.options.debug ? + minifyWithDebug(context, data) : + minify(context, data); + data = withMetadata(context, data); + + return callback ? + callback.call(null, context.errors.length > 0 ? context.errors : null, data) : + data; + } + + return function (data) { + if (context.options.sourceMap) { + return context.inputSourceMapTracker.track(data, function () { + if (context.options.sourceMapInlineSources) { + return context.inputSourceMapTracker.resolveSources(function () { + return whenSourceMapReady(data); + }); + } else { + return whenSourceMapReady(data); + } + }); + } else { + return whenSourceMapReady(data); + } + }; +} + +function withMetadata(context, data) { + data.stats = context.stats; + data.errors = context.errors; + data.warnings = context.warnings; + return data; +} + +function minifyWithDebug(context, data) { + var startedAt = process.hrtime(); + context.stats.originalSize = context.sourceTracker.removeAll(data).length; + + data = minify(context, data); + + var elapsed = process.hrtime(startedAt); + context.stats.timeSpent = ~~(elapsed[0] * 1e3 + elapsed[1] / 1e6); + context.stats.efficiency = 1 - data.styles.length / context.stats.originalSize; + context.stats.minifiedSize = data.styles.length; + + return data; +} + +function benchmark(runner) { + return function (processor, action) { + var name = processor.constructor.name + '#' + action; + var start = process.hrtime(); + runner(processor, action); + var itTook = process.hrtime(start); + console.log('%d ms: ' + name, 1000 * itTook[0] + itTook[1] / 1000000); + }; +} + +function minify(context, data) { + var options = context.options; + + var commentsProcessor = new CommentsProcessor(context, options.keepSpecialComments, options.keepBreaks, options.sourceMap); + var expressionsProcessor = new ExpressionsProcessor(options.sourceMap); + var freeTextProcessor = new FreeTextProcessor(options.sourceMap); + var urlsProcessor = new UrlsProcessor(context, options.sourceMap, options.compatibility.properties.urlQuotes); + + var stringify = options.sourceMap ? sourceMapStringify : simpleStringify; + + var run = function (processor, action) { + data = typeof processor == 'function' ? + processor(data) : + processor[action](data); + }; + + if (options.benchmark) + run = benchmark(run); + + run(commentsProcessor, 'escape'); + run(expressionsProcessor, 'escape'); + run(urlsProcessor, 'escape'); + run(freeTextProcessor, 'escape'); + + function restoreEscapes(data, prefixContent) { + data = freeTextProcessor.restore(data, prefixContent); + data = urlsProcessor.restore(data); + data = options.rebase ? rebaseUrls(data, context) : data; + data = expressionsProcessor.restore(data); + return commentsProcessor.restore(data); + } + + var tokens = tokenize(data, context); + + simpleOptimize(tokens, options); + + if (options.advanced) + advancedOptimize(tokens, options, context.validator, true); + + return stringify(tokens, options, restoreEscapes, context.inputSourceMapTracker); +} + +}).call(this,require('_process')) +},{"./imports/inliner":12,"./properties/validator":26,"./selectors/advanced":29,"./selectors/simple":42,"./stringifier/simple":46,"./stringifier/source-maps":47,"./text/comments-processor":48,"./text/expressions-processor":50,"./text/free-text-processor":51,"./text/urls-processor":52,"./tokenizer/tokenize":55,"./urls/rebase":56,"./utils/compatibility":60,"./utils/input-source-map-tracker":61,"./utils/object":62,"./utils/source-reader":64,"./utils/source-tracker":65,"_process":78,"fs":4,"path":76,"url":140}],9:[function(require,module,exports){ +var HexNameShortener = {}; + +var COLORS = { + aliceblue: '#f0f8ff', + antiquewhite: '#faebd7', + aqua: '#0ff', + aquamarine: '#7fffd4', + azure: '#f0ffff', + beige: '#f5f5dc', + bisque: '#ffe4c4', + black: '#000', + blanchedalmond: '#ffebcd', + blue: '#00f', + blueviolet: '#8a2be2', + brown: '#a52a2a', + burlywood: '#deb887', + cadetblue: '#5f9ea0', + chartreuse: '#7fff00', + chocolate: '#d2691e', + coral: '#ff7f50', + cornflowerblue: '#6495ed', + cornsilk: '#fff8dc', + crimson: '#dc143c', + cyan: '#0ff', + darkblue: '#00008b', + darkcyan: '#008b8b', + darkgoldenrod: '#b8860b', + darkgray: '#a9a9a9', + darkgreen: '#006400', + darkgrey: '#a9a9a9', + darkkhaki: '#bdb76b', + darkmagenta: '#8b008b', + darkolivegreen: '#556b2f', + darkorange: '#ff8c00', + darkorchid: '#9932cc', + darkred: '#8b0000', + darksalmon: '#e9967a', + darkseagreen: '#8fbc8f', + darkslateblue: '#483d8b', + darkslategray: '#2f4f4f', + darkslategrey: '#2f4f4f', + darkturquoise: '#00ced1', + darkviolet: '#9400d3', + deeppink: '#ff1493', + deepskyblue: '#00bfff', + dimgray: '#696969', + dimgrey: '#696969', + dodgerblue: '#1e90ff', + firebrick: '#b22222', + floralwhite: '#fffaf0', + forestgreen: '#228b22', + fuchsia: '#f0f', + gainsboro: '#dcdcdc', + ghostwhite: '#f8f8ff', + gold: '#ffd700', + goldenrod: '#daa520', + gray: '#808080', + green: '#008000', + greenyellow: '#adff2f', + grey: '#808080', + honeydew: '#f0fff0', + hotpink: '#ff69b4', + indianred: '#cd5c5c', + indigo: '#4b0082', + ivory: '#fffff0', + khaki: '#f0e68c', + lavender: '#e6e6fa', + lavenderblush: '#fff0f5', + lawngreen: '#7cfc00', + lemonchiffon: '#fffacd', + lightblue: '#add8e6', + lightcoral: '#f08080', + lightcyan: '#e0ffff', + lightgoldenrodyellow: '#fafad2', + lightgray: '#d3d3d3', + lightgreen: '#90ee90', + lightgrey: '#d3d3d3', + lightpink: '#ffb6c1', + lightsalmon: '#ffa07a', + lightseagreen: '#20b2aa', + lightskyblue: '#87cefa', + lightslategray: '#778899', + lightslategrey: '#778899', + lightsteelblue: '#b0c4de', + lightyellow: '#ffffe0', + lime: '#0f0', + limegreen: '#32cd32', + linen: '#faf0e6', + magenta: '#ff00ff', + maroon: '#800000', + mediumaquamarine: '#66cdaa', + mediumblue: '#0000cd', + mediumorchid: '#ba55d3', + mediumpurple: '#9370db', + mediumseagreen: '#3cb371', + mediumslateblue: '#7b68ee', + mediumspringgreen: '#00fa9a', + mediumturquoise: '#48d1cc', + mediumvioletred: '#c71585', + midnightblue: '#191970', + mintcream: '#f5fffa', + mistyrose: '#ffe4e1', + moccasin: '#ffe4b5', + navajowhite: '#ffdead', + navy: '#000080', + oldlace: '#fdf5e6', + olive: '#808000', + olivedrab: '#6b8e23', + orange: '#ffa500', + orangered: '#ff4500', + orchid: '#da70d6', + palegoldenrod: '#eee8aa', + palegreen: '#98fb98', + paleturquoise: '#afeeee', + palevioletred: '#db7093', + papayawhip: '#ffefd5', + peachpuff: '#ffdab9', + peru: '#cd853f', + pink: '#ffc0cb', + plum: '#dda0dd', + powderblue: '#b0e0e6', + purple: '#800080', + rebeccapurple: '#663399', + red: '#f00', + rosybrown: '#bc8f8f', + royalblue: '#4169e1', + saddlebrown: '#8b4513', + salmon: '#fa8072', + sandybrown: '#f4a460', + seagreen: '#2e8b57', + seashell: '#fff5ee', + sienna: '#a0522d', + silver: '#c0c0c0', + skyblue: '#87ceeb', + slateblue: '#6a5acd', + slategray: '#708090', + slategrey: '#708090', + snow: '#fffafa', + springgreen: '#00ff7f', + steelblue: '#4682b4', + tan: '#d2b48c', + teal: '#008080', + thistle: '#d8bfd8', + tomato: '#ff6347', + turquoise: '#40e0d0', + violet: '#ee82ee', + wheat: '#f5deb3', + white: '#fff', + whitesmoke: '#f5f5f5', + yellow: '#ff0', + yellowgreen: '#9acd32' +}; + +var toHex = {}; +var toName = {}; + +for (var name in COLORS) { + var hex = COLORS[name]; + if (name.length < hex.length) + toName[hex] = name; + else + toHex[name] = hex; +} + +var toHexPattern = new RegExp('(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig'); +var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)', 'ig'); + +function hexConverter(match, prefix, colorValue, suffix) { + return prefix + toHex[colorValue.toLowerCase()] + suffix; +} + +function nameConverter(match, colorValue, suffix) { + return toName[colorValue.toLowerCase()] + suffix; +} + +HexNameShortener.shorten = function (value) { + var hasHex = value.indexOf('#') > -1; + var shortened = value.replace(toHexPattern, hexConverter); + + if (shortened != value) + shortened = shortened.replace(toHexPattern, hexConverter); + + return hasHex ? shortened.replace(toNamePattern, nameConverter) : shortened; +}; + +module.exports = HexNameShortener; + +},{}],10:[function(require,module,exports){ +// HSL to RGB converter. Both methods adapted from: +// http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript + +function HSLColor(hue, saturation, lightness) { + this.hue = hue; + this.saturation = saturation; + this.lightness = lightness; +} + +function hslToRgb(h, s, l) { + var r, g, b; + + // normalize hue orientation b/w 0 and 360 degrees + h = h % 360; + if (h < 0) + h += 360; + h = ~~h / 360; + + if (s < 0) + s = 0; + else if (s > 100) + s = 100; + s = ~~s / 100; + + if (l < 0) + l = 0; + else if (l > 100) + l = 100; + l = ~~l / 100; + + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? + l * (1 + s) : + l + s - l * s; + var p = 2 * l - q; + r = hueToRgb(p, q, h + 1/3); + g = hueToRgb(p, q, h); + b = hueToRgb(p, q, h - 1/3); + } + + return [~~(r * 255), ~~(g * 255), ~~(b * 255)]; +} + +function hueToRgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1/6) return p + (q - p) * 6 * t; + if (t < 1/2) return q; + if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; +} + +HSLColor.prototype.toHex = function () { + var asRgb = hslToRgb(this.hue, this.saturation, this.lightness); + var redAsHex = asRgb[0].toString(16); + var greenAsHex = asRgb[1].toString(16); + var blueAsHex = asRgb[2].toString(16); + + return '#' + + ((redAsHex.length == 1 ? '0' : '') + redAsHex) + + ((greenAsHex.length == 1 ? '0' : '') + greenAsHex) + + ((blueAsHex.length == 1 ? '0' : '') + blueAsHex); +}; + +module.exports = HSLColor; + +},{}],11:[function(require,module,exports){ +function RGB(red, green, blue) { + this.red = red; + this.green = green; + this.blue = blue; +} + +RGB.prototype.toHex = function () { + var red = Math.max(0, Math.min(~~this.red, 255)); + var green = Math.max(0, Math.min(~~this.green, 255)); + var blue = Math.max(0, Math.min(~~this.blue, 255)); + + // Credit: Asen http://jsbin.com/UPUmaGOc/2/edit?js,console + return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6); +}; + +module.exports = RGB; + +},{}],12:[function(require,module,exports){ +(function (process){ +var fs = require('fs'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var rewriteUrls = require('../urls/rewrite'); +var split = require('../utils/split'); +var override = require('../utils/object.js').override; + +var MAP_MARKER = /\/\*# sourceMappingURL=(\S+) \*\//; +var REMOTE_RESOURCE = /^(https?:)?\/\//; +var NO_PROTOCOL_RESOURCE = /^\/\//; + +function ImportInliner (context) { + this.outerContext = context; +} + +ImportInliner.prototype.process = function (data, context) { + var root = this.outerContext.options.root; + + context = override(context, { + baseRelativeTo: this.outerContext.options.relativeTo || root, + debug: this.outerContext.options.debug, + done: [], + errors: this.outerContext.errors, + left: [], + inliner: this.outerContext.options.inliner, + rebase: this.outerContext.options.rebase, + relativeTo: this.outerContext.options.relativeTo || root, + root: root, + sourceReader: this.outerContext.sourceReader, + sourceTracker: this.outerContext.sourceTracker, + warnings: this.outerContext.warnings, + visited: [] + }); + + return importFrom(data, context); +}; + +function importFrom(data, context) { + if (context.shallow) { + context.shallow = false; + context.done.push(data); + return processNext(context); + } + + var nextStart = 0; + var nextEnd = 0; + var cursor = 0; + var isComment = commentScanner(data); + + for (; nextEnd < data.length;) { + nextStart = nextImportAt(data, cursor); + if (nextStart == -1) + break; + + if (isComment(nextStart)) { + cursor = nextStart + 1; + continue; + } + + nextEnd = data.indexOf(';', nextStart); + if (nextEnd == -1) { + cursor = data.length; + data = ''; + break; + } + + var noImportPart = data.substring(0, nextStart); + context.done.push(noImportPart); + context.left.unshift([data.substring(nextEnd + 1), context]); + context.afterContent = hasContent(noImportPart); + return inline(data, nextStart, nextEnd, context); + } + + // no @import matched in current data + context.done.push(data); + return processNext(context); +} + +function rebaseMap(data, source) { + return data.replace(MAP_MARKER, function (match, sourceMapUrl) { + return REMOTE_RESOURCE.test(sourceMapUrl) ? + match : + match.replace(sourceMapUrl, url.resolve(source, sourceMapUrl)); + }); +} + +function nextImportAt(data, cursor) { + var nextLowerCase = data.indexOf('@import', cursor); + var nextUpperCase = data.indexOf('@IMPORT', cursor); + + if (nextLowerCase > -1 && nextUpperCase == -1) + return nextLowerCase; + else if (nextLowerCase == -1 && nextUpperCase > -1) + return nextUpperCase; + else + return Math.min(nextLowerCase, nextUpperCase); +} + +function processNext(context) { + return context.left.length > 0 ? + importFrom.apply(null, context.left.shift()) : + context.whenDone(context.done.join('')); +} + +function commentScanner(data) { + var commentRegex = /(\/\*(?!\*\/)[\s\S]*?\*\/)/; + var lastStartIndex = 0; + var lastEndIndex = 0; + var noComments = false; + + // test whether an index is located within a comment + return function scanner(idx) { + var comment; + var localStartIndex = 0; + var localEndIndex = 0; + var globalStartIndex = 0; + var globalEndIndex = 0; + + // return if we know there are no more comments + if (noComments) + return false; + + do { + // idx can be still within last matched comment (many @import statements inside one comment) + if (idx > lastStartIndex && idx < lastEndIndex) + return true; + + comment = data.match(commentRegex); + + if (!comment) { + noComments = true; + return false; + } + + // get the indexes relative to the current data chunk + lastStartIndex = localStartIndex = comment.index; + localEndIndex = localStartIndex + comment[0].length; + + // calculate the indexes relative to the full original data + globalEndIndex = localEndIndex + lastEndIndex; + globalStartIndex = globalEndIndex - comment[0].length; + + // chop off data up to and including current comment block + data = data.substring(localEndIndex); + lastEndIndex = globalEndIndex; + } while (globalEndIndex < idx); + + return globalEndIndex > idx && idx > globalStartIndex; + }; +} + +function hasContent(data) { + var isComment = commentScanner(data); + var firstContentIdx = -1; + while (true) { + firstContentIdx = data.indexOf('{', firstContentIdx + 1); + if (firstContentIdx == -1 || !isComment(firstContentIdx)) + break; + } + + return firstContentIdx > -1; +} + +function inline(data, nextStart, nextEnd, context) { + context.shallow = data.indexOf('@shallow') > 0; + + var importDeclaration = data + .substring(nextImportAt(data, nextStart) + '@import'.length + 1, nextEnd) + .replace(/@shallow\)$/, ')') + .trim(); + + var viaUrl = importDeclaration.indexOf('url(') === 0; + var urlStartsAt = viaUrl ? 4 : 0; + var isQuoted = /^['"]/.exec(importDeclaration.substring(urlStartsAt, urlStartsAt + 2)); + var urlEndsAt = isQuoted ? + importDeclaration.indexOf(isQuoted[0], urlStartsAt + 1) : + split(importDeclaration, ' ')[0].length - (viaUrl ? 1 : 0); + + var importedFile = importDeclaration + .substring(urlStartsAt, urlEndsAt) + .replace(/['"]/g, '') + .replace(/\)$/, '') + .trim(); + + var mediaQuery = importDeclaration + .substring(urlEndsAt + 1) + .replace(/^\)/, '') + .trim(); + + var isRemote = context.isRemote || REMOTE_RESOURCE.test(importedFile); + + if (isRemote && (context.localOnly || !allowedResource(importedFile, true, context.imports))) { + if (context.afterContent || hasContent(context.done.join(''))) + context.warnings.push('Ignoring remote @import of "' + importedFile + '" as no callback given.'); + else + restoreImport(importedFile, mediaQuery, context); + + return processNext(context); + } + + if (!isRemote && !allowedResource(importedFile, false, context.imports)) { + if (context.afterImport) + context.warnings.push('Ignoring local @import of "' + importedFile + '" as after other inlined content.'); + else + restoreImport(importedFile, mediaQuery, context); + return processNext(context); + } + + if (!isRemote && context.afterContent) { + context.warnings.push('Ignoring local @import of "' + importedFile + '" as after other CSS content.'); + return processNext(context); + } + + var method = isRemote ? inlineRemoteResource : inlineLocalResource; + return method(importedFile, mediaQuery, context); +} + +function allowedResource(importedFile, isRemote, rules) { + if (rules.length === 0) + return false; + + if (isRemote && NO_PROTOCOL_RESOURCE.test(importedFile)) + importedFile = 'http:' + importedFile; + + var match = isRemote ? + url.parse(importedFile).host : + importedFile; + var allowed = true; + + for (var i = 0; i < rules.length; i++) { + var rule = rules[i]; + + if (rule == 'all') + allowed = true; + else if (isRemote && rule == 'local') + allowed = false; + else if (isRemote && rule == 'remote') + allowed = true; + else if (!isRemote && rule == 'remote') + allowed = false; + else if (!isRemote && rule == 'local') + allowed = true; + else if (rule[0] == '!' && rule.substring(1) === match) + allowed = false; + } + + return allowed; +} + +function inlineRemoteResource(importedFile, mediaQuery, context) { + var importedUrl = REMOTE_RESOURCE.test(importedFile) ? + importedFile : + url.resolve(context.relativeTo, importedFile); + var originalUrl = importedUrl; + + if (NO_PROTOCOL_RESOURCE.test(importedUrl)) + importedUrl = 'http:' + importedUrl; + + if (context.visited.indexOf(importedUrl) > -1) + return processNext(context); + + + if (context.debug) + console.error('Inlining remote stylesheet: ' + importedUrl); + + context.visited.push(importedUrl); + + var get = importedUrl.indexOf('http://') === 0 ? + http.get : + https.get; + + var errorHandled = false; + function handleError(message) { + if (errorHandled) + return; + + errorHandled = true; + context.errors.push('Broken @import declaration of "' + importedUrl + '" - ' + message); + restoreImport(importedUrl, mediaQuery, context); + + process.nextTick(function () { + processNext(context); + }); + } + + var requestOptions = override(url.parse(importedUrl), context.inliner.request); + if (context.inliner.request.hostname !== undefined) + requestOptions.path = requestOptions.href; + + get(requestOptions, function (res) { + if (res.statusCode < 200 || res.statusCode > 399) { + return handleError('error ' + res.statusCode); + } else if (res.statusCode > 299) { + var movedUrl = url.resolve(importedUrl, res.headers.location); + return inlineRemoteResource(movedUrl, mediaQuery, context); + } + + var chunks = []; + var parsedUrl = url.parse(importedUrl); + res.on('data', function (chunk) { + chunks.push(chunk.toString()); + }); + res.on('end', function () { + var importedData = chunks.join(''); + if (context.rebase) + importedData = rewriteUrls(importedData, { toBase: originalUrl }, context); + context.sourceReader.trackSource(importedUrl, importedData); + importedData = context.sourceTracker.store(importedUrl, importedData); + importedData = rebaseMap(importedData, importedUrl); + + if (mediaQuery.length > 0) + importedData = '@media ' + mediaQuery + '{' + importedData + '}'; + + context.afterImport = true; + + var newContext = override(context, { + isRemote: true, + relativeTo: parsedUrl.protocol + '//' + parsedUrl.host + parsedUrl.pathname + }); + + process.nextTick(function () { + importFrom(importedData, newContext); + }); + }); + }) + .on('error', function (res) { + handleError(res.message); + }) + .on('timeout', function () { + handleError('timeout'); + }) + .setTimeout(context.inliner.timeout); +} + +function inlineLocalResource(importedFile, mediaQuery, context) { + var relativeTo = importedFile[0] == '/' ? + context.root : + context.relativeTo; + + var fullPath = path.resolve(path.join(relativeTo, importedFile)); + + if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) { + context.errors.push('Broken @import declaration of "' + importedFile + '"'); + return processNext(context); + } + + if (context.visited.indexOf(fullPath) > -1) + return processNext(context); + + + if (context.debug) + console.error('Inlining local stylesheet: ' + fullPath); + + context.visited.push(fullPath); + + var importRelativeTo = path.dirname(fullPath); + var importedData = fs.readFileSync(fullPath, 'utf8'); + if (context.rebase) { + var rewriteOptions = { + relative: true, + fromBase: importRelativeTo, + toBase: context.baseRelativeTo + }; + importedData = rewriteUrls(importedData, rewriteOptions, context); + } + + var relativePath = path.relative(context.root, fullPath); + context.sourceReader.trackSource(relativePath, importedData); + importedData = context.sourceTracker.store(relativePath, importedData); + + if (mediaQuery.length > 0) + importedData = '@media ' + mediaQuery + '{' + importedData + '}'; + + context.afterImport = true; + + var newContext = override(context, { + relativeTo: importRelativeTo + }); + + return importFrom(importedData, newContext); +} + +function restoreImport(importedUrl, mediaQuery, context) { + var restoredImport = '@import url(' + importedUrl + ')' + (mediaQuery.length > 0 ? ' ' + mediaQuery : '') + ';'; + context.done.push(restoredImport); +} + +module.exports = ImportInliner; + +}).call(this,require('_process')) +},{"../urls/rewrite":58,"../utils/object.js":62,"../utils/split":66,"_process":78,"fs":4,"http":122,"https":69,"path":76,"url":140}],13:[function(require,module,exports){ +var wrapSingle = require('./wrap-for-optimizing').single; + +var split = require('../utils/split'); +var MULTIPLEX_SEPARATOR = ','; + +function _colorFilter(validator) { + return function (value) { + return value[0] == 'invert' || validator.isValidColor(value[0]); + }; +} + +function _styleFilter(validator) { + return function (value) { + return value[0] != 'inherit' && validator.isValidStyle(value[0]) && !validator.isValidColorValue(value[0]); + }; +} + +function _wrapDefault(name, property, compactable) { + var descriptor = compactable[name]; + if (descriptor.doubleValues && descriptor.defaultValue.length == 2) + return wrapSingle([[name, property.important], [descriptor.defaultValue[0]], [descriptor.defaultValue[1]]]); + else if (descriptor.doubleValues && descriptor.defaultValue.length == 1) + return wrapSingle([[name, property.important], [descriptor.defaultValue[0]]]); + else + return wrapSingle([[name, property.important], [descriptor.defaultValue]]); +} + +function _widthFilter(validator) { + return function (value) { + return value[0] != 'inherit' && validator.isValidWidth(value[0]) && !validator.isValidStyleKeyword(value[0]) && !validator.isValidColorValue(value[0]); + }; +} + +function background(property, compactable, validator) { + var image = _wrapDefault('background-image', property, compactable); + var position = _wrapDefault('background-position', property, compactable); + var size = _wrapDefault('background-size', property, compactable); + var repeat = _wrapDefault('background-repeat', property, compactable); + var attachment = _wrapDefault('background-attachment', property, compactable); + var origin = _wrapDefault('background-origin', property, compactable); + var clip = _wrapDefault('background-clip', property, compactable); + var color = _wrapDefault('background-color', property, compactable); + var components = [image, position, size, repeat, attachment, origin, clip, color]; + var values = property.value; + + var positionSet = false; + var clipSet = false; + var originSet = false; + var repeatSet = false; + + if (property.value.length == 1 && property.value[0][0] == 'inherit') { + // NOTE: 'inherit' is not a valid value for background-attachment + color.value = image.value = repeat.value = position.value = size.value = origin.value = clip.value = property.value; + return components; + } + + for (var i = values.length - 1; i >= 0; i--) { + var value = values[i]; + + if (validator.isValidBackgroundAttachment(value[0])) { + attachment.value = [value]; + } else if (validator.isValidBackgroundBox(value[0])) { + if (clipSet) { + origin.value = [value]; + originSet = true; + } else { + clip.value = [value]; + clipSet = true; + } + } else if (validator.isValidBackgroundRepeat(value[0])) { + if (repeatSet) { + repeat.value.unshift(value); + } else { + repeat.value = [value]; + repeatSet = true; + } + } else if (validator.isValidBackgroundPositionPart(value[0]) || validator.isValidBackgroundSizePart(value[0])) { + if (i > 0) { + var previousValue = values[i - 1]; + + if (previousValue[0].indexOf('/') > 0) { + var twoParts = split(previousValue[0], '/'); + // NOTE: we do this slicing as value may contain metadata too, like for source maps + size.value = [[twoParts.pop()].concat(previousValue.slice(1)), value]; + values[i - 1] = [twoParts.pop()].concat(previousValue.slice(1)); + } else if (i > 1 && values[i - 2] == '/') { + size.value = [previousValue, value]; + i -= 2; + } else if (previousValue[0] == '/') { + size.value = [value]; + } else { + if (!positionSet) + position.value = []; + + position.value.unshift(value); + positionSet = true; + } + } else { + if (!positionSet) + position.value = []; + + position.value.unshift(value); + positionSet = true; + } + } else if (validator.isValidBackgroundPositionAndSize(value[0])) { + var sizeValue = split(value[0], '/'); + // NOTE: we do this slicing as value may contain metadata too, like for source maps + size.value = [[sizeValue.pop()].concat(value.slice(1))]; + position.value = [[sizeValue.pop()].concat(value.slice(1))]; + } else if ((color.value[0][0] == compactable[color.name].defaultValue || color.value[0][0] == 'none') && validator.isValidColor(value[0])) { + color.value = [value]; + } else if (validator.isValidUrl(value[0]) || validator.isValidFunction(value[0])) { + image.value = [value]; + } + } + + if (clipSet && !originSet) + origin.value = clip.value.slice(0); + + return components; +} + +function borderRadius(property, compactable) { + var values = property.value; + var splitAt = -1; + + for (var i = 0, l = values.length; i < l; i++) { + if (values[i][0] == '/') { + splitAt = i; + break; + } + } + + if (splitAt == -1) + return fourValues(property, compactable); + + var target = _wrapDefault(property.name, property, compactable); + target.value = values.slice(0, splitAt); + target.components = fourValues(target, compactable); + + var remainder = _wrapDefault(property.name, property, compactable); + remainder.value = values.slice(splitAt + 1); + remainder.components = fourValues(remainder, compactable); + + for (var j = 0; j < 4; j++) { + target.components[j].multiplex = true; + target.components[j].value = target.components[j].value.concat([['/']]).concat(remainder.components[j].value); + } + + return target.components; +} + +function fourValues(property, compactable) { + var componentNames = compactable[property.name].components; + var components = []; + var value = property.value; + + if (value.length < 1) + return []; + + if (value.length < 2) + value[1] = value[0].slice(0); + if (value.length < 3) + value[2] = value[0].slice(0); + if (value.length < 4) + value[3] = value[1].slice(0); + + for (var i = componentNames.length - 1; i >= 0; i--) { + var component = wrapSingle([[componentNames[i], property.important]]); + component.value = [value[i]]; + components.unshift(component); + } + + return components; +} + +function multiplex(splitWith) { + return function (property, compactable, validator) { + var splitsAt = []; + var values = property.value; + var i, j, l, m; + + // find split commas + for (i = 0, l = values.length; i < l; i++) { + if (values[i][0] == ',') + splitsAt.push(i); + } + + if (splitsAt.length === 0) + return splitWith(property, compactable, validator); + + var splitComponents = []; + + // split over commas, and into components + for (i = 0, l = splitsAt.length; i <= l; i++) { + var from = i === 0 ? 0 : splitsAt[i - 1] + 1; + var to = i < l ? splitsAt[i] : values.length; + + var _property = _wrapDefault(property.name, property, compactable); + _property.value = values.slice(from, to); + + splitComponents.push(splitWith(_property, compactable, validator)); + } + + var components = splitComponents[0]; + + // group component values from each split + for (i = 0, l = components.length; i < l; i++) { + components[i].multiplex = true; + + for (j = 1, m = splitComponents.length; j < m; j++) { + components[i].value.push([MULTIPLEX_SEPARATOR]); + Array.prototype.push.apply(components[i].value, splitComponents[j][i].value); + } + } + + return components; + }; +} + +function listStyle(property, compactable, validator) { + var type = _wrapDefault('list-style-type', property, compactable); + var position = _wrapDefault('list-style-position', property, compactable); + var image = _wrapDefault('list-style-image', property, compactable); + var components = [type, position, image]; + + if (property.value.length == 1 && property.value[0][0] == 'inherit') { + type.value = position.value = image.value = [property.value[0]]; + return components; + } + + var values = property.value.slice(0); + var total = values.length; + var index = 0; + + // `image` first... + for (index = 0, total = values.length; index < total; index++) { + if (validator.isValidUrl(values[index][0]) || values[index][0] == '0') { + image.value = [values[index]]; + values.splice(index, 1); + break; + } + } + + // ... then `type`... + for (index = 0, total = values.length; index < total; index++) { + if (validator.isValidListStyleType(values[index][0])) { + type.value = [values[index]]; + values.splice(index, 1); + break; + } + } + + // ... and what's left is a `position` + if (values.length > 0 && validator.isValidListStylePosition(values[0][0])) + position.value = [values[0]]; + + return components; +} + +function widthStyleColor(property, compactable, validator) { + var descriptor = compactable[property.name]; + var components = [ + _wrapDefault(descriptor.components[0], property, compactable), + _wrapDefault(descriptor.components[1], property, compactable), + _wrapDefault(descriptor.components[2], property, compactable) + ]; + var color, style, width; + + for (var i = 0; i < 3; i++) { + var component = components[i]; + + if (component.name.indexOf('color') > 0) + color = component; + else if (component.name.indexOf('style') > 0) + style = component; + else + width = component; + } + + if ((property.value.length == 1 && property.value[0][0] == 'inherit') || + (property.value.length == 3 && property.value[0][0] == 'inherit' && property.value[1][0] == 'inherit' && property.value[2][0] == 'inherit')) { + color.value = style.value = width.value = [property.value[0]]; + return components; + } + + var values = property.value.slice(0); + var match, matches; + + // NOTE: usually users don't follow the required order of parts in this shorthand, + // so we'll try to parse it caring as little about order as possible + + if (values.length > 0) { + matches = values.filter(_widthFilter(validator)); + match = matches.length > 1 && (matches[0][0] == 'none' || matches[0][0] == 'auto') ? matches[1] : matches[0]; + if (match) { + width.value = [match]; + values.splice(values.indexOf(match), 1); + } + } + + if (values.length > 0) { + match = values.filter(_styleFilter(validator))[0]; + if (match) { + style.value = [match]; + values.splice(values.indexOf(match), 1); + } + } + + if (values.length > 0) { + match = values.filter(_colorFilter(validator))[0]; + if (match) { + color.value = [match]; + values.splice(values.indexOf(match), 1); + } + } + + return components; +} + +module.exports = { + background: background, + border: widthStyleColor, + borderRadius: borderRadius, + fourValues: fourValues, + listStyle: listStyle, + multiplex: multiplex, + outline: widthStyleColor +}; + +},{"../utils/split":66,"./wrap-for-optimizing":28}],14:[function(require,module,exports){ +// Functions that decide what value can override what. +// The main purpose is to disallow removing CSS fallbacks. +// A separate implementation is needed for every different kind of CSS property. +// ----- +// The generic idea is that properties that have wider browser support are 'more understandable' +// than others and that 'less understandable' values can't override more understandable ones. + +// Use when two tokens of the same property can always be merged +function always() { + return true; +} + +function backgroundImage(property1, property2, validator) { + // The idea here is that 'more understandable' values override 'less understandable' values, but not vice versa + // Understandability: (none | url | inherit) > (same function) > (same value) + + // (none | url) + var image1 = property1.value[0][0]; + var image2 = property2.value[0][0]; + + if (image2 == 'none' || image2 == 'inherit' || validator.isValidUrl(image2)) + return true; + if (image1 == 'none' || image1 == 'inherit' || validator.isValidUrl(image1)) + return false; + + // Functions with the same name can override each other; same values can override each other + return sameFunctionOrValue(property1, property2, validator); +} + +function border(property1, property2, validator) { + return color(property1.components[2], property2.components[2], validator); +} + +// Use for color properties (color, background-color, border-color, etc.) +function color(property1, property2, validator) { + // The idea here is that 'more understandable' values override 'less understandable' values, but not vice versa + // Understandability: (hex | named) > (rgba | hsla) > (same function name) > anything else + // NOTE: at this point rgb and hsl are replaced by hex values by clean-css + + var color1 = property1.value[0][0]; + var color2 = property2.value[0][0]; + + if (!validator.colorOpacity && (validator.isValidRgbaColor(color1) || validator.isValidHslaColor(color1))) + return false; + if (!validator.colorOpacity && (validator.isValidRgbaColor(color2) || validator.isValidHslaColor(color2))) + return false; + + // (hex | named) + if (validator.isValidNamedColor(color2) || validator.isValidHexColor(color2)) + return true; + if (validator.isValidNamedColor(color1) || validator.isValidHexColor(color1)) + return false; + + // (rgba|hsla) + if (validator.isValidRgbaColor(color2) || validator.isValidHslaColor(color2)) + return true; + if (validator.isValidRgbaColor(color1) || validator.isValidHslaColor(color1)) + return false; + + // Functions with the same name can override each other; same values can override each other + return sameFunctionOrValue(property1, property2, validator); +} + +function twoOptionalFunctions(property1, property2, validator) { + var value1 = property1.value[0][0]; + var value2 = property2.value[0][0]; + + return !(validator.isValidFunction(value1) ^ validator.isValidFunction(value2)); +} + +function sameValue(property1, property2) { + var value1 = property1.value[0][0]; + var value2 = property2.value[0][0]; + + return value1 === value2; +} + +function sameFunctionOrValue(property1, property2, validator) { + var value1 = property1.value[0][0]; + var value2 = property2.value[0][0]; + + // Functions with the same name can override each other + if (validator.areSameFunction(value1, value2)) + return true; + + return value1 === value2; +} + +// Use for properties containing CSS units (margin-top, padding-left, etc.) +function unit(property1, property2, validator) { + // The idea here is that 'more understandable' values override 'less understandable' values, but not vice versa + // Understandability: (unit without functions) > (same functions | standard functions) > anything else + // NOTE: there is no point in having different vendor-specific functions override each other or standard functions, + // or having standard functions override vendor-specific functions, but standard functions can override each other + // NOTE: vendor-specific property values are not taken into consideration here at the moment + var value1 = property1.value[0][0]; + var value2 = property2.value[0][0]; + + if (validator.isValidAndCompatibleUnitWithoutFunction(value1) && !validator.isValidAndCompatibleUnitWithoutFunction(value2)) + return false; + + if (validator.isValidUnitWithoutFunction(value2)) + return true; + if (validator.isValidUnitWithoutFunction(value1)) + return false; + + // Standard non-vendor-prefixed functions can override each other + if (validator.isValidFunctionWithoutVendorPrefix(value2) && validator.isValidFunctionWithoutVendorPrefix(value1)) { + return true; + } + + // Functions with the same name can override each other; same values can override each other + return sameFunctionOrValue(property1, property2, validator); +} + +module.exports = { + always: always, + backgroundImage: backgroundImage, + border: border, + color: color, + sameValue: sameValue, + sameFunctionOrValue: sameFunctionOrValue, + twoOptionalFunctions: twoOptionalFunctions, + unit: unit +}; + +},{}],15:[function(require,module,exports){ +var wrapSingle = require('./wrap-for-optimizing').single; + +function deep(property) { + var cloned = shallow(property); + for (var i = property.components.length - 1; i >= 0; i--) { + var component = shallow(property.components[i]); + component.value = property.components[i].value.slice(0); + cloned.components.unshift(component); + } + + cloned.dirty = true; + cloned.value = property.value.slice(0); + + return cloned; +} + +function shallow(property) { + var cloned = wrapSingle([[property.name, property.important, property.hack]]); + cloned.unused = false; + return cloned; +} + +module.exports = { + deep: deep, + shallow: shallow +}; + +},{"./wrap-for-optimizing":28}],16:[function(require,module,exports){ +// Contains the interpretation of CSS properties, as used by the property optimizer + +var breakUp = require('./break-up'); +var canOverride = require('./can-override'); +var restore = require('./restore'); + +// Properties to process +// Extend this object in order to add support for more properties in the optimizer. +// +// Each key in this object represents a CSS property and should be an object. +// Such an object contains properties that describe how the represented CSS property should be handled. +// Possible options: +// +// * components: array (Only specify for shorthand properties.) +// Contains the names of the granular properties this shorthand compacts. +// +// * canOverride: function (Default is canOverride.sameValue - meaning that they'll only be merged if they have the same value.) +// Returns whether two tokens of this property can be merged with each other. +// This property has no meaning for shorthands. +// +// * defaultValue: string +// Specifies the default value of the property according to the CSS standard. +// For shorthand, this is used when every component is set to its default value, therefore it should be the shortest possible default value of all the components. +// +// * shortestValue: string +// Specifies the shortest possible value the property can possibly have. +// (Falls back to defaultValue if unspecified.) +// +// * breakUp: function (Only specify for shorthand properties.) +// Breaks the shorthand up to its components. +// +// * restore: function (Only specify for shorthand properties.) +// Puts the shorthand together from its components. +// +var compactable = { + 'color': { + canOverride: canOverride.color, + defaultValue: 'transparent', + shortestValue: 'red' + }, + 'background': { + components: [ + 'background-image', + 'background-position', + 'background-size', + 'background-repeat', + 'background-attachment', + 'background-origin', + 'background-clip', + 'background-color' + ], + breakUp: breakUp.multiplex(breakUp.background), + defaultValue: '0 0', + restore: restore.multiplex(restore.background), + shortestValue: '0', + shorthand: true + }, + 'background-clip': { + canOverride: canOverride.always, + defaultValue: 'border-box', + shortestValue: 'border-box' + }, + 'background-color': { + canOverride: canOverride.color, + defaultValue: 'transparent', + multiplexLastOnly: true, + nonMergeableValue: 'none', + shortestValue: 'red' + }, + 'background-image': { + canOverride: canOverride.backgroundImage, + defaultValue: 'none' + }, + 'background-origin': { + canOverride: canOverride.always, + defaultValue: 'padding-box', + shortestValue: 'border-box' + }, + 'background-repeat': { + canOverride: canOverride.always, + defaultValue: ['repeat'], + doubleValues: true + }, + 'background-position': { + canOverride: canOverride.always, + defaultValue: ['0', '0'], + doubleValues: true, + shortestValue: '0' + }, + 'background-size': { + canOverride: canOverride.always, + defaultValue: ['auto'], + doubleValues: true, + shortestValue: '0 0' + }, + 'background-attachment': { + canOverride: canOverride.always, + defaultValue: 'scroll' + }, + 'border': { + breakUp: breakUp.border, + canOverride: canOverride.border, + components: [ + 'border-width', + 'border-style', + 'border-color' + ], + defaultValue: 'none', + restore: restore.withoutDefaults, + shorthand: true + }, + 'border-color': { + canOverride: canOverride.color, + defaultValue: 'none', + shorthand: true + }, + 'border-style': { + canOverride: canOverride.always, + defaultValue: 'none', + shorthand: true + }, + 'border-width': { + canOverride: canOverride.unit, + defaultValue: 'medium', + shortestValue: '0', + shorthand: true + }, + 'list-style': { + components: [ + 'list-style-type', + 'list-style-position', + 'list-style-image' + ], + canOverride: canOverride.always, + breakUp: breakUp.listStyle, + restore: restore.withoutDefaults, + defaultValue: 'outside', // can't use 'disc' because that'd override default 'decimal' for
    + shortestValue: 'none', + shorthand: true + }, + 'list-style-type' : { + canOverride: canOverride.always, + defaultValue: '__hack', + // NOTE: we can't tell the real default value here, it's 'disc' for
      and 'decimal' for
        + // -- this is a hack, but it doesn't matter because this value will be either overridden or it will disappear at the final step anyway + shortestValue: 'none' + }, + 'list-style-position' : { + canOverride: canOverride.always, + defaultValue: 'outside', + shortestValue: 'inside' + }, + 'list-style-image' : { + canOverride: canOverride.always, + defaultValue: 'none' + }, + 'outline': { + components: [ + 'outline-color', + 'outline-style', + 'outline-width' + ], + breakUp: breakUp.outline, + restore: restore.withoutDefaults, + defaultValue: '0', + shorthand: true + }, + 'outline-color': { + canOverride: canOverride.color, + defaultValue: 'invert', + shortestValue: 'red' + }, + 'outline-style': { + canOverride: canOverride.always, + defaultValue: 'none' + }, + 'outline-width': { + canOverride: canOverride.unit, + defaultValue: 'medium', + shortestValue: '0' + }, + '-moz-transform': { + canOverride: canOverride.sameFunctionOrValue + }, + '-ms-transform': { + canOverride: canOverride.sameFunctionOrValue + }, + '-webkit-transform': { + canOverride: canOverride.sameFunctionOrValue + }, + 'transform': { + canOverride: canOverride.sameFunctionOrValue + } +}; + +var addFourValueShorthand = function (prop, components, options) { + options = options || {}; + compactable[prop] = { + canOverride: options.canOverride, + components: components, + breakUp: options.breakUp || breakUp.fourValues, + defaultValue: options.defaultValue || '0', + restore: options.restore || restore.fourValues, + shortestValue: options.shortestValue, + shorthand: true + }; + for (var i = 0; i < components.length; i++) { + compactable[components[i]] = { + breakUp: options.breakUp || breakUp.fourValues, + canOverride: options.canOverride || canOverride.unit, + defaultValue: options.defaultValue || '0', + shortestValue: options.shortestValue + }; + } +}; + +['', '-moz-', '-o-', '-webkit-'].forEach(function (prefix) { + addFourValueShorthand(prefix + 'border-radius', [ + prefix + 'border-top-left-radius', + prefix + 'border-top-right-radius', + prefix + 'border-bottom-right-radius', + prefix + 'border-bottom-left-radius' + ], { + breakUp: breakUp.borderRadius, + restore: restore.borderRadius + }); +}); + +addFourValueShorthand('border-color', [ + 'border-top-color', + 'border-right-color', + 'border-bottom-color', + 'border-left-color' +], { + breakUp: breakUp.fourValues, + canOverride: canOverride.color, + defaultValue: 'none', + shortestValue: 'red' +}); + +addFourValueShorthand('border-style', [ + 'border-top-style', + 'border-right-style', + 'border-bottom-style', + 'border-left-style' +], { + breakUp: breakUp.fourValues, + canOverride: canOverride.always, + defaultValue: 'none' +}); + +addFourValueShorthand('border-width', [ + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width' +], { + defaultValue: 'medium', + shortestValue: '0' +}); + +addFourValueShorthand('padding', [ + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left' +]); + +addFourValueShorthand('margin', [ + 'margin-top', + 'margin-right', + 'margin-bottom', + 'margin-left' +]); + +// Adds `componentOf` field to all longhands +for (var property in compactable) { + if (compactable[property].shorthand) { + for (var i = 0, l = compactable[property].components.length; i < l; i++) { + compactable[compactable[property].components[i]].componentOf = property; + } + } +} + +module.exports = compactable; + +},{"./break-up":13,"./can-override":14,"./restore":24}],17:[function(require,module,exports){ +var shallowClone = require('./clone').shallow; + +var MULTIPLEX_SEPARATOR = ','; + +function everyCombination(fn, left, right, validator) { + var _left = shallowClone(left); + var _right = shallowClone(right); + + for (var i = 0, l = left.value.length; i < l; i++) { + for (var j = 0, m = right.value.length; j < m; j++) { + if (left.value[i][0] == MULTIPLEX_SEPARATOR || right.value[j][0] == MULTIPLEX_SEPARATOR) + continue; + + _left.value = [left.value[i]]; + _right.value = [right.value[j]]; + if (!fn(_left, _right, validator)) + return false; + } + } + + return true; +} + +module.exports = everyCombination; + +},{"./clone":15}],18:[function(require,module,exports){ +function hasInherit(property) { + for (var i = property.value.length - 1; i >= 0; i--) { + if (property.value[i][0] == 'inherit') + return true; + } + + return false; +} + +module.exports = hasInherit; + +},{}],19:[function(require,module,exports){ +var compactable = require('./compactable'); +var wrapForOptimizing = require('./wrap-for-optimizing').all; +var populateComponents = require('./populate-components'); +var compactOverrides = require('./override-compactor'); +var compactShorthands = require('./shorthand-compactor'); +var removeUnused = require('./remove-unused'); +var restoreFromOptimizing = require('./restore-from-optimizing'); +var stringifyProperty = require('../stringifier/one-time').property; + +var shorthands = { + 'animation-delay': ['animation'], + 'animation-direction': ['animation'], + 'animation-duration': ['animation'], + 'animation-fill-mode': ['animation'], + 'animation-iteration-count': ['animation'], + 'animation-name': ['animation'], + 'animation-play-state': ['animation'], + 'animation-timing-function': ['animation'], + '-moz-animation-delay': ['-moz-animation'], + '-moz-animation-direction': ['-moz-animation'], + '-moz-animation-duration': ['-moz-animation'], + '-moz-animation-fill-mode': ['-moz-animation'], + '-moz-animation-iteration-count': ['-moz-animation'], + '-moz-animation-name': ['-moz-animation'], + '-moz-animation-play-state': ['-moz-animation'], + '-moz-animation-timing-function': ['-moz-animation'], + '-o-animation-delay': ['-o-animation'], + '-o-animation-direction': ['-o-animation'], + '-o-animation-duration': ['-o-animation'], + '-o-animation-fill-mode': ['-o-animation'], + '-o-animation-iteration-count': ['-o-animation'], + '-o-animation-name': ['-o-animation'], + '-o-animation-play-state': ['-o-animation'], + '-o-animation-timing-function': ['-o-animation'], + '-webkit-animation-delay': ['-webkit-animation'], + '-webkit-animation-direction': ['-webkit-animation'], + '-webkit-animation-duration': ['-webkit-animation'], + '-webkit-animation-fill-mode': ['-webkit-animation'], + '-webkit-animation-iteration-count': ['-webkit-animation'], + '-webkit-animation-name': ['-webkit-animation'], + '-webkit-animation-play-state': ['-webkit-animation'], + '-webkit-animation-timing-function': ['-webkit-animation'], + 'border-color': ['border'], + 'border-style': ['border'], + 'border-width': ['border'], + 'border-bottom': ['border'], + 'border-bottom-color': ['border-bottom', 'border-color', 'border'], + 'border-bottom-style': ['border-bottom', 'border-style', 'border'], + 'border-bottom-width': ['border-bottom', 'border-width', 'border'], + 'border-left': ['border'], + 'border-left-color': ['border-left', 'border-color', 'border'], + 'border-left-style': ['border-left', 'border-style', 'border'], + 'border-left-width': ['border-left', 'border-width', 'border'], + 'border-right': ['border'], + 'border-right-color': ['border-right', 'border-color', 'border'], + 'border-right-style': ['border-right', 'border-style', 'border'], + 'border-right-width': ['border-right', 'border-width', 'border'], + 'border-top': ['border'], + 'border-top-color': ['border-top', 'border-color', 'border'], + 'border-top-style': ['border-top', 'border-style', 'border'], + 'border-top-width': ['border-top', 'border-width', 'border'], + 'font-family': ['font'], + 'font-size': ['font'], + 'font-style': ['font'], + 'font-variant': ['font'], + 'font-weight': ['font'], + 'transition-delay': ['transition'], + 'transition-duration': ['transition'], + 'transition-property': ['transition'], + 'transition-timing-function': ['transition'], + '-moz-transition-delay': ['-moz-transition'], + '-moz-transition-duration': ['-moz-transition'], + '-moz-transition-property': ['-moz-transition'], + '-moz-transition-timing-function': ['-moz-transition'], + '-o-transition-delay': ['-o-transition'], + '-o-transition-duration': ['-o-transition'], + '-o-transition-property': ['-o-transition'], + '-o-transition-timing-function': ['-o-transition'], + '-webkit-transition-delay': ['-webkit-transition'], + '-webkit-transition-duration': ['-webkit-transition'], + '-webkit-transition-property': ['-webkit-transition'], + '-webkit-transition-timing-function': ['-webkit-transition'] +}; + +function _optimize(properties, mergeAdjacent, aggressiveMerging, validator) { + var overrideMapping = {}; + var lastName = null; + var lastProperty; + var j; + + function mergeablePosition(position) { + if (mergeAdjacent === false || mergeAdjacent === true) + return mergeAdjacent; + + return mergeAdjacent.indexOf(position) > -1; + } + + function sameValue(position) { + var left = properties[position - 1]; + var right = properties[position]; + + return stringifyProperty(left.all, left.position) == stringifyProperty(right.all, right.position); + } + + propertyLoop: + for (var position = 0, total = properties.length; position < total; position++) { + var property = properties[position]; + var _name = (property.name == '-ms-filter' || property.name == 'filter') ? + (lastName == 'background' || lastName == 'background-image' ? lastName : property.name) : + property.name; + var isImportant = property.important; + var isHack = property.hack; + + if (property.unused) + continue; + + if (position > 0 && lastProperty && _name == lastName && isImportant == lastProperty.important && isHack == lastProperty.hack && sameValue(position) && !lastProperty.unused) { + property.unused = true; + continue; + } + + // comment is necessary - we assume that if two properties are one after another + // then it is intentional way of redefining property which may not be widely supported + // e.g. a{display:inline-block;display:-moz-inline-box} + // however if `mergeablePosition` yields true then the rule does not apply + // (e.g merging two adjacent selectors: `a{display:block}a{display:block}`) + if (_name in overrideMapping && (aggressiveMerging && _name != lastName || mergeablePosition(position))) { + var toOverridePositions = overrideMapping[_name]; + var canOverride = compactable[_name] && compactable[_name].canOverride; + var anyRemoved = false; + + for (j = toOverridePositions.length - 1; j >= 0; j--) { + var toRemove = properties[toOverridePositions[j]]; + var longhandToShorthand = toRemove.name != _name; + var wasImportant = toRemove.important; + var wasHack = toRemove.hack; + + if (toRemove.unused) + continue; + + if (longhandToShorthand && wasImportant) + continue; + + if (!wasImportant && (wasHack && !isHack || !wasHack && isHack)) + continue; + + if (wasImportant && (isHack == 'star' || isHack == 'underscore')) + continue; + + if (!wasHack && !isHack && !longhandToShorthand && canOverride && !canOverride(toRemove, property, validator)) + continue; + + if (wasImportant && !isImportant || wasImportant && isHack) { + property.unused = true; + lastProperty = property; + continue propertyLoop; + } else { + anyRemoved = true; + toRemove.unused = true; + } + } + + if (anyRemoved) { + position = -1; + lastProperty = null; + lastName = null; + overrideMapping = {}; + continue; + } + } else { + overrideMapping[_name] = overrideMapping[_name] || []; + overrideMapping[_name].push(position); + + // TODO: to be removed with + // certain shorthand (see values of `shorthands`) should trigger removal of + // longhand properties (see keys of `shorthands`) + var _shorthands = shorthands[_name]; + if (_shorthands) { + for (j = _shorthands.length - 1; j >= 0; j--) { + var shorthand = _shorthands[j]; + overrideMapping[shorthand] = overrideMapping[shorthand] || []; + overrideMapping[shorthand].push(position); + } + } + } + + lastName = _name; + lastProperty = property; + } +} + +function optimize(selector, properties, mergeAdjacent, withCompacting, options, validator) { + var _properties = wrapForOptimizing(properties); + populateComponents(_properties, validator); + _optimize(_properties, mergeAdjacent, options.aggressiveMerging, validator); + + for (var i = 0, l = _properties.length; i < l; i++) { + var _property = _properties[i]; + if (_property.variable && _property.block) + optimize(selector, _property.value[0], mergeAdjacent, withCompacting, options, validator); + } + + if (withCompacting && options.shorthandCompacting) { + compactOverrides(_properties, options.compatibility, validator); + compactShorthands(_properties, options.sourceMap, validator); + } + + restoreFromOptimizing(_properties); + removeUnused(_properties); +} + +module.exports = optimize; + +},{"../stringifier/one-time":45,"./compactable":16,"./override-compactor":20,"./populate-components":21,"./remove-unused":22,"./restore-from-optimizing":23,"./shorthand-compactor":25,"./wrap-for-optimizing":28}],20:[function(require,module,exports){ +var canOverride = require('./can-override'); +var compactable = require('./compactable'); +var deepClone = require('./clone').deep; +var shallowClone = require('./clone').shallow; +var hasInherit = require('./has-inherit'); +var restoreFromOptimizing = require('./restore-from-optimizing'); +var everyCombination = require('./every-combination'); +var sameVendorPrefixesIn = require('./vendor-prefixes').same; + +var stringifyProperty = require('../stringifier/one-time').property; + +var MULTIPLEX_SEPARATOR = ','; + +// Used when searching for a component that matches property +function nameMatchFilter(to) { + return function (property) { + return to.name === property.name; + }; +} + +function wouldBreakCompatibility(property, validator) { + for (var i = 0; i < property.components.length; i++) { + var component = property.components[i]; + var descriptor = compactable[component.name]; + var canOverride = descriptor && descriptor.canOverride || canOverride.sameValue; + + var _component = shallowClone(component); + _component.value = [[descriptor.defaultValue]]; + + if (!canOverride(_component, component, validator)) + return true; + } + + return false; +} + +function isComponentOf(shorthand, longhand) { + return compactable[shorthand.name].components.indexOf(longhand.name) > -1; +} + +function overrideIntoMultiplex(property, by) { + by.unused = true; + + turnIntoMultiplex(by, multiplexSize(property)); + property.value = by.value; +} + +function overrideByMultiplex(property, by) { + by.unused = true; + property.multiplex = true; + property.value = by.value; +} + +function overrideSimple(property, by) { + by.unused = true; + property.value = by.value; +} + +function override(property, by) { + if (by.multiplex) + overrideByMultiplex(property, by); + else if (property.multiplex) + overrideIntoMultiplex(property, by); + else + overrideSimple(property, by); +} + +function overrideShorthand(property, by) { + by.unused = true; + + for (var i = 0, l = property.components.length; i < l; i++) { + override(property.components[i], by.components[i], property.multiplex); + } +} + +function turnIntoMultiplex(property, size) { + property.multiplex = true; + + for (var i = 0, l = property.components.length; i < l; i++) { + var component = property.components[i]; + if (component.multiplex) + continue; + + var value = component.value.slice(0); + + for (var j = 1; j < size; j++) { + component.value.push([MULTIPLEX_SEPARATOR]); + Array.prototype.push.apply(component.value, value); + } + } +} + +function multiplexSize(component) { + var size = 0; + + for (var i = 0, l = component.value.length; i < l; i++) { + if (component.value[i][0] == MULTIPLEX_SEPARATOR) + size++; + } + + return size + 1; +} + +function lengthOf(property) { + var fakeAsArray = [[property.name]].concat(property.value); + return stringifyProperty([fakeAsArray], 0).length; +} + +function moreSameShorthands(properties, startAt, name) { + // Since we run the main loop in `compactOverrides` backwards, at this point some + // properties may not be marked as unused. + // We should consider reverting the order if possible + var count = 0; + + for (var i = startAt; i >= 0; i--) { + if (properties[i].name == name && !properties[i].unused) + count++; + if (count > 1) + break; + } + + return count > 1; +} + +function overridingFunction(shorthand, validator) { + for (var i = 0, l = shorthand.components.length; i < l; i++) { + if (anyValue(validator.isValidFunction, shorthand.components[i])) + return true; + } + + return false; +} + +function anyValue(fn, property) { + for (var i = 0, l = property.value.length; i < l; i++) { + if (property.value[i][0] == MULTIPLEX_SEPARATOR) + continue; + + if (fn(property.value[i][0])) + return true; + } + + return false; +} + +function wouldResultInLongerValue(left, right) { + if (!left.multiplex && !right.multiplex || left.multiplex && right.multiplex) + return false; + + var multiplex = left.multiplex ? left : right; + var simple = left.multiplex ? right : left; + var component; + + var multiplexClone = deepClone(multiplex); + restoreFromOptimizing([multiplexClone]); + + var simpleClone = deepClone(simple); + restoreFromOptimizing([simpleClone]); + + var lengthBefore = lengthOf(multiplexClone) + 1 + lengthOf(simpleClone); + + if (left.multiplex) { + component = multiplexClone.components.filter(nameMatchFilter(simpleClone))[0]; + overrideIntoMultiplex(component, simpleClone); + } else { + component = simpleClone.components.filter(nameMatchFilter(multiplexClone))[0]; + turnIntoMultiplex(simpleClone, multiplexSize(multiplexClone)); + overrideByMultiplex(component, multiplexClone); + } + + restoreFromOptimizing([simpleClone]); + + var lengthAfter = lengthOf(simpleClone); + + return lengthBefore < lengthAfter; +} + +function isCompactable(property) { + return property.name in compactable; +} + +function noneOverrideHack(left, right) { + return !left.multiplex && + (left.name == 'background' || left.name == 'background-image') && + right.multiplex && + (right.name == 'background' || right.name == 'background-image') && + anyLayerIsNone(right.value); +} + +function anyLayerIsNone(values) { + var layers = intoLayers(values); + + for (var i = 0, l = layers.length; i < l; i++) { + if (layers[i].length == 1 && layers[i][0][0] == 'none') + return true; + } + + return false; +} + +function intoLayers(values) { + var layers = []; + + for (var i = 0, layer = [], l = values.length; i < l; i++) { + var value = values[i]; + if (value[0] == MULTIPLEX_SEPARATOR) { + layers.push(layer); + layer = []; + } else { + layer.push(value); + } + } + + layers.push(layer); + return layers; +} + +function compactOverrides(properties, compatibility, validator) { + var mayOverride, right, left, component; + var i, j, k; + + propertyLoop: + for (i = properties.length - 1; i >= 0; i--) { + right = properties[i]; + + if (!isCompactable(right)) + continue; + + if (right.variable) + continue; + + mayOverride = compactable[right.name].canOverride || canOverride.sameValue; + + for (j = i - 1; j >= 0; j--) { + left = properties[j]; + + if (!isCompactable(left)) + continue; + + if (left.variable) + continue; + + if (left.unused || right.unused) + continue; + + if (left.hack && !right.hack || !left.hack && right.hack) + continue; + + if (hasInherit(right)) + continue; + + if (noneOverrideHack(left, right)) + continue; + + if (!left.shorthand && right.shorthand && isComponentOf(right, left)) { + // maybe `left` can be overridden by `right` which is a shorthand? + if (!right.important && left.important) + continue; + + if (!sameVendorPrefixesIn([left], right.components)) + continue; + + if (!anyValue(validator.isValidFunction, left) && overridingFunction(right, validator)) + continue; + + component = right.components.filter(nameMatchFilter(left))[0]; + mayOverride = (compactable[left.name] && compactable[left.name].canOverride) || canOverride.sameValue; + if (everyCombination(mayOverride, left, component, validator)) { + left.unused = true; + } + } else if (left.shorthand && !right.shorthand && isComponentOf(left, right)) { + // maybe `right` can be pulled into `left` which is a shorthand? + if (right.important && !left.important) + continue; + + // Pending more clever algorithm in #527 + if (moreSameShorthands(properties, i - 1, left.name)) + continue; + + if (overridingFunction(left, validator)) + continue; + + component = left.components.filter(nameMatchFilter(right))[0]; + if (everyCombination(mayOverride, component, right, validator)) { + var disabledBackgroundMerging = + !compatibility.properties.backgroundClipMerging && component.name.indexOf('background-clip') > -1 || + !compatibility.properties.backgroundOriginMerging && component.name.indexOf('background-origin') > -1 || + !compatibility.properties.backgroundSizeMerging && component.name.indexOf('background-size') > -1; + var nonMergeableValue = compactable[right.name].nonMergeableValue === right.value[0][0]; + + if (disabledBackgroundMerging || nonMergeableValue) + continue; + + if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator)) + continue; + + if (component.value[0][0] != right.value[0][0] && (hasInherit(left) || hasInherit(right))) + continue; + + if (wouldResultInLongerValue(left, right)) + continue; + + if (!left.multiplex && right.multiplex) + turnIntoMultiplex(left, multiplexSize(right)); + + override(component, right); + left.dirty = true; + } + } else if (left.shorthand && right.shorthand && left.name == right.name) { + // merge if all components can be merged + + if (!left.multiplex && right.multiplex) + continue; + + if (!right.important && left.important) { + right.unused = true; + continue propertyLoop; + } + + if (right.important && !left.important) { + left.unused = true; + continue; + } + + for (k = left.components.length - 1; k >= 0; k--) { + var leftComponent = left.components[k]; + var rightComponent = right.components[k]; + + mayOverride = compactable[leftComponent.name].canOverride || canOverride.sameValue; + if (!everyCombination(mayOverride, leftComponent, rightComponent, validator)) + continue propertyLoop; + if (!everyCombination(canOverride.twoOptionalFunctions, leftComponent, rightComponent, validator) && validator.isValidFunction(rightComponent)) + continue propertyLoop; + } + + overrideShorthand(left, right); + left.dirty = true; + } else if (left.shorthand && right.shorthand && isComponentOf(left, right)) { + // border is a shorthand but any of its components is a shorthand too + + if (!left.important && right.important) + continue; + + component = left.components.filter(nameMatchFilter(right))[0]; + mayOverride = compactable[right.name].canOverride || canOverride.sameValue; + if (!everyCombination(mayOverride, component, right, validator)) + continue; + + if (left.important && !right.important) { + right.unused = true; + continue; + } + + var rightRestored = compactable[right.name].restore(right, compactable); + if (rightRestored.length > 1) + continue; + + component = left.components.filter(nameMatchFilter(right))[0]; + override(component, right); + right.dirty = true; + } else if (left.name == right.name) { + // two non-shorthands should be merged based on understandability + + if (left.important && !right.important) { + right.unused = true; + continue; + } + + mayOverride = compactable[right.name].canOverride || canOverride.sameValue; + if (!everyCombination(mayOverride, left, right, validator)) + continue; + + left.unused = true; + } + } + } +} + +module.exports = compactOverrides; + +},{"../stringifier/one-time":45,"./can-override":14,"./clone":15,"./compactable":16,"./every-combination":17,"./has-inherit":18,"./restore-from-optimizing":23,"./vendor-prefixes":27}],21:[function(require,module,exports){ +var compactable = require('./compactable'); + +function populateComponents(properties, validator) { + for (var i = properties.length - 1; i >= 0; i--) { + var property = properties[i]; + var descriptor = compactable[property.name]; + + if (descriptor && descriptor.shorthand) { + property.shorthand = true; + property.dirty = true; + property.components = descriptor.breakUp(property, compactable, validator); + + if (property.components.length > 0) + property.multiplex = property.components[0].multiplex; + else + property.unused = true; + } + } +} + +module.exports = populateComponents; + +},{"./compactable":16}],22:[function(require,module,exports){ +function removeUnused(properties) { + for (var i = properties.length - 1; i >= 0; i--) { + var property = properties[i]; + + if (property.unused) + property.all.splice(property.position, 1); + } +} + +module.exports = removeUnused; + +},{}],23:[function(require,module,exports){ +var compactable = require('./compactable'); + +var BACKSLASH_HACK = '\\9'; +var IMPORTANT_TOKEN = '!important'; +var STAR_HACK = '*'; +var UNDERSCORE_HACK = '_'; +var BANG_HACK = '!ie'; + +function restoreImportant(property) { + property.value[property.value.length - 1][0] += IMPORTANT_TOKEN; +} + +function restoreHack(property) { + if (property.hack == 'underscore') + property.name = UNDERSCORE_HACK + property.name; + else if (property.hack == 'star') + property.name = STAR_HACK + property.name; + else if (property.hack == 'backslash') + property.value[property.value.length - 1][0] += BACKSLASH_HACK; + else if (property.hack == 'bang') + property.value[property.value.length - 1][0] += ' ' + BANG_HACK; +} + +function restoreFromOptimizing(properties, simpleMode) { + for (var i = properties.length - 1; i >= 0; i--) { + var property = properties[i]; + var descriptor = compactable[property.name]; + var restored; + + if (property.unused) + continue; + + if (!property.dirty && !property.important && !property.hack) + continue; + + if (!simpleMode && descriptor && descriptor.shorthand) { + restored = descriptor.restore(property, compactable); + property.value = restored; + } else { + restored = property.value; + } + + if (property.important) + restoreImportant(property); + + if (property.hack) + restoreHack(property); + + if (!('all' in property)) + continue; + + var current = property.all[property.position]; + current[0][0] = property.name; + + current.splice(1, current.length - 1); + Array.prototype.push.apply(current, restored); + } +} + +module.exports = restoreFromOptimizing; + +},{"./compactable":16}],24:[function(require,module,exports){ +var shallowClone = require('./clone').shallow; +var MULTIPLEX_SEPARATOR = ','; +var SIZE_POSITION_SEPARATOR = '/'; + +function isInheritOnly(values) { + for (var i = 0, l = values.length; i < l; i++) { + var value = values[i][0]; + + if (value != 'inherit' && value != MULTIPLEX_SEPARATOR && value != SIZE_POSITION_SEPARATOR) + return false; + } + + return true; +} + +function background(property, compactable, lastInMultiplex) { + var components = property.components; + var restored = []; + var needsOne, needsBoth; + + function restoreValue(component) { + Array.prototype.unshift.apply(restored, component.value); + } + + function isDefaultValue(component) { + var descriptor = compactable[component.name]; + if (descriptor.doubleValues) { + if (descriptor.defaultValue.length == 1) + return component.value[0][0] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][0] == descriptor.defaultValue[0] : true); + else + return component.value[0][0] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][0] : component.value[0][0]) == descriptor.defaultValue[1]; + } else { + return component.value[0][0] == descriptor.defaultValue; + } + } + + for (var i = components.length - 1; i >= 0; i--) { + var component = components[i]; + var isDefault = isDefaultValue(component); + + if (component.name == 'background-clip') { + var originComponent = components[i - 1]; + var isOriginDefault = isDefaultValue(originComponent); + + needsOne = component.value[0][0] == originComponent.value[0][0]; + + needsBoth = !needsOne && ( + (isOriginDefault && !isDefault) || + (!isOriginDefault && !isDefault) || + (!isOriginDefault && isDefault && component.value[0][0] != originComponent.value[0][0])); + + if (needsOne) { + restoreValue(originComponent); + } else if (needsBoth) { + restoreValue(component); + restoreValue(originComponent); + } + + i--; + } else if (component.name == 'background-size') { + var positionComponent = components[i - 1]; + var isPositionDefault = isDefaultValue(positionComponent); + + needsOne = !isPositionDefault && isDefault; + + needsBoth = !needsOne && + (isPositionDefault && !isDefault || !isPositionDefault && !isDefault); + + if (needsOne) { + restoreValue(positionComponent); + } else if (needsBoth) { + restoreValue(component); + restored.unshift([SIZE_POSITION_SEPARATOR]); + restoreValue(positionComponent); + } else if (positionComponent.value.length == 1) { + restoreValue(positionComponent); + } + + i--; + } else { + if (isDefault || compactable[component.name].multiplexLastOnly && !lastInMultiplex) + continue; + + restoreValue(component); + } + } + + if (restored.length === 0 && property.value.length == 1 && property.value[0][0] == '0') + restored.push(property.value[0]); + + if (restored.length === 0) + restored.push([compactable[property.name].defaultValue]); + + if (isInheritOnly(restored)) + return [restored[0]]; + + return restored; +} + +function borderRadius(property, compactable) { + if (property.multiplex) { + var horizontal = shallowClone(property); + var vertical = shallowClone(property); + + for (var i = 0; i < 4; i++) { + var component = property.components[i]; + + var horizontalComponent = shallowClone(property); + horizontalComponent.value = [component.value[0]]; + horizontal.components.push(horizontalComponent); + + var verticalComponent = shallowClone(property); + verticalComponent.value = [component.value[2]]; + vertical.components.push(verticalComponent); + } + + var horizontalValues = fourValues(horizontal, compactable); + var verticalValues = fourValues(vertical, compactable); + + if (horizontalValues.length == verticalValues.length && + horizontalValues[0][0] == verticalValues[0][0] && + (horizontalValues.length > 1 ? horizontalValues[1][0] == verticalValues[1][0] : true) && + (horizontalValues.length > 2 ? horizontalValues[2][0] == verticalValues[2][0] : true) && + (horizontalValues.length > 3 ? horizontalValues[3][0] == verticalValues[3][0] : true)) { + return horizontalValues; + } else { + return horizontalValues.concat([['/']]).concat(verticalValues); + } + } else { + return fourValues(property, compactable); + } +} + +function fourValues(property) { + var components = property.components; + var value1 = components[0].value[0]; + var value2 = components[1].value[0]; + var value3 = components[2].value[0]; + var value4 = components[3].value[0]; + + if (value1[0] == value2[0] && value1[0] == value3[0] && value1[0] == value4[0]) { + return [value1]; + } else if (value1[0] == value3[0] && value2[0] == value4[0]) { + return [value1, value2]; + } else if (value2[0] == value4[0]) { + return [value1, value2, value3]; + } else { + return [value1, value2, value3, value4]; + } +} + +function multiplex(restoreWith) { + return function (property, compactable) { + if (!property.multiplex) + return restoreWith(property, compactable, true); + + var multiplexSize = 0; + var restored = []; + var componentMultiplexSoFar = {}; + var i, l; + + // At this point we don't know what's the multiplex size, e.g. how many background layers are there + for (i = 0, l = property.components[0].value.length; i < l; i++) { + if (property.components[0].value[i][0] == MULTIPLEX_SEPARATOR) + multiplexSize++; + } + + for (i = 0; i <= multiplexSize; i++) { + var _property = shallowClone(property); + + // We split multiplex into parts and restore them one by one + for (var j = 0, m = property.components.length; j < m; j++) { + var componentToClone = property.components[j]; + var _component = shallowClone(componentToClone); + _property.components.push(_component); + + // The trick is some properties has more than one value, so we iterate over values looking for + // a multiplex separator - a comma + for (var k = componentMultiplexSoFar[_component.name] || 0, n = componentToClone.value.length; k < n; k++) { + if (componentToClone.value[k][0] == MULTIPLEX_SEPARATOR) { + componentMultiplexSoFar[_component.name] = k + 1; + break; + } + + _component.value.push(componentToClone.value[k]); + } + } + + // No we can restore shorthand value + var lastInMultiplex = i == multiplexSize; + var _restored = restoreWith(_property, compactable, lastInMultiplex); + Array.prototype.push.apply(restored, _restored); + + if (i < multiplexSize) + restored.push([',']); + } + + return restored; + }; +} + +function withoutDefaults(property, compactable) { + var components = property.components; + var restored = []; + + for (var i = components.length - 1; i >= 0; i--) { + var component = components[i]; + var descriptor = compactable[component.name]; + + if (component.value[0][0] != descriptor.defaultValue) + restored.unshift(component.value[0]); + } + + if (restored.length === 0) + restored.push([compactable[property.name].defaultValue]); + + if (isInheritOnly(restored)) + return [restored[0]]; + + return restored; +} + +module.exports = { + background: background, + borderRadius: borderRadius, + fourValues: fourValues, + multiplex: multiplex, + withoutDefaults: withoutDefaults +}; + +},{"./clone":15}],25:[function(require,module,exports){ +var compactable = require('./compactable'); +var deepClone = require('./clone').deep; +var hasInherit = require('./has-inherit'); +var populateComponents = require('./populate-components'); +var wrapSingle = require('./wrap-for-optimizing').single; +var everyCombination = require('./every-combination'); + +function mixedImportance(components) { + var important; + + for (var name in components) { + if (undefined !== important && components[name].important != important) + return true; + + important = components[name].important; + } + + return false; +} + +function componentSourceMaps(components) { + var sourceMapping = []; + + for (var name in components) { + var component = components[name]; + var originalValue = component.all[component.position]; + var mapping = originalValue[0][originalValue[0].length - 1]; + + if (Array.isArray(mapping)) + Array.prototype.push.apply(sourceMapping, mapping); + } + + return sourceMapping; +} + +function replaceWithShorthand(properties, candidateComponents, name, sourceMaps, validator) { + var descriptor = compactable[name]; + var newValuePlaceholder = [[name], [descriptor.defaultValue]]; + var all; + + var newProperty = wrapSingle(newValuePlaceholder); + newProperty.shorthand = true; + newProperty.dirty = true; + + populateComponents([newProperty], validator); + + for (var i = 0, l = descriptor.components.length; i < l; i++) { + var component = candidateComponents[descriptor.components[i]]; + var canOverride = compactable[component.name].canOverride; + + if (hasInherit(component)) + return; + + if (!everyCombination(canOverride, newProperty.components[i], component, validator)) + return; + + newProperty.components[i] = deepClone(component); + newProperty.important = component.important; + + all = component.all; + } + + for (var componentName in candidateComponents) { + candidateComponents[componentName].unused = true; + } + + if (sourceMaps) { + var sourceMapping = componentSourceMaps(candidateComponents); + if (sourceMapping.length > 0) + newValuePlaceholder[0].push(sourceMapping); + } + + newProperty.position = all.length; + newProperty.all = all; + newProperty.all.push(newValuePlaceholder); + + properties.push(newProperty); +} + +function invalidateOrCompact(properties, position, candidates, sourceMaps, validator) { + var property = properties[position]; + + for (var name in candidates) { + if (undefined !== property && name == property.name) + continue; + + var descriptor = compactable[name]; + var candidateComponents = candidates[name]; + if (descriptor.components.length > Object.keys(candidateComponents).length) { + delete candidates[name]; + continue; + } + + if (mixedImportance(candidateComponents)) + continue; + + replaceWithShorthand(properties, candidateComponents, name, sourceMaps, validator); + } +} + +function compactShortands(properties, sourceMaps, validator) { + var candidates = {}; + + if (properties.length < 3) + return; + + for (var i = 0, l = properties.length; i < l; i++) { + var property = properties[i]; + if (property.unused) + continue; + + if (property.hack) + continue; + + if (property.variable) + continue; + + var descriptor = compactable[property.name]; + if (!descriptor || !descriptor.componentOf) + continue; + + if (property.shorthand) { + invalidateOrCompact(properties, i, candidates, sourceMaps, validator); + } else { + var componentOf = descriptor.componentOf; + candidates[componentOf] = candidates[componentOf] || {}; + candidates[componentOf][property.name] = property; + } + } + + invalidateOrCompact(properties, i, candidates, sourceMaps, validator); +} + +module.exports = compactShortands; + +},{"./clone":15,"./compactable":16,"./every-combination":17,"./has-inherit":18,"./populate-components":21,"./wrap-for-optimizing":28}],26:[function(require,module,exports){ +// Validates various CSS property values + +var split = require('../utils/split'); + +var widthKeywords = ['thin', 'thick', 'medium', 'inherit', 'initial']; +var allUnits = ['px', '%', 'em', 'in', 'cm', 'mm', 'ex', 'pt', 'pc', 'ch', 'rem', 'vh', 'vm', 'vmin', 'vmax', 'vw']; +var cssUnitRegexStr = '(\\-?\\.?\\d+\\.?\\d*(' + allUnits.join('|') + '|)|auto|inherit)'; +var cssCalcRegexStr = '(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)'; +var cssFunctionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(.*?\\)'; +var cssFunctionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(.*?\\)'; +var cssVariableRegexStr = 'var\\(\\-\\-[^\\)]+\\)'; +var cssFunctionAnyRegexStr = '(' + cssVariableRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')'; +var cssUnitOrCalcRegexStr = '(' + cssUnitRegexStr + '|' + cssCalcRegexStr + ')'; +var cssUnitAnyRegexStr = '(none|' + widthKeywords.join('|') + '|' + cssUnitRegexStr + '|' + cssVariableRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')'; + +var cssFunctionNoVendorRegex = new RegExp('^' + cssFunctionNoVendorRegexStr + '$', 'i'); +var cssFunctionVendorRegex = new RegExp('^' + cssFunctionVendorRegexStr + '$', 'i'); +var cssVariableRegex = new RegExp('^' + cssVariableRegexStr + '$', 'i'); +var cssFunctionAnyRegex = new RegExp('^' + cssFunctionAnyRegexStr + '$', 'i'); +var cssUnitRegex = new RegExp('^' + cssUnitRegexStr + '$', 'i'); +var cssUnitOrCalcRegex = new RegExp('^' + cssUnitOrCalcRegexStr + '$', 'i'); +var cssUnitAnyRegex = new RegExp('^' + cssUnitAnyRegexStr + '$', 'i'); + +var backgroundRepeatKeywords = ['repeat', 'no-repeat', 'repeat-x', 'repeat-y', 'inherit']; +var backgroundAttachmentKeywords = ['inherit', 'scroll', 'fixed', 'local']; +var backgroundPositionKeywords = ['center', 'top', 'bottom', 'left', 'right']; +var backgroundSizeKeywords = ['contain', 'cover']; +var backgroundBoxKeywords = ['border-box', 'content-box', 'padding-box']; +var styleKeywords = ['auto', 'inherit', 'hidden', 'none', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']; +var listStyleTypeKeywords = ['armenian', 'circle', 'cjk-ideographic', 'decimal', 'decimal-leading-zero', 'disc', 'georgian', 'hebrew', 'hiragana', 'hiragana-iroha', 'inherit', 'katakana', 'katakana-iroha', 'lower-alpha', 'lower-greek', 'lower-latin', 'lower-roman', 'none', 'square', 'upper-alpha', 'upper-latin', 'upper-roman']; +var listStylePositionKeywords = ['inside', 'outside', 'inherit']; + +function Validator(compatibility) { + var validUnits = allUnits.slice(0).filter(function (value) { + return !(value in compatibility.units) || compatibility.units[value] === true; + }); + + var compatibleCssUnitRegexStr = '(\\-?\\.?\\d+\\.?\\d*(' + validUnits.join('|') + '|)|auto|inherit)'; + this.compatibleCssUnitRegex = new RegExp('^' + compatibleCssUnitRegexStr + '$', 'i'); + this.compatibleCssUnitAnyRegex = new RegExp('^(none|' + widthKeywords.join('|') + '|' + compatibleCssUnitRegexStr + '|' + cssVariableRegexStr + '|' + cssFunctionNoVendorRegexStr + '|' + cssFunctionVendorRegexStr + ')$', 'i'); + + this.colorOpacity = compatibility.colors.opacity; +} + +Validator.prototype.isValidHexColor = function (s) { + return (s.length === 4 || s.length === 7) && s[0] === '#'; +}; + +Validator.prototype.isValidRgbaColor = function (s) { + s = s.split(' ').join(''); + return s.length > 0 && s.indexOf('rgba(') === 0 && s.indexOf(')') === s.length - 1; +}; + +Validator.prototype.isValidHslaColor = function (s) { + s = s.split(' ').join(''); + return s.length > 0 && s.indexOf('hsla(') === 0 && s.indexOf(')') === s.length - 1; +}; + +Validator.prototype.isValidNamedColor = function (s) { + // We don't really check if it's a valid color value, but allow any letters in it + return s !== 'auto' && (s === 'transparent' || s === 'inherit' || /^[a-zA-Z]+$/.test(s)); +}; + +Validator.prototype.isValidVariable = function (s) { + return cssVariableRegex.test(s); +}; + +Validator.prototype.isValidColor = function (s) { + return this.isValidNamedColor(s) || + this.isValidColorValue(s) || + this.isValidVariable(s) || + this.isValidVendorPrefixedValue(s); +}; + +Validator.prototype.isValidColorValue = function (s) { + return this.isValidHexColor(s) || + this.isValidRgbaColor(s) || + this.isValidHslaColor(s); +}; + +Validator.prototype.isValidUrl = function (s) { + // NOTE: at this point all URLs are replaced with placeholders by clean-css, so we check for those placeholders + return s.indexOf('__ESCAPED_URL_CLEAN_CSS') === 0; +}; + +Validator.prototype.isValidUnit = function (s) { + return cssUnitAnyRegex.test(s); +}; + +Validator.prototype.isValidUnitWithoutFunction = function (s) { + return cssUnitRegex.test(s); +}; + +Validator.prototype.isValidAndCompatibleUnit = function (s) { + return this.compatibleCssUnitAnyRegex.test(s); +}; + +Validator.prototype.isValidAndCompatibleUnitWithoutFunction = function (s) { + return this.compatibleCssUnitRegex.test(s); +}; + +Validator.prototype.isValidFunctionWithoutVendorPrefix = function (s) { + return cssFunctionNoVendorRegex.test(s); +}; + +Validator.prototype.isValidFunctionWithVendorPrefix = function (s) { + return cssFunctionVendorRegex.test(s); +}; + +Validator.prototype.isValidFunction = function (s) { + return cssFunctionAnyRegex.test(s); +}; + +Validator.prototype.isValidBackgroundRepeat = function (s) { + return backgroundRepeatKeywords.indexOf(s) >= 0 || this.isValidVariable(s); +}; + +Validator.prototype.isValidBackgroundAttachment = function (s) { + return backgroundAttachmentKeywords.indexOf(s) >= 0 || this.isValidVariable(s); +}; + +Validator.prototype.isValidBackgroundBox = function (s) { + return backgroundBoxKeywords.indexOf(s) >= 0 || this.isValidVariable(s); +}; + +Validator.prototype.isValidBackgroundPositionPart = function (s) { + return backgroundPositionKeywords.indexOf(s) >= 0 || cssUnitOrCalcRegex.test(s) || this.isValidVariable(s); +}; + +Validator.prototype.isValidBackgroundPosition = function (s) { + if (s === 'inherit') + return true; + + var parts = s.split(' '); + for (var i = 0, l = parts.length; i < l; i++) { + if (parts[i] === '') + continue; + if (this.isValidBackgroundPositionPart(parts[i]) || this.isValidVariable(parts[i])) + continue; + + return false; + } + + return true; +}; + +Validator.prototype.isValidBackgroundSizePart = function (s) { + return backgroundSizeKeywords.indexOf(s) >= 0 || cssUnitRegex.test(s) || this.isValidVariable(s); +}; + +Validator.prototype.isValidBackgroundPositionAndSize = function (s) { + if (s.indexOf('/') < 0) + return false; + + var twoParts = split(s, '/'); + return this.isValidBackgroundSizePart(twoParts.pop()) && this.isValidBackgroundPositionPart(twoParts.pop()); +}; + +Validator.prototype.isValidListStyleType = function (s) { + return listStyleTypeKeywords.indexOf(s) >= 0 || this.isValidVariable(s); +}; + +Validator.prototype.isValidListStylePosition = function (s) { + return listStylePositionKeywords.indexOf(s) >= 0 || this.isValidVariable(s); +}; + +Validator.prototype.isValidStyle = function (s) { + return this.isValidStyleKeyword(s) || this.isValidVariable(s); +}; + +Validator.prototype.isValidStyleKeyword = function (s) { + return styleKeywords.indexOf(s) >= 0; +}; + +Validator.prototype.isValidWidth = function (s) { + return this.isValidUnit(s) || this.isValidWidthKeyword(s) || this.isValidVariable(s); +}; + +Validator.prototype.isValidWidthKeyword = function (s) { + return widthKeywords.indexOf(s) >= 0; +}; + +Validator.prototype.isValidVendorPrefixedValue = function (s) { + return /^-([A-Za-z0-9]|-)*$/gi.test(s); +}; + +Validator.prototype.areSameFunction = function (a, b) { + if (!this.isValidFunction(a) || !this.isValidFunction(b)) + return false; + + var f1name = a.substring(0, a.indexOf('(')); + var f2name = b.substring(0, b.indexOf('(')); + + return f1name === f2name; +}; + +module.exports = Validator; + +},{"../utils/split":66}],27:[function(require,module,exports){ +var VENDOR_PREFIX_PATTERN = /$\-moz\-|\-ms\-|\-o\-|\-webkit\-/; + +function prefixesIn(tokens) { + var prefixes = []; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + for (var j = 0, m = token.value.length; j < m; j++) { + var match = VENDOR_PREFIX_PATTERN.exec(token.value[j][0]); + + if (match && prefixes.indexOf(match[0]) == -1) + prefixes.push(match[0]); + } + } + + return prefixes; +} + +function same(left, right) { + return prefixesIn(left).sort().join(',') == prefixesIn(right).sort().join(','); +} + +module.exports = { + same: same +}; + +},{}],28:[function(require,module,exports){ +var BACKSLASH_HACK = '\\'; +var IMPORTANT_TOKEN = '!important'; +var STAR_HACK = '*'; +var UNDERSCORE_HACK = '_'; +var BANG_HACK = '!'; + +function wrapAll(properties) { + var wrapped = []; + + for (var i = properties.length - 1; i >= 0; i--) { + if (typeof properties[i][0] == 'string') + continue; + + var single = wrapSingle(properties[i]); + single.all = properties; + single.position = i; + wrapped.unshift(single); + } + + return wrapped; +} + +function isMultiplex(property) { + for (var i = 1, l = property.length; i < l; i++) { + if (property[i][0] == ',' || property[i][0] == '/') + return true; + } + + return false; +} + +function hackType(property) { + var type = false; + var name = property[0][0]; + var lastValue = property[property.length - 1]; + + if (name[0] == UNDERSCORE_HACK) { + type = 'underscore'; + } else if (name[0] == STAR_HACK) { + type = 'star'; + } else if (lastValue[0][0] == BANG_HACK && lastValue[0].indexOf('important') == -1) { + type = 'bang'; + } else if (lastValue[0].indexOf(BANG_HACK) > 0 && lastValue[0].indexOf('important') == -1) { + type = 'bang'; + } else if (lastValue[0].indexOf(BACKSLASH_HACK) > 0 && lastValue[0].indexOf(BACKSLASH_HACK) == lastValue[0].length - BACKSLASH_HACK.length - 1) { + type = 'backslash'; + } else if (lastValue[0].indexOf(BACKSLASH_HACK) === 0 && lastValue[0].length == 2) { + type = 'backslash'; + } + + return type; +} + +function isImportant(property) { + return property.length > 1 ? + property[property.length - 1][0].indexOf(IMPORTANT_TOKEN) > 0 : + false; +} + +function stripImportant(property) { + if (property.length > 0) + property[property.length - 1][0] = property[property.length - 1][0].replace(IMPORTANT_TOKEN, ''); +} + +function stripPrefixHack(property) { + property[0][0] = property[0][0].substring(1); +} + +function stripSuffixHack(property, hackType) { + var lastValue = property[property.length - 1]; + lastValue[0] = lastValue[0] + .substring(0, lastValue[0].indexOf(hackType == 'backslash' ? BACKSLASH_HACK : BANG_HACK)) + .trim(); + + if (lastValue[0].length === 0) + property.pop(); +} + +function wrapSingle(property) { + var _isImportant = isImportant(property); + if (_isImportant) + stripImportant(property); + + var _hackType = hackType(property); + if (_hackType == 'star' || _hackType == 'underscore') + stripPrefixHack(property); + else if (_hackType == 'backslash' || _hackType == 'bang') + stripSuffixHack(property, _hackType); + + var isVariable = property[0][0].indexOf('--') === 0; + + return { + block: isVariable && property[1] && Array.isArray(property[1][0][0]), + components: [], + dirty: false, + hack: _hackType, + important: _isImportant, + name: property[0][0], + multiplex: property.length > 2 ? isMultiplex(property) : false, + position: 0, + shorthand: false, + unused: property.length < 2, + value: property.slice(1), + variable: isVariable + }; +} + +module.exports = { + all: wrapAll, + single: wrapSingle +}; + +},{}],29:[function(require,module,exports){ +var optimizeProperties = require('../properties/optimizer'); + +var removeDuplicates = require('./remove-duplicates'); +var mergeAdjacent = require('./merge-adjacent'); +var reduceNonAdjacent = require('./reduce-non-adjacent'); +var mergeNonAdjacentBySelector = require('./merge-non-adjacent-by-selector'); +var mergeNonAdjacentByBody = require('./merge-non-adjacent-by-body'); +var restructure = require('./restructure'); +var removeDuplicateMediaQueries = require('./remove-duplicate-media-queries'); +var mergeMediaQueries = require('./merge-media-queries'); + +function removeEmpty(tokens) { + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + var isEmpty = false; + + switch (token[0]) { + case 'selector': + isEmpty = token[1].length === 0 || token[2].length === 0; + break; + case 'block': + removeEmpty(token[2]); + isEmpty = token[2].length === 0; + } + + if (isEmpty) { + tokens.splice(i, 1); + i--; + l--; + } + } +} + +function recursivelyOptimizeBlocks(tokens, options, validator) { + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + if (token[0] == 'block') { + var isKeyframes = /@(-moz-|-o-|-webkit-)?keyframes/.test(token[1][0]); + optimize(token[2], options, validator, !isKeyframes); + } + } +} + +function recursivelyOptimizeProperties(tokens, options, validator) { + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + switch (token[0]) { + case 'selector': + optimizeProperties(token[1], token[2], false, true, options, validator); + break; + case 'block': + recursivelyOptimizeProperties(token[2], options, validator); + } + } +} + +function optimize(tokens, options, validator, withRestructuring) { + recursivelyOptimizeBlocks(tokens, options, validator); + recursivelyOptimizeProperties(tokens, options, validator); + + removeDuplicates(tokens); + mergeAdjacent(tokens, options, validator); + reduceNonAdjacent(tokens, options, validator); + + mergeNonAdjacentBySelector(tokens, options, validator); + mergeNonAdjacentByBody(tokens, options); + + if (options.restructuring && withRestructuring) { + restructure(tokens, options); + mergeAdjacent(tokens, options, validator); + } + + if (options.mediaMerging) { + removeDuplicateMediaQueries(tokens); + var reduced = mergeMediaQueries(tokens); + for (var i = reduced.length - 1; i >= 0; i--) { + optimize(reduced[i][2], options, validator, false); + } + } + + removeEmpty(tokens); +} + +module.exports = optimize; + +},{"../properties/optimizer":19,"./merge-adjacent":33,"./merge-media-queries":34,"./merge-non-adjacent-by-body":35,"./merge-non-adjacent-by-selector":36,"./reduce-non-adjacent":37,"./remove-duplicate-media-queries":38,"./remove-duplicates":39,"./restructure":41}],30:[function(require,module,exports){ +function removeWhitespace(match, value) { + return '[' + value.replace(/ /g, '') + ']'; +} + +function selectorSorter(s1, s2) { + return s1[0] > s2[0] ? 1 : -1; +} + +function whitespaceReplacements(_, p1, p2, p3) { + if (p1 && p2 && p3.length) + return p1 + p2 + ' '; + else if (p1 && p2) + return p1 + p2; + else + return p2; +} + +var CleanUp = { + selectors: function (selectors, removeUnsupported, adjacentSpace) { + var list = []; + var repeated = []; + + for (var i = 0, l = selectors.length; i < l; i++) { + var selector = selectors[i]; + var reduced = selector[0] + .replace(/\s+/g, ' ') + .replace(/ ?, ?/g, ',') + .replace(/\s*(\\)?([>+~])(\s*)/g, whitespaceReplacements) + .trim(); + + if (adjacentSpace && reduced.indexOf('nav') > 0) + reduced = reduced.replace(/\+nav(\S|$)/, '+ nav$1'); + + if (removeUnsupported && (reduced.indexOf('*+html ') != -1 || reduced.indexOf('*:first-child+html ') != -1)) + continue; + + if (reduced.indexOf('*') > -1) { + reduced = reduced + .replace(/\*([:#\.\[])/g, '$1') + .replace(/^(\:first\-child)?\+html/, '*$1+html'); + } + + if (reduced.indexOf('[') > -1) + reduced = reduced.replace(/\[([^\]]+)\]/g, removeWhitespace); + + if (repeated.indexOf(reduced) == -1) { + selector[0] = reduced; + repeated.push(reduced); + list.push(selector); + } + } + + return list.sort(selectorSorter); + }, + + selectorDuplicates: function (selectors) { + var list = []; + var repeated = []; + + for (var i = 0, l = selectors.length; i < l; i++) { + var selector = selectors[i]; + + if (repeated.indexOf(selector[0]) == -1) { + repeated.push(selector[0]); + list.push(selector); + } + } + + return list.sort(selectorSorter); + }, + + block: function (values, spaceAfterClosingBrace) { + values[0] = values[0] + .replace(/\s+/g, ' ') + .replace(/(,|:|\() /g, '$1') + .replace(/ \)/g, ')'); + + if (!spaceAfterClosingBrace) + values[0] = values[0].replace(/\) /g, ')'); + }, + + atRule: function (values) { + values[0] = values[0] + .replace(/\s+/g, ' ') + .trim(); + } +}; + +module.exports = CleanUp; + +},{}],31:[function(require,module,exports){ +// This extractor is used in advanced optimizations +// IMPORTANT: Mind Token class and this code is not related! +// Properties will be tokenized in one step, see #429 + +var stringifySelectors = require('../stringifier/one-time').selectors; +var stringifyValue = require('../stringifier/one-time').value; + +var AT_RULE = 'at-rule'; + +function extract(token) { + var properties = []; + + if (token[0] == 'selector') { + var inSpecificSelector = !/[\.\+>~]/.test(stringifySelectors(token[1])); + for (var i = 0, l = token[2].length; i < l; i++) { + var property = token[2][i]; + + if (property.indexOf('__ESCAPED') === 0) + continue; + + if (property[0] == AT_RULE) + continue; + + var name = token[2][i][0][0]; + if (name.length === 0) + continue; + + if (name.indexOf('--') === 0) + continue; + + var value = stringifyValue(token[2], i); + + properties.push([ + name, + value, + findNameRoot(name), + token[2][i], + name + ':' + value, + token[1], + inSpecificSelector + ]); + } + } else if (token[0] == 'block') { + for (var j = 0, k = token[2].length; j < k; j++) { + properties = properties.concat(extract(token[2][j])); + } + } + + return properties; +} + +function findNameRoot(name) { + if (name == 'list-style') + return name; + if (name.indexOf('-radius') > 0) + return 'border-radius'; + if (name == 'border-collapse' || name == 'border-spacing' || name == 'border-image') + return name; + if (name.indexOf('border-') === 0 && /^border\-\w+\-\w+$/.test(name)) + return name.match(/border\-\w+/)[0]; + if (name.indexOf('border-') === 0 && /^border\-\w+$/.test(name)) + return 'border'; + if (name.indexOf('text-') === 0) + return name; + + return name.replace(/^\-\w+\-/, '').match(/([a-zA-Z]+)/)[0].toLowerCase(); +} + +module.exports = extract; + +},{"../stringifier/one-time":45}],32:[function(require,module,exports){ +function isSpecial(options, selector) { + return options.compatibility.selectors.special.test(selector); +} + +module.exports = isSpecial; + +},{}],33:[function(require,module,exports){ +var optimizeProperties = require('../properties/optimizer'); + +var stringifyBody = require('../stringifier/one-time').body; +var stringifySelectors = require('../stringifier/one-time').selectors; +var cleanUpSelectors = require('./clean-up').selectors; +var isSpecial = require('./is-special'); + +function mergeAdjacent(tokens, options, validator) { + var lastToken = [null, [], []]; + var adjacentSpace = options.compatibility.selectors.adjacentSpace; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + if (token[0] != 'selector') { + lastToken = [null, [], []]; + continue; + } + + if (lastToken[0] == 'selector' && stringifySelectors(token[1]) == stringifySelectors(lastToken[1])) { + var joinAt = [lastToken[2].length]; + Array.prototype.push.apply(lastToken[2], token[2]); + optimizeProperties(token[1], lastToken[2], joinAt, true, options, validator); + token[2] = []; + } else if (lastToken[0] == 'selector' && stringifyBody(token[2]) == stringifyBody(lastToken[2]) && + !isSpecial(options, stringifySelectors(token[1])) && !isSpecial(options, stringifySelectors(lastToken[1]))) { + lastToken[1] = cleanUpSelectors(lastToken[1].concat(token[1]), false, adjacentSpace); + token[2] = []; + } else { + lastToken = token; + } + } +} + +module.exports = mergeAdjacent; + +},{"../properties/optimizer":19,"../stringifier/one-time":45,"./clean-up":30,"./is-special":32}],34:[function(require,module,exports){ +var canReorder = require('./reorderable').canReorder; +var extractProperties = require('./extractor'); + +function mergeMediaQueries(tokens) { + var candidates = {}; + var reduced = []; + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + if (token[0] != 'block') + continue; + + var candidate = candidates[token[1][0]]; + if (!candidate) { + candidate = []; + candidates[token[1][0]] = candidate; + } + + candidate.push(i); + } + + for (var name in candidates) { + var positions = candidates[name]; + + positionLoop: + for (var j = positions.length - 1; j > 0; j--) { + var positionOne = positions[j]; + var tokenOne = tokens[positionOne]; + var positionTwo = positions[j - 1]; + var tokenTwo = tokens[positionTwo]; + + directionLoop: + for (var direction = 1; direction >= -1; direction -= 2) { + var topToBottom = direction == 1; + var from = topToBottom ? positionOne + 1 : positionTwo - 1; + var to = topToBottom ? positionTwo : positionOne; + var delta = topToBottom ? 1 : -1; + var source = topToBottom ? tokenOne : tokenTwo; + var target = topToBottom ? tokenTwo : tokenOne; + var movedProperties = extractProperties(source); + + while (from != to) { + var traversedProperties = extractProperties(tokens[from]); + from += delta; + + if (!canReorder(movedProperties, traversedProperties)) + continue directionLoop; + } + + target[2] = topToBottom ? + source[2].concat(target[2]) : + target[2].concat(source[2]); + source[2] = []; + + reduced.push(target); + continue positionLoop; + } + } + } + + return reduced; +} + +module.exports = mergeMediaQueries; + +},{"./extractor":31,"./reorderable":40}],35:[function(require,module,exports){ +var stringifyBody = require('../stringifier/one-time').body; +var stringifySelectors = require('../stringifier/one-time').selectors; +var cleanUpSelectors = require('./clean-up').selectors; +var isSpecial = require('./is-special'); + +function unsafeSelector(value) { + return /\.|\*| :/.test(value); +} + +function isBemElement(token) { + var asString = stringifySelectors(token[1]); + return asString.indexOf('__') > -1 || asString.indexOf('--') > -1; +} + +function withoutModifier(selector) { + return selector.replace(/--[^ ,>\+~:]+/g, ''); +} + +function removeAnyUnsafeElements(left, candidates) { + var leftSelector = withoutModifier(stringifySelectors(left[1])); + + for (var body in candidates) { + var right = candidates[body]; + var rightSelector = withoutModifier(stringifySelectors(right[1])); + + if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1) + delete candidates[body]; + } +} + +function mergeNonAdjacentByBody(tokens, options) { + var candidates = {}; + var adjacentSpace = options.compatibility.selectors.adjacentSpace; + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + if (token[0] != 'selector') + continue; + + if (token[2].length > 0 && (!options.semanticMerging && unsafeSelector(stringifySelectors(token[1])))) + candidates = {}; + + if (token[2].length > 0 && options.semanticMerging && isBemElement(token)) + removeAnyUnsafeElements(token, candidates); + + var candidateBody = stringifyBody(token[2]); + var oldToken = candidates[candidateBody]; + if (oldToken && !isSpecial(options, stringifySelectors(token[1])) && !isSpecial(options, stringifySelectors(oldToken[1]))) { + token[1] = token[2].length > 0 ? + cleanUpSelectors(oldToken[1].concat(token[1]), false, adjacentSpace) : + oldToken[1].concat(token[1]); + + oldToken[2] = []; + candidates[candidateBody] = null; + } + + candidates[stringifyBody(token[2])] = token; + } +} + +module.exports = mergeNonAdjacentByBody; + +},{"../stringifier/one-time":45,"./clean-up":30,"./is-special":32}],36:[function(require,module,exports){ +var optimizeProperties = require('../properties/optimizer'); +var stringifySelectors = require('../stringifier/one-time').selectors; +var extractProperties = require('./extractor'); +var canReorder = require('./reorderable').canReorder; + +function mergeNonAdjacentBySelector(tokens, options, validator) { + var allSelectors = {}; + var repeatedSelectors = []; + var i; + + for (i = tokens.length - 1; i >= 0; i--) { + if (tokens[i][0] != 'selector') + continue; + if (tokens[i][2].length === 0) + continue; + + var selector = stringifySelectors(tokens[i][1]); + allSelectors[selector] = [i].concat(allSelectors[selector] || []); + + if (allSelectors[selector].length == 2) + repeatedSelectors.push(selector); + } + + for (i = repeatedSelectors.length - 1; i >= 0; i--) { + var positions = allSelectors[repeatedSelectors[i]]; + + selectorIterator: + for (var j = positions.length - 1; j > 0; j--) { + var positionOne = positions[j - 1]; + var tokenOne = tokens[positionOne]; + var positionTwo = positions[j]; + var tokenTwo = tokens[positionTwo]; + + directionIterator: + for (var direction = 1; direction >= -1; direction -= 2) { + var topToBottom = direction == 1; + var from = topToBottom ? positionOne + 1 : positionTwo - 1; + var to = topToBottom ? positionTwo : positionOne; + var delta = topToBottom ? 1 : -1; + var moved = topToBottom ? tokenOne : tokenTwo; + var target = topToBottom ? tokenTwo : tokenOne; + var movedProperties = extractProperties(moved); + var joinAt; + + while (from != to) { + var traversedProperties = extractProperties(tokens[from]); + from += delta; + + // traversed then moved as we move selectors towards the start + var reorderable = topToBottom ? + canReorder(movedProperties, traversedProperties) : + canReorder(traversedProperties, movedProperties); + + if (!reorderable && !topToBottom) + continue selectorIterator; + if (!reorderable && topToBottom) + continue directionIterator; + } + + if (topToBottom) { + joinAt = [moved[2].length]; + Array.prototype.push.apply(moved[2], target[2]); + target[2] = moved[2]; + } else { + joinAt = [target[2].length]; + Array.prototype.push.apply(target[2], moved[2]); + } + + optimizeProperties(target[1], target[2], joinAt, true, options, validator); + moved[2] = []; + } + } + } +} + +module.exports = mergeNonAdjacentBySelector; + +},{"../properties/optimizer":19,"../stringifier/one-time":45,"./extractor":31,"./reorderable":40}],37:[function(require,module,exports){ +var optimizeProperties = require('../properties/optimizer'); +var stringifyBody = require('../stringifier/one-time').body; +var stringifySelectors = require('../stringifier/one-time').selectors; +var isSpecial = require('./is-special'); +var cloneArray = require('../utils/clone-array'); + +function reduceNonAdjacent(tokens, options, validator) { + var candidates = {}; + var repeated = []; + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + + if (token[0] != 'selector') + continue; + if (token[2].length === 0) + continue; + + var selectorAsString = stringifySelectors(token[1]); + var isComplexAndNotSpecial = token[1].length > 1 && !isSpecial(options, selectorAsString); + var wrappedSelectors = options.sourceMap ? wrappedSelectorsFrom(token[1]) : token[1]; + var selectors = isComplexAndNotSpecial ? + [selectorAsString].concat(wrappedSelectors) : + [selectorAsString]; + + for (var j = 0, m = selectors.length; j < m; j++) { + var selector = selectors[j]; + + if (!candidates[selector]) + candidates[selector] = []; + else + repeated.push(selector); + + candidates[selector].push({ + where: i, + list: wrappedSelectors, + isPartial: isComplexAndNotSpecial && j > 0, + isComplex: isComplexAndNotSpecial && j === 0 + }); + } + } + + reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, validator); + reduceComplexNonAdjacentCases(tokens, candidates, options, validator); +} + +function wrappedSelectorsFrom(list) { + var wrapped = []; + + for (var i = 0; i < list.length; i++) { + wrapped.push([list[i][0]]); + } + + return wrapped; +} + +function reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, validator) { + function filterOut(idx, bodies) { + return data[idx].isPartial && bodies.length === 0; + } + + function reduceBody(token, newBody, processedCount, tokenIdx) { + if (!data[processedCount - tokenIdx - 1].isPartial) + token[2] = newBody; + } + + for (var i = 0, l = repeated.length; i < l; i++) { + var selector = repeated[i]; + var data = candidates[selector]; + + reduceSelector(tokens, selector, data, { + filterOut: filterOut, + callback: reduceBody + }, options, validator); + } +} + +function reduceComplexNonAdjacentCases(tokens, candidates, options, validator) { + var localContext = {}; + + function filterOut(idx) { + return localContext.data[idx].where < localContext.intoPosition; + } + + function collectReducedBodies(token, newBody, processedCount, tokenIdx) { + if (tokenIdx === 0) + localContext.reducedBodies.push(newBody); + } + + allSelectors: + for (var complexSelector in candidates) { + var into = candidates[complexSelector]; + if (!into[0].isComplex) + continue; + + var intoPosition = into[into.length - 1].where; + var intoToken = tokens[intoPosition]; + var reducedBodies = []; + + var selectors = isSpecial(options, complexSelector) ? + [complexSelector] : + into[0].list; + + localContext.intoPosition = intoPosition; + localContext.reducedBodies = reducedBodies; + + for (var j = 0, m = selectors.length; j < m; j++) { + var selector = selectors[j]; + var data = candidates[selector]; + + if (data.length < 2) + continue allSelectors; + + localContext.data = data; + + reduceSelector(tokens, selector, data, { + filterOut: filterOut, + callback: collectReducedBodies + }, options, validator); + + if (stringifyBody(reducedBodies[reducedBodies.length - 1]) != stringifyBody(reducedBodies[0])) + continue allSelectors; + } + + intoToken[2] = reducedBodies[0]; + } +} + +function reduceSelector(tokens, selector, data, context, options, validator) { + var bodies = []; + var bodiesAsList = []; + var joinsAt = []; + var processedTokens = []; + + for (var j = data.length - 1, m = 0; j >= 0; j--) { + if (context.filterOut(j, bodies)) + continue; + + var where = data[j].where; + var token = tokens[where]; + var clonedBody = cloneArray(token[2]); + + bodies = bodies.concat(clonedBody); + bodiesAsList.push(clonedBody); + processedTokens.push(where); + } + + for (j = 0, m = bodiesAsList.length; j < m; j++) { + if (bodiesAsList[j].length > 0) + joinsAt.push((joinsAt[j - 1] || 0) + bodiesAsList[j].length); + } + + optimizeProperties(selector, bodies, joinsAt, false, options, validator); + + var processedCount = processedTokens.length; + var propertyIdx = bodies.length - 1; + var tokenIdx = processedCount - 1; + + while (tokenIdx >= 0) { + if ((tokenIdx === 0 || (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) { + propertyIdx--; + continue; + } + + var newBody = bodies.splice(propertyIdx + 1); + context.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx); + + tokenIdx--; + } +} + +module.exports = reduceNonAdjacent; + +},{"../properties/optimizer":19,"../stringifier/one-time":45,"../utils/clone-array":59,"./is-special":32}],38:[function(require,module,exports){ +var stringifyAll = require('../stringifier/one-time').all; + +function removeDuplicateMediaQueries(tokens) { + var candidates = {}; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + if (token[0] != 'block') + continue; + + var key = token[1][0] + '%' + stringifyAll(token[2]); + var candidate = candidates[key]; + + if (candidate) + candidate[2] = []; + + candidates[key] = token; + } +} + +module.exports = removeDuplicateMediaQueries; + +},{"../stringifier/one-time":45}],39:[function(require,module,exports){ +var stringifyBody = require('../stringifier/one-time').body; +var stringifySelectors = require('../stringifier/one-time').selectors; + +function removeDuplicates(tokens) { + var matched = {}; + var moreThanOnce = []; + var id, token; + var body, bodies; + + for (var i = 0, l = tokens.length; i < l; i++) { + token = tokens[i]; + if (token[0] != 'selector') + continue; + + id = stringifySelectors(token[1]); + + if (matched[id] && matched[id].length == 1) + moreThanOnce.push(id); + else + matched[id] = matched[id] || []; + + matched[id].push(i); + } + + for (i = 0, l = moreThanOnce.length; i < l; i++) { + id = moreThanOnce[i]; + bodies = []; + + for (var j = matched[id].length - 1; j >= 0; j--) { + token = tokens[matched[id][j]]; + body = stringifyBody(token[2]); + + if (bodies.indexOf(body) > -1) + token[2] = []; + else + bodies.push(body); + } + } +} + +module.exports = removeDuplicates; + +},{"../stringifier/one-time":45}],40:[function(require,module,exports){ +// TODO: it'd be great to merge it with the other canReorder functionality + +var FLEX_PROPERTIES = /align\-items|box\-align|box\-pack|flex|justify/; +var BORDER_PROPERTIES = /^border\-(top|right|bottom|left|color|style|width|radius)/; + +function canReorder(left, right) { + for (var i = right.length - 1; i >= 0; i--) { + for (var j = left.length - 1; j >= 0; j--) { + if (!canReorderSingle(left[j], right[i])) + return false; + } + } + + return true; +} + +function canReorderSingle(left, right) { + var leftName = left[0]; + var leftValue = left[1]; + var leftNameRoot = left[2]; + var leftSelector = left[5]; + var leftInSpecificSelector = left[6]; + var rightName = right[0]; + var rightValue = right[1]; + var rightNameRoot = right[2]; + var rightSelector = right[5]; + var rightInSpecificSelector = right[6]; + + if (leftName == 'font' && rightName == 'line-height' || rightName == 'font' && leftName == 'line-height') + return false; + if (FLEX_PROPERTIES.test(leftName) && FLEX_PROPERTIES.test(rightName)) + return false; + if (leftNameRoot == rightNameRoot && unprefixed(leftName) == unprefixed(rightName) && (vendorPrefixed(leftName) ^ vendorPrefixed(rightName))) + return false; + if (leftNameRoot == 'border' && BORDER_PROPERTIES.test(rightNameRoot) && (leftName == 'border' || leftName == rightNameRoot)) + return false; + if (rightNameRoot == 'border' && BORDER_PROPERTIES.test(leftNameRoot) && (rightName == 'border' || rightName == leftNameRoot)) + return false; + if (leftNameRoot == 'border' && rightNameRoot == 'border' && leftName != rightName && (isSideBorder(leftName) && isStyleBorder(rightName) || isStyleBorder(leftName) && isSideBorder(rightName))) + return false; + if (leftNameRoot != rightNameRoot) + return true; + if (leftName == rightName && leftNameRoot == rightNameRoot && (leftValue == rightValue || withDifferentVendorPrefix(leftValue, rightValue))) + return true; + if (leftName != rightName && leftNameRoot == rightNameRoot && leftName != leftNameRoot && rightName != rightNameRoot) + return true; + if (leftName != rightName && leftNameRoot == rightNameRoot && leftValue == rightValue) + return true; + if (rightInSpecificSelector && leftInSpecificSelector && !inheritable(leftNameRoot) && !inheritable(rightNameRoot) && selectorsDoNotOverlap(rightSelector, leftSelector)) + return true; + + return false; +} + +function vendorPrefixed(name) { + return /^\-(?:moz|webkit|ms|o)\-/.test(name); +} + +function unprefixed(name) { + return name.replace(/^\-(?:moz|webkit|ms|o)\-/, ''); +} + +function isSideBorder(name) { + return name == 'border-top' || name == 'border-right' || name == 'border-bottom' || name == 'border-left'; +} + +function isStyleBorder(name) { + return name == 'border-color' || name == 'border-style' || name == 'border-width'; +} + +function withDifferentVendorPrefix(value1, value2) { + return vendorPrefixed(value1) && vendorPrefixed(value2) && value1.split('-')[1] != value2.split('-')[2]; +} + +function selectorsDoNotOverlap(s1, s2) { + for (var i = 0, l = s1.length; i < l; i++) { + for (var j = 0, m = s2.length; j < m; j++) { + if (s1[i][0] == s2[j][0]) + return false; + } + } + + return true; +} + +function inheritable(name) { + // According to http://www.w3.org/TR/CSS21/propidx.html + // Others will be catched by other, preceeding rules + return name == 'font' || name == 'line-height' || name == 'list-style'; +} + +module.exports = { + canReorder: canReorder, + canReorderSingle: canReorderSingle +}; + +},{}],41:[function(require,module,exports){ +var extractProperties = require('./extractor'); +var canReorderSingle = require('./reorderable').canReorderSingle; +var stringifyBody = require('../stringifier/one-time').body; +var stringifySelectors = require('../stringifier/one-time').selectors; +var cleanUpSelectorDuplicates = require('./clean-up').selectorDuplicates; +var isSpecial = require('./is-special'); +var cloneArray = require('../utils/clone-array'); + +function naturalSorter(a, b) { + return a > b; +} + +function cloneAndMergeSelectors(propertyA, propertyB) { + var cloned = cloneArray(propertyA); + cloned[5] = cloned[5].concat(propertyB[5]); + + return cloned; +} + +function restructure(tokens, options) { + var movableTokens = {}; + var movedProperties = []; + var multiPropertyMoveCache = {}; + var movedToBeDropped = []; + var maxCombinationsLevel = 2; + var ID_JOIN_CHARACTER = '%'; + + function sendToMultiPropertyMoveCache(position, movedProperty, allFits) { + for (var i = allFits.length - 1; i >= 0; i--) { + var fit = allFits[i][0]; + var id = addToCache(movedProperty, fit); + + if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) { + removeAllMatchingFromCache(id); + break; + } + } + } + + function addToCache(movedProperty, fit) { + var id = cacheId(fit); + multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || []; + multiPropertyMoveCache[id].push([movedProperty, fit]); + return id; + } + + function removeAllMatchingFromCache(matchId) { + var matchSelectors = matchId.split(ID_JOIN_CHARACTER); + var forRemoval = []; + var i; + + for (var id in multiPropertyMoveCache) { + var selectors = id.split(ID_JOIN_CHARACTER); + for (i = selectors.length - 1; i >= 0; i--) { + if (matchSelectors.indexOf(selectors[i]) > -1) { + forRemoval.push(id); + break; + } + } + } + + for (i = forRemoval.length - 1; i >= 0; i--) { + delete multiPropertyMoveCache[forRemoval[i]]; + } + } + + function cacheId(cachedTokens) { + var id = []; + for (var i = 0, l = cachedTokens.length; i < l; i++) { + id.push(stringifySelectors(cachedTokens[i][1])); + } + return id.join(ID_JOIN_CHARACTER); + } + + function tokensToMerge(sourceTokens) { + var uniqueTokensWithBody = []; + var mergeableTokens = []; + + for (var i = sourceTokens.length - 1; i >= 0; i--) { + if (isSpecial(options, stringifySelectors(sourceTokens[i][1]))) + continue; + + mergeableTokens.unshift(sourceTokens[i]); + if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1) + uniqueTokensWithBody.push(sourceTokens[i]); + } + + return uniqueTokensWithBody.length > 1 ? + mergeableTokens : + []; + } + + function shortenIfPossible(position, movedProperty) { + var name = movedProperty[0]; + var value = movedProperty[1]; + var key = movedProperty[4]; + var valueSize = name.length + value.length + 1; + var allSelectors = []; + var qualifiedTokens = []; + + var mergeableTokens = tokensToMerge(movableTokens[key]); + if (mergeableTokens.length < 2) + return; + + var allFits = findAllFits(mergeableTokens, valueSize, 1); + var bestFit = allFits[0]; + if (bestFit[1] > 0) + return sendToMultiPropertyMoveCache(position, movedProperty, allFits); + + for (var i = bestFit[0].length - 1; i >=0; i--) { + allSelectors = bestFit[0][i][1].concat(allSelectors); + qualifiedTokens.unshift(bestFit[0][i]); + } + + allSelectors = cleanUpSelectorDuplicates(allSelectors); + dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens); + } + + function fitSorter(fit1, fit2) { + return fit1[1] > fit2[1]; + } + + function findAllFits(mergeableTokens, propertySize, propertiesCount) { + var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1); + return combinations.sort(fitSorter); + } + + function allCombinations(tokensVariant, propertySize, propertiesCount, level) { + var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]]; + if (tokensVariant.length > 2 && level > 0) { + for (var i = tokensVariant.length - 1; i >= 0; i--) { + var subVariant = Array.prototype.slice.call(tokensVariant, 0); + subVariant.splice(i, 1); + differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1)); + } + } + + return differenceVariants; + } + + function sizeDifference(tokensVariant, propertySize, propertiesCount) { + var allSelectorsSize = 0; + for (var i = tokensVariant.length - 1; i >= 0; i--) { + allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? stringifySelectors(tokensVariant[i][1]).length : -1; + } + return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1; + } + + function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) { + var i, j, k, m; + var allProperties = []; + + for (i = mergeableTokens.length - 1; i >= 0; i--) { + var mergeableToken = mergeableTokens[i]; + + for (j = mergeableToken[2].length - 1; j >= 0; j--) { + var mergeableProperty = mergeableToken[2][j]; + + for (k = 0, m = properties.length; k < m; k++) { + var property = properties[k]; + + var mergeablePropertyName = mergeableProperty[0][0]; + var propertyName = property[0]; + var propertyBody = property[4]; + if (mergeablePropertyName == propertyName && stringifyBody([mergeableProperty]) == propertyBody) { + mergeableToken[2].splice(j, 1); + break; + } + } + } + } + + for (i = properties.length - 1; i >= 0; i--) { + allProperties.unshift(properties[i][3]); + } + + var newToken = ['selector', allSelectors, allProperties]; + tokens.splice(position, 0, newToken); + } + + function dropPropertiesAt(position, movedProperty) { + var key = movedProperty[4]; + var toMove = movableTokens[key]; + + if (toMove && toMove.length > 1) { + if (!shortenMultiMovesIfPossible(position, movedProperty)) + shortenIfPossible(position, movedProperty); + } + } + + function shortenMultiMovesIfPossible(position, movedProperty) { + var candidates = []; + var propertiesAndMergableTokens = []; + var key = movedProperty[4]; + var j, k; + + var mergeableTokens = tokensToMerge(movableTokens[key]); + if (mergeableTokens.length < 2) + return; + + movableLoop: + for (var value in movableTokens) { + var tokensList = movableTokens[value]; + + for (j = mergeableTokens.length - 1; j >= 0; j--) { + if (tokensList.indexOf(mergeableTokens[j]) == -1) + continue movableLoop; + } + + candidates.push(value); + } + + if (candidates.length < 2) + return false; + + for (j = candidates.length - 1; j >= 0; j--) { + for (k = movedProperties.length - 1; k >= 0; k--) { + if (movedProperties[k][4] == candidates[j]) { + propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]); + break; + } + } + } + + return processMultiPropertyMove(position, propertiesAndMergableTokens); + } + + function processMultiPropertyMove(position, propertiesAndMergableTokens) { + var valueSize = 0; + var properties = []; + var property; + + for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) { + property = propertiesAndMergableTokens[i][0]; + var fullValue = property[4]; + valueSize += fullValue.length + (i > 0 ? 1 : 0); + + properties.push(property); + } + + var mergeableTokens = propertiesAndMergableTokens[0][1]; + var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0]; + if (bestFit[1] > 0) + return false; + + var allSelectors = []; + var qualifiedTokens = []; + for (i = bestFit[0].length - 1; i >= 0; i--) { + allSelectors = bestFit[0][i][1].concat(allSelectors); + qualifiedTokens.unshift(bestFit[0][i]); + } + + allSelectors = cleanUpSelectorDuplicates(allSelectors); + dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens); + + for (i = properties.length - 1; i >= 0; i--) { + property = properties[i]; + var index = movedProperties.indexOf(property); + + delete movableTokens[property[4]]; + + if (index > -1 && movedToBeDropped.indexOf(index) == -1) + movedToBeDropped.push(index); + } + + return true; + } + + function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) { + var propertyName = property[0]; + var movedPropertyName = movedProperty[0]; + if (propertyName != movedPropertyName) + return false; + + var key = movedProperty[4]; + var toMove = movableTokens[key]; + return toMove && toMove.indexOf(token) > -1; + } + + for (var i = tokens.length - 1; i >= 0; i--) { + var token = tokens[i]; + var isSelector; + var j, k, m; + var samePropertyAt; + + if (token[0] == 'selector') { + isSelector = true; + } else if (token[0] == 'block') { + isSelector = false; + } else { + continue; + } + + // We cache movedProperties.length as it may change in the loop + var movedCount = movedProperties.length; + + var properties = extractProperties(token); + movedToBeDropped = []; + + var unmovableInCurrentToken = []; + for (j = properties.length - 1; j >= 0; j--) { + for (k = j - 1; k >= 0; k--) { + if (!canReorderSingle(properties[j], properties[k])) { + unmovableInCurrentToken.push(j); + break; + } + } + } + + for (j = properties.length - 1; j >= 0; j--) { + var property = properties[j]; + var movedSameProperty = false; + + for (k = 0; k < movedCount; k++) { + var movedProperty = movedProperties[k]; + + if (movedToBeDropped.indexOf(k) == -1 && !canReorderSingle(property, movedProperty) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token)) { + dropPropertiesAt(i + 1, movedProperty, token); + + if (movedToBeDropped.indexOf(k) == -1) { + movedToBeDropped.push(k); + delete movableTokens[movedProperty[4]]; + } + } + + if (!movedSameProperty) { + movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1]; + + if (movedSameProperty) { + samePropertyAt = k; + } + } + } + + if (!isSelector || unmovableInCurrentToken.indexOf(j) > -1) + continue; + + var key = property[4]; + movableTokens[key] = movableTokens[key] || []; + movableTokens[key].push(token); + + if (movedSameProperty) { + movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property); + } else { + movedProperties.push(property); + } + } + + movedToBeDropped = movedToBeDropped.sort(naturalSorter); + for (j = 0, m = movedToBeDropped.length; j < m; j++) { + var dropAt = movedToBeDropped[j] - j; + movedProperties.splice(dropAt, 1); + } + } + + var position = tokens[0] && tokens[0][0] == 'at-rule' && tokens[0][1][0].indexOf('@charset') === 0 ? 1 : 0; + for (; position < tokens.length - 1; position++) { + var isImportRule = tokens[position][0] === 'at-rule' && tokens[position][1][0].indexOf('@import') === 0; + var isEscapedCommentSpecial = tokens[position][0] === 'text' && tokens[position][1][0].indexOf('__ESCAPED_COMMENT_SPECIAL') === 0; + if (!(isImportRule || isEscapedCommentSpecial)) + break; + } + + for (i = 0; i < movedProperties.length; i++) { + dropPropertiesAt(position, movedProperties[i]); + } +} + +module.exports = restructure; + +},{"../stringifier/one-time":45,"../utils/clone-array":59,"./clean-up":30,"./extractor":31,"./is-special":32,"./reorderable":40}],42:[function(require,module,exports){ +var cleanUpSelectors = require('./clean-up').selectors; +var cleanUpBlock = require('./clean-up').block; +var cleanUpAtRule = require('./clean-up').atRule; +var split = require('../utils/split'); + +var RGB = require('../colors/rgb'); +var HSL = require('../colors/hsl'); +var HexNameShortener = require('../colors/hex-name-shortener'); + +var wrapForOptimizing = require('../properties/wrap-for-optimizing').all; +var restoreFromOptimizing = require('../properties/restore-from-optimizing'); +var removeUnused = require('../properties/remove-unused'); + +var DEFAULT_ROUNDING_PRECISION = 2; +var CHARSET_TOKEN = '@charset'; +var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i'); + +var FONT_NUMERAL_WEIGHTS = ['100', '200', '300', '400', '500', '600', '700', '800', '900']; +var FONT_NAME_WEIGHTS = ['normal', 'bold', 'bolder', 'lighter']; +var FONT_NAME_WEIGHTS_WITHOUT_NORMAL = ['bold', 'bolder', 'lighter']; + +var WHOLE_PIXEL_VALUE = /(?:^|\s|\()(-?\d+)px/; +var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/; + +var valueMinifiers = { + 'background': function (value, index, total) { + return index === 0 && total == 1 && (value == 'none' || value == 'transparent') ? '0 0' : value; + }, + 'font-weight': function (value) { + if (value == 'normal') + return '400'; + else if (value == 'bold') + return '700'; + else + return value; + }, + 'outline': function (value, index, total) { + return index === 0 && total == 1 && value == 'none' ? '0' : value; + } +}; + +function isNegative(property, idx) { + return property.value[idx] && property.value[idx][0][0] == '-' && parseFloat(property.value[idx][0]) < 0; +} + +function zeroMinifier(name, value) { + if (value.indexOf('0') == -1) + return value; + + if (value.indexOf('-') > -1) { + value = value + .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2') + .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2'); + } + + return value + .replace(/(^|\s)0+([1-9])/g, '$1$2') + .replace(/(^|\D)\.0+(\D|$)/g, '$10$2') + .replace(/(^|\D)\.0+(\D|$)/g, '$10$2') + .replace(/\.([1-9]*)0+(\D|$)/g, function (match, nonZeroPart, suffix) { + return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix; + }) + .replace(/(^|\D)0\.(\d)/g, '$1.$2'); +} + +function zeroDegMinifier(_, value) { + if (value.indexOf('0deg') == -1) + return value; + + return value.replace(/\(0deg\)/g, '(0)'); +} + +function whitespaceMinifier(name, value) { + if (name.indexOf('filter') > -1 || value.indexOf(' ') == -1) + return value; + + value = value.replace(/\s+/g, ' '); + + if (value.indexOf('calc') > -1) + value = value.replace(/\) ?\/ ?/g, ')/ '); + + return value + .replace(/\( /g, '(') + .replace(/ \)/g, ')') + .replace(/, /g, ','); +} + +function precisionMinifier(_, value, precisionOptions) { + if (precisionOptions.value === -1 || value.indexOf('.') === -1) + return value; + + return value + .replace(precisionOptions.regexp, function (match, number) { + return Math.round(parseFloat(number) * precisionOptions.multiplier) / precisionOptions.multiplier + 'px'; + }) + .replace(/(\d)\.($|\D)/g, '$1$2'); +} + +function unitMinifier(name, value, unitsRegexp) { + if (/^(?:\-moz\-calc|\-webkit\-calc|calc)\(/.test(value)) + return value; + + if (name == 'flex' || name == '-ms-flex' || name == '-webkit-flex' || name == 'flex-basis' || name == '-webkit-flex-basis') + return value; + + if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height')) + return value; + + return value + .replace(unitsRegexp, '$1' + '0' + '$2') + .replace(unitsRegexp, '$1' + '0' + '$2'); +} + +function multipleZerosMinifier(property) { + var values = property.value; + var spliceAt; + + if (values.length == 4 && values[0][0] === '0' && values[1][0] === '0' && values[2][0] === '0' && values[3][0] === '0') { + if (property.name.indexOf('box-shadow') > -1) + spliceAt = 2; + else + spliceAt = 1; + } + + if (spliceAt) { + property.value.splice(spliceAt); + property.dirty = true; + } +} + +function colorMininifier(name, value, compatibility) { + if (value.indexOf('#') === -1 && value.indexOf('rgb') == -1 && value.indexOf('hsl') == -1) + return HexNameShortener.shorten(value); + + value = value + .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/g, function (match, red, green, blue) { + return new RGB(red, green, blue).toHex(); + }) + .replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/g, function (match, hue, saturation, lightness) { + return new HSL(hue, saturation, lightness).toHex(); + }) + .replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color) { + if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) + return prefix + '#' + color[0] + color[2] + color[4]; + else + return prefix + '#' + color; + }) + .replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/g, function (match, colorFunction, colorDef) { + var tokens = colorDef.split(','); + var applies = (colorFunction == 'hsl' && tokens.length == 3) || + (colorFunction == 'hsla' && tokens.length == 4) || + (colorFunction == 'rgb' && tokens.length == 3 && colorDef.indexOf('%') > 0) || + (colorFunction == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0); + if (!applies) + return match; + + if (tokens[1].indexOf('%') == -1) + tokens[1] += '%'; + if (tokens[2].indexOf('%') == -1) + tokens[2] += '%'; + return colorFunction + '(' + tokens.join(',') + ')'; + }); + + if (compatibility.colors.opacity && name.indexOf('background') == -1) { + value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) { + if (split(value, ',').pop().indexOf('gradient(') > -1) + return match; + + return 'transparent'; + }); + } + + return HexNameShortener.shorten(value); +} + +function pixelLengthMinifier(_, value, compatibility) { + if (!WHOLE_PIXEL_VALUE.test(value)) + return value; + + return value.replace(WHOLE_PIXEL_VALUE, function (match, val) { + var newValue; + var intVal = parseInt(val); + + if (intVal === 0) + return match; + + if (compatibility.properties.shorterLengthUnits && compatibility.units.pt && intVal * 3 % 4 === 0) + newValue = intVal * 3 / 4 + 'pt'; + + if (compatibility.properties.shorterLengthUnits && compatibility.units.pc && intVal % 16 === 0) + newValue = intVal / 16 + 'pc'; + + if (compatibility.properties.shorterLengthUnits && compatibility.units.in && intVal % 96 === 0) + newValue = intVal / 96 + 'in'; + + if (newValue) + newValue = match.substring(0, match.indexOf(val)) + newValue; + + return newValue && newValue.length < match.length ? newValue : match; + }); +} + +function timeUnitMinifier(_, value) { + if (!TIME_VALUE.test(value)) + return value; + + return value.replace(TIME_VALUE, function (match, val, unit) { + var newValue; + + if (unit == 'ms') { + newValue = parseInt(val) / 1000 + 's'; + } else if (unit == 's') { + newValue = parseFloat(val) * 1000 + 'ms'; + } + + return newValue.length < match.length ? newValue : match; + }); +} + +function minifyBorderRadius(property) { + var values = property.value; + var spliceAt; + + if (values.length == 3 && values[1][0] == '/' && values[0][0] == values[2][0]) + spliceAt = 1; + else if (values.length == 5 && values[2][0] == '/' && values[0][0] == values[3][0] && values[1][0] == values[4][0]) + spliceAt = 2; + else if (values.length == 7 && values[3][0] == '/' && values[0][0] == values[4][0] && values[1][0] == values[5][0] && values[2][0] == values[6][0]) + spliceAt = 3; + else if (values.length == 9 && values[4][0] == '/' && values[0][0] == values[5][0] && values[1][0] == values[6][0] && values[2][0] == values[7][0] && values[3][0] == values[8][0]) + spliceAt = 4; + + if (spliceAt) { + property.value.splice(spliceAt); + property.dirty = true; + } +} + +function minifyFilter(property) { + if (property.value.length == 1) { + property.value[0][0] = property.value[0][0].replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/, function (match, filter, suffix) { + return filter.toLowerCase() + suffix; + }); + } + + property.value[0][0] = property.value[0][0] + .replace(/,(\S)/g, ', $1') + .replace(/ ?= ?/g, '='); +} + +function minifyFont(property) { + var values = property.value; + var hasNumeral = FONT_NUMERAL_WEIGHTS.indexOf(values[0][0]) > -1 || + values[1] && FONT_NUMERAL_WEIGHTS.indexOf(values[1][0]) > -1 || + values[2] && FONT_NUMERAL_WEIGHTS.indexOf(values[2][0]) > -1; + + if (hasNumeral) + return; + + if (values[1] == '/') + return; + + var normalCount = 0; + if (values[0][0] == 'normal') + normalCount++; + if (values[1] && values[1][0] == 'normal') + normalCount++; + if (values[2] && values[2][0] == 'normal') + normalCount++; + + if (normalCount > 1) + return; + + var toOptimize; + if (FONT_NAME_WEIGHTS_WITHOUT_NORMAL.indexOf(values[0][0]) > -1) + toOptimize = 0; + else if (values[1] && FONT_NAME_WEIGHTS_WITHOUT_NORMAL.indexOf(values[1][0]) > -1) + toOptimize = 1; + else if (values[2] && FONT_NAME_WEIGHTS_WITHOUT_NORMAL.indexOf(values[2][0]) > -1) + toOptimize = 2; + else if (FONT_NAME_WEIGHTS.indexOf(values[0][0]) > -1) + toOptimize = 0; + else if (values[1] && FONT_NAME_WEIGHTS.indexOf(values[1][0]) > -1) + toOptimize = 1; + else if (values[2] && FONT_NAME_WEIGHTS.indexOf(values[2][0]) > -1) + toOptimize = 2; + + if (toOptimize !== undefined) { + property.value[toOptimize][0] = valueMinifiers['font-weight'](values[toOptimize][0]); + property.dirty = true; + } +} + +function optimizeBody(properties, options) { + var property, name, value; + var _properties = wrapForOptimizing(properties); + + for (var i = 0, l = _properties.length; i < l; i++) { + property = _properties[i]; + name = property.name; + + if (property.hack && ( + (property.hack == 'star' || property.hack == 'underscore') && !options.compatibility.properties.iePrefixHack || + property.hack == 'backslash' && !options.compatibility.properties.ieSuffixHack || + property.hack == 'bang' && !options.compatibility.properties.ieBangHack)) + property.unused = true; + + if (name.indexOf('padding') === 0 && (isNegative(property, 0) || isNegative(property, 1) || isNegative(property, 2) || isNegative(property, 3))) + property.unused = true; + + if (property.unused) + continue; + + if (property.variable) { + if (property.block) + optimizeBody(property.value[0], options); + continue; + } + + for (var j = 0, m = property.value.length; j < m; j++) { + value = property.value[j][0]; + + if (valueMinifiers[name]) + value = valueMinifiers[name](value, j, m); + + value = whitespaceMinifier(name, value); + value = precisionMinifier(name, value, options.precision); + value = pixelLengthMinifier(name, value, options.compatibility); + value = timeUnitMinifier(name, value); + value = zeroMinifier(name, value); + if (options.compatibility.properties.zeroUnits) { + value = zeroDegMinifier(name, value); + value = unitMinifier(name, value, options.unitsRegexp); + } + if (options.compatibility.properties.colors) + value = colorMininifier(name, value, options.compatibility); + + property.value[j][0] = value; + } + + multipleZerosMinifier(property); + + if (name.indexOf('border') === 0 && name.indexOf('radius') > 0) + minifyBorderRadius(property); + else if (name == 'filter') + minifyFilter(property); + else if (name == 'font') + minifyFont(property); + } + + restoreFromOptimizing(_properties, true); + removeUnused(_properties); +} + +function cleanupCharsets(tokens) { + var hasCharset = false; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + if (token[0] != 'at-rule') + continue; + + if (!CHARSET_REGEXP.test(token[1][0])) + continue; + + if (hasCharset || token[1][0].indexOf(CHARSET_TOKEN) == -1) { + tokens.splice(i, 1); + i--; + l--; + } else { + hasCharset = true; + tokens.splice(i, 1); + tokens.unshift(['at-rule', [token[1][0].replace(CHARSET_REGEXP, CHARSET_TOKEN)]]); + } + } +} + +function buildUnitRegexp(options) { + var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%']; + var otherUnits = ['ch', 'rem', 'vh', 'vm', 'vmax', 'vmin', 'vw']; + + otherUnits.forEach(function (unit) { + if (options.compatibility.units[unit]) + units.push(unit); + }); + + return new RegExp('(^|\\s|\\(|,)0(?:' + units.join('|') + ')(\\W|$)', 'g'); +} + +function buildPrecision(options) { + var precision = {}; + + precision.value = options.roundingPrecision === undefined ? + DEFAULT_ROUNDING_PRECISION : + options.roundingPrecision; + precision.multiplier = Math.pow(10, precision.value); + precision.regexp = new RegExp('(\\d*\\.\\d{' + (precision.value + 1) + ',})px', 'g'); + + return precision; +} + +function optimize(tokens, options) { + var ie7Hack = options.compatibility.selectors.ie7Hack; + var adjacentSpace = options.compatibility.selectors.adjacentSpace; + var spaceAfterClosingBrace = options.compatibility.properties.spaceAfterClosingBrace; + var mayHaveCharset = false; + + options.unitsRegexp = buildUnitRegexp(options); + options.precision = buildPrecision(options); + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + switch (token[0]) { + case 'selector': + token[1] = cleanUpSelectors(token[1], !ie7Hack, adjacentSpace); + optimizeBody(token[2], options); + break; + case 'block': + cleanUpBlock(token[1], spaceAfterClosingBrace); + optimize(token[2], options); + break; + case 'flat-block': + cleanUpBlock(token[1], spaceAfterClosingBrace); + optimizeBody(token[2], options); + break; + case 'at-rule': + cleanUpAtRule(token[1]); + mayHaveCharset = true; + } + + if (token[1].length === 0 || (token[2] && token[2].length === 0)) { + tokens.splice(i, 1); + i--; + l--; + } + } + + if (mayHaveCharset) + cleanupCharsets(tokens); +} + +module.exports = optimize; + +},{"../colors/hex-name-shortener":9,"../colors/hsl":10,"../colors/rgb":11,"../properties/remove-unused":22,"../properties/restore-from-optimizing":23,"../properties/wrap-for-optimizing":28,"../utils/split":66,"./clean-up":30}],43:[function(require,module,exports){ +var escapePrefix = '__ESCAPED_'; + +function trackPrefix(value, context, interestingContent) { + if (!interestingContent && value.indexOf('\n') == -1) { + if (value.indexOf(escapePrefix) === 0) { + return value; + } else { + context.column += value.length; + return; + } + } + + var withoutContent = 0; + var split = value.split('\n'); + var total = split.length; + var shift = 0; + + while (true) { + if (withoutContent == total - 1) + break; + + var part = split[withoutContent]; + if (/\S/.test(part)) + break; + + shift += part.length + 1; + withoutContent++; + } + + context.line += withoutContent; + context.column = withoutContent > 0 ? 0 : context.column; + context.column += /^(\s)*/.exec(split[withoutContent])[0].length; + + return value.substring(shift).trimLeft(); +} + +function sourceFor(originalMetadata, contextMetadata, context) { + var source = originalMetadata.source || contextMetadata.source; + + if (source && context.resolvePath) + return context.resolvePath(contextMetadata.source, source); + + return source; +} + +function snapshot(data, context, fallbacks) { + var metadata = { + line: context.line, + column: context.column, + source: context.source + }; + var sourceContent = null; + var sourceMetadata = context.sourceMapTracker.isTracking(metadata.source) ? + context.sourceMapTracker.originalPositionFor(metadata, data, fallbacks || 0) : + {}; + + metadata.line = sourceMetadata.line || metadata.line; + metadata.column = sourceMetadata.column || metadata.column; + metadata.source = sourceMetadata.sourceResolved ? + sourceMetadata.source : + sourceFor(sourceMetadata, metadata, context); + + if (context.sourceMapInlineSources) { + var sourceMapSourcesContent = context.sourceMapTracker.sourcesContentFor(context.source); + sourceContent = sourceMapSourcesContent && sourceMapSourcesContent[metadata.source] ? + sourceMapSourcesContent : + context.sourceReader.sourceAt(context.source); + } + + return sourceContent ? + [metadata.line, metadata.column, metadata.source, sourceContent] : + [metadata.line, metadata.column, metadata.source]; +} + +function trackSuffix(data, context) { + var parts = data.split('\n'); + + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i]; + var cursor = 0; + + if (i > 0) { + context.line++; + context.column = 0; + } + + while (true) { + var next = part.indexOf(escapePrefix, cursor); + + if (next == -1) { + context.column += part.substring(cursor).length; + break; + } + + context.column += next - cursor; + cursor += next - cursor; + + var escaped = part.substring(next, part.indexOf('__', next + 1) + 2); + var encodedValues = escaped.substring(escaped.indexOf('(') + 1, escaped.indexOf(')')).split(','); + context.line += ~~encodedValues[0]; + context.column = (~~encodedValues[0] === 0 ? context.column : 0) + ~~encodedValues[1]; + cursor += escaped.length; + } + } +} + +function track(data, context, snapshotMetadata, fallbacks) { + var untracked = trackPrefix(data, context, snapshotMetadata); + var metadata = snapshotMetadata ? + snapshot(untracked, context, fallbacks) : + []; + + if (untracked) + trackSuffix(untracked, context); + + return metadata; +} + +module.exports = track; + +},{}],44:[function(require,module,exports){ +var lineBreak = require('os').EOL; + +var AT_RULE = 'at-rule'; +var PROPERTY_SEPARATOR = ';'; + +function hasMoreProperties(tokens, index) { + for (var i = index, l = tokens.length; i < l; i++) { + if (typeof tokens[i] != 'string') + return true; + } + + return false; +} + +function supportsAfterClosingBrace(token) { + return token[0][0] == 'background' || token[0][0] == 'transform' || token[0][0] == 'src'; +} + +function isVariable(token, valueIndex) { + return token[valueIndex][0].indexOf('var(') === 0; +} + +function afterClosingBrace(token, valueIndex) { + return token[valueIndex][0][token[valueIndex][0].length - 1] == ')' || token[valueIndex][0].indexOf('__ESCAPED_URL_CLEAN_CSS') === 0; +} + +function afterComma(token, valueIndex) { + return token[valueIndex][0] == ','; +} + +function afterSlash(token, valueIndex) { + return token[valueIndex][0] == '/'; +} + +function beforeComma(token, valueIndex) { + return token[valueIndex + 1] && token[valueIndex + 1][0] == ','; +} + +function beforeSlash(token, valueIndex) { + return token[valueIndex + 1] && token[valueIndex + 1][0] == '/'; +} + +function inFilter(token) { + return token[0][0] == 'filter' || token[0][0] == '-ms-filter'; +} + +function inSpecialContext(token, valueIndex, context) { + return (!context.spaceAfterClosingBrace && supportsAfterClosingBrace(token) || isVariable(token, valueIndex)) && afterClosingBrace(token, valueIndex) || + beforeSlash(token, valueIndex) || + afterSlash(token, valueIndex) || + beforeComma(token, valueIndex) || + afterComma(token, valueIndex); +} + +function selectors(tokens, context) { + var store = context.store; + + for (var i = 0, l = tokens.length; i < l; i++) { + store(tokens[i], context); + + if (i < l - 1) + store(',', context); + } +} + +function body(tokens, context) { + for (var i = 0, l = tokens.length; i < l; i++) { + property(tokens, i, i == l - 1, context); + } +} + +function property(tokens, position, isLast, context) { + var store = context.store; + var token = tokens[position]; + + if (typeof token == 'string') { + store(token, context); + } else if (token[0] == AT_RULE) { + propertyAtRule(token[1], isLast, context); + } else { + store(token[0], context); + store(':', context); + value(tokens, position, isLast, context); + } +} + +function propertyAtRule(value, isLast, context) { + var store = context.store; + + store(value, context); + if (!isLast) + store(PROPERTY_SEPARATOR, context); +} + +function value(tokens, position, isLast, context) { + var store = context.store; + var token = tokens[position]; + var isVariableDeclaration = token[0][0].indexOf('--') === 0; + + if (isVariableDeclaration && atRulesOrProperties(token[1])) { + store('{', context); + body(token[1], context); + store('};', context); + return; + } + + for (var j = 1, m = token.length; j < m; j++) { + store(token[j], context); + + if (j < m - 1 && (inFilter(token) || !inSpecialContext(token, j, context))) { + store(' ', context); + } else if (j == m - 1 && !isLast && hasMoreProperties(tokens, position + 1)) { + store(PROPERTY_SEPARATOR, context); + } + } +} + +function atRulesOrProperties(values) { + for (var i = 0, l = values.length; i < l; i++) { + if (values[i][0] == AT_RULE || Array.isArray(values[i][0])) + return true; + } + + return false; +} + +function all(tokens, context) { + var joinCharacter = context.keepBreaks ? lineBreak : ''; + var store = context.store; + + for (var i = 0, l = tokens.length; i < l; i++) { + var token = tokens[i]; + + switch (token[0]) { + case 'at-rule': + case 'text': + store(token[1][0], context); + store(joinCharacter, context); + break; + case 'block': + selectors([token[1]], context); + store('{', context); + all(token[2], context); + store('}', context); + store(joinCharacter, context); + break; + case 'flat-block': + selectors([token[1]], context); + store('{', context); + body(token[2], context); + store('}', context); + store(joinCharacter, context); + break; + default: + selectors(token[1], context); + store('{', context); + body(token[2], context); + store('}', context); + store(joinCharacter, context); + } + } +} + +module.exports = { + all: all, + body: body, + property: property, + selectors: selectors, + value: value +}; + +},{"os":75}],45:[function(require,module,exports){ +var helpers = require('./helpers'); + +function store(token, context) { + context.output.push(typeof token == 'string' ? token : token[0]); +} + +function context() { + return { + output: [], + store: store + }; +} + +function all(tokens) { + var fakeContext = context(); + helpers.all(tokens, fakeContext); + return fakeContext.output.join(''); +} + +function body(tokens) { + var fakeContext = context(); + helpers.body(tokens, fakeContext); + return fakeContext.output.join(''); +} + +function property(tokens, position) { + var fakeContext = context(); + helpers.property(tokens, position, true, fakeContext); + return fakeContext.output.join(''); +} + +function selectors(tokens) { + var fakeContext = context(); + helpers.selectors(tokens, fakeContext); + return fakeContext.output.join(''); +} + +function value(tokens, position) { + var fakeContext = context(); + helpers.value(tokens, position, true, fakeContext); + return fakeContext.output.join(''); +} + +module.exports = { + all: all, + body: body, + property: property, + selectors: selectors, + value: value +}; + +},{"./helpers":44}],46:[function(require,module,exports){ +var all = require('./helpers').all; + +function store(token, context) { + context.output.push(typeof token == 'string' ? token : token[0]); +} + +function stringify(tokens, options, restoreCallback) { + var context = { + keepBreaks: options.keepBreaks, + output: [], + spaceAfterClosingBrace: options.compatibility.properties.spaceAfterClosingBrace, + store: store + }; + + all(tokens, context, false); + + return { + styles: restoreCallback(context.output.join('')).trim() + }; +} + +module.exports = stringify; + +},{"./helpers":44}],47:[function(require,module,exports){ +(function (process){ +var SourceMapGenerator = require('source-map').SourceMapGenerator; +var all = require('./helpers').all; + +var isWindows = process.platform == 'win32'; +var unknownSource = '$stdin'; + +function store(element, context) { + var fromString = typeof element == 'string'; + var value = fromString ? element : element[0]; + + if (value.indexOf('_') > -1) + value = context.restore(value, prefixContentFrom(context.output)); + + track(value, fromString ? null : element, context); + context.output.push(value); +} + +function prefixContentFrom(values) { + var content = []; + + for (var i = values.length - 1; i >= 0; i--) { + var value = values[i]; + content.unshift(value); + + if (value == '{' || value == ';') + break; + } + + return content.join(''); +} + +function track(value, element, context) { + if (element) + trackAllMappings(element, context); + + var parts = value.split('\n'); + context.line += parts.length - 1; + context.column = parts.length > 1 ? 0 : (context.column + parts.pop().length); +} + +function trackAllMappings(element, context) { + var mapping = element[element.length - 1]; + + if (!Array.isArray(mapping)) + return; + + for (var i = 0, l = mapping.length; i < l; i++) { + trackMapping(mapping[i], context); + } +} + +function trackMapping(mapping, context) { + var source = mapping[2] || unknownSource; + + if (isWindows) + source = source.replace(/\\/g, '/'); + + context.outputMap.addMapping({ + generated: { + line: context.line, + column: context.column + }, + source: source, + original: { + line: mapping[0], + column: mapping[1] + } + }); + + if (mapping[3]) + context.outputMap.setSourceContent(source, mapping[3][mapping[2]]); +} + +function stringify(tokens, options, restoreCallback, inputMapTracker) { + var context = { + column: 0, + inputMapTracker: inputMapTracker, + keepBreaks: options.keepBreaks, + line: 1, + output: [], + outputMap: new SourceMapGenerator(), + restore: restoreCallback, + sourceMapInlineSources: options.sourceMapInlineSources, + spaceAfterClosingBrace: options.compatibility.properties.spaceAfterClosingBrace, + store: store + }; + + all(tokens, context, false); + + return { + sourceMap: context.outputMap, + styles: context.output.join('').trim() + }; +} + +module.exports = stringify; + +}).call(this,require('_process')) +},{"./helpers":44,"_process":78,"source-map":110}],48:[function(require,module,exports){ +var EscapeStore = require('./escape-store'); +var QuoteScanner = require('../utils/quote-scanner'); + +var SPECIAL_COMMENT_PREFIX = '/*!'; +var COMMENT_PREFIX = '/*'; +var COMMENT_SUFFIX = '*/'; + +var lineBreak = require('os').EOL; + +function CommentsProcessor(context, keepSpecialComments, keepBreaks, saveWaypoints) { + this.comments = new EscapeStore('COMMENT'); + this.specialComments = new EscapeStore('COMMENT_SPECIAL'); + + this.context = context; + this.restored = 0; + this.keepAll = keepSpecialComments == '*'; + this.keepOne = keepSpecialComments == '1' || keepSpecialComments === 1; + this.keepBreaks = keepBreaks; + this.saveWaypoints = saveWaypoints; +} + +function quoteScannerFor(data) { + var quoteMap = []; + new QuoteScanner(data).each(function (quotedString, _, startsAt) { + quoteMap.push([startsAt, startsAt + quotedString.length]); + }); + + return function (position) { + for (var i = 0, l = quoteMap.length; i < l; i++) { + if (quoteMap[i][0] < position && quoteMap[i][1] > position) + return true; + } + + return false; + }; +} + +CommentsProcessor.prototype.escape = function (data) { + var tempData = []; + var nextStart = 0; + var nextEnd = 0; + var cursor = 0; + var indent = 0; + var breaksCount; + var lastBreakAt; + var newIndent; + var isQuotedAt = quoteScannerFor(data); + var saveWaypoints = this.saveWaypoints; + + for (; nextEnd < data.length;) { + nextStart = data.indexOf(COMMENT_PREFIX, cursor); + if (nextStart == -1) + break; + + if (isQuotedAt(nextStart)) { + tempData.push(data.substring(cursor, nextStart + COMMENT_PREFIX.length)); + cursor = nextStart + COMMENT_PREFIX.length; + continue; + } + + nextEnd = data.indexOf(COMMENT_SUFFIX, nextStart + COMMENT_PREFIX.length); + if (nextEnd == -1) { + this.context.warnings.push('Broken comment: \'' + data.substring(nextStart) + '\'.'); + nextEnd = data.length - 2; + } + + tempData.push(data.substring(cursor, nextStart)); + + var comment = data.substring(nextStart, nextEnd + COMMENT_SUFFIX.length); + var isSpecialComment = comment.indexOf(SPECIAL_COMMENT_PREFIX) === 0; + + if (saveWaypoints) { + breaksCount = comment.split(lineBreak).length - 1; + lastBreakAt = comment.lastIndexOf(lineBreak); + newIndent = lastBreakAt > 0 ? + comment.substring(lastBreakAt + lineBreak.length).length : + indent + comment.length; + } + + if (saveWaypoints || isSpecialComment) { + var metadata = saveWaypoints ? [breaksCount, newIndent] : null; + var placeholder = isSpecialComment ? + this.specialComments.store(comment, metadata) : + this.comments.store(comment, metadata); + tempData.push(placeholder); + } + + if (saveWaypoints) + indent = newIndent + 1; + cursor = nextEnd + COMMENT_SUFFIX.length; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +}; + +function restore(context, data, from, isSpecial) { + var tempData = []; + var cursor = 0; + + for (; cursor < data.length;) { + var nextMatch = from.nextMatch(data, cursor); + if (nextMatch.start < 0) + break; + + tempData.push(data.substring(cursor, nextMatch.start)); + var comment = from.restore(nextMatch.match); + + if (isSpecial && (context.keepAll || (context.keepOne && context.restored === 0))) { + context.restored++; + tempData.push(comment); + + cursor = nextMatch.end; + } else { + cursor = nextMatch.end + (context.keepBreaks && data.substring(nextMatch.end, nextMatch.end + lineBreak.length) == lineBreak ? lineBreak.length : 0); + } + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +} + +CommentsProcessor.prototype.restore = function (data) { + data = restore(this, data, this.comments, false); + data = restore(this, data, this.specialComments, true); + return data; +}; + +module.exports = CommentsProcessor; + +},{"../utils/quote-scanner":63,"./escape-store":49,"os":75}],49:[function(require,module,exports){ +var placeholderBrace = '__'; + +function EscapeStore(placeholderRoot) { + this.placeholderRoot = 'ESCAPED_' + placeholderRoot + '_CLEAN_CSS'; + this.placeholderToData = {}; + this.dataToPlaceholder = {}; + this.count = 0; + this.restoreMatcher = new RegExp(this.placeholderRoot + '(\\d+)'); +} + +EscapeStore.prototype._nextPlaceholder = function (metadata) { + return { + index: this.count, + value: placeholderBrace + this.placeholderRoot + this.count++ + metadata + placeholderBrace + }; +}; + +EscapeStore.prototype.store = function (data, metadata) { + var encodedMetadata = metadata ? + '(' + metadata.join(',') + ')' : + ''; + var placeholder = this.dataToPlaceholder[data]; + + if (!placeholder) { + var nextPlaceholder = this._nextPlaceholder(encodedMetadata); + placeholder = nextPlaceholder.value; + this.placeholderToData[nextPlaceholder.index] = data; + this.dataToPlaceholder[data] = nextPlaceholder.value; + } + + if (metadata) + placeholder = placeholder.replace(/\([^\)]+\)/, encodedMetadata); + + return placeholder; +}; + +EscapeStore.prototype.nextMatch = function (data, cursor) { + var next = {}; + + next.start = data.indexOf(this.placeholderRoot, cursor) - placeholderBrace.length; + next.end = data.indexOf(placeholderBrace, next.start + placeholderBrace.length) + placeholderBrace.length; + if (next.start > -1 && next.end > -1) + next.match = data.substring(next.start, next.end); + + return next; +}; + +EscapeStore.prototype.restore = function (placeholder) { + var index = this.restoreMatcher.exec(placeholder)[1]; + return this.placeholderToData[index]; +}; + +module.exports = EscapeStore; + +},{}],50:[function(require,module,exports){ +var EscapeStore = require('./escape-store'); + +var EXPRESSION_NAME = 'expression'; +var EXPRESSION_START = '('; +var EXPRESSION_END = ')'; +var EXPRESSION_PREFIX = EXPRESSION_NAME + EXPRESSION_START; +var BODY_START = '{'; +var BODY_END = '}'; + +var lineBreak = require('os').EOL; + +function findEnd(data, start) { + var end = start + EXPRESSION_NAME.length; + var level = 0; + var quoted = false; + var braced = false; + + while (true) { + var current = data[end++]; + + if (quoted) { + quoted = current != '\'' && current != '"'; + } else { + quoted = current == '\'' || current == '"'; + + if (current == EXPRESSION_START) + level++; + if (current == EXPRESSION_END) + level--; + if (current == BODY_START) + braced = true; + if (current == BODY_END && !braced && level == 1) { + end--; + level--; + } + } + + if (level === 0 && current == EXPRESSION_END) + break; + if (!current) { + end = data.substring(0, end).lastIndexOf(BODY_END); + break; + } + } + + return end; +} + +function ExpressionsProcessor(saveWaypoints) { + this.expressions = new EscapeStore('EXPRESSION'); + this.saveWaypoints = saveWaypoints; +} + +ExpressionsProcessor.prototype.escape = function (data) { + var nextStart = 0; + var nextEnd = 0; + var cursor = 0; + var tempData = []; + var indent = 0; + var breaksCount; + var lastBreakAt; + var newIndent; + var saveWaypoints = this.saveWaypoints; + + for (; nextEnd < data.length;) { + nextStart = data.indexOf(EXPRESSION_PREFIX, nextEnd); + if (nextStart == -1) + break; + + nextEnd = findEnd(data, nextStart); + + var expression = data.substring(nextStart, nextEnd); + if (saveWaypoints) { + breaksCount = expression.split(lineBreak).length - 1; + lastBreakAt = expression.lastIndexOf(lineBreak); + newIndent = lastBreakAt > 0 ? + expression.substring(lastBreakAt + lineBreak.length).length : + indent + expression.length; + } + + var metadata = saveWaypoints ? [breaksCount, newIndent] : null; + var placeholder = this.expressions.store(expression, metadata); + tempData.push(data.substring(cursor, nextStart)); + tempData.push(placeholder); + + if (saveWaypoints) + indent = newIndent + 1; + cursor = nextEnd; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +}; + +ExpressionsProcessor.prototype.restore = function (data) { + var tempData = []; + var cursor = 0; + + for (; cursor < data.length;) { + var nextMatch = this.expressions.nextMatch(data, cursor); + if (nextMatch.start < 0) + break; + + tempData.push(data.substring(cursor, nextMatch.start)); + var comment = this.expressions.restore(nextMatch.match); + tempData.push(comment); + + cursor = nextMatch.end; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +}; + +module.exports = ExpressionsProcessor; + +},{"./escape-store":49,"os":75}],51:[function(require,module,exports){ +var EscapeStore = require('./escape-store'); +var QuoteScanner = require('../utils/quote-scanner'); + +var lineBreak = require('os').EOL; + +function FreeTextProcessor(saveWaypoints) { + this.matches = new EscapeStore('FREE_TEXT'); + this.saveWaypoints = saveWaypoints; +} + +// Strip content tags by replacing them by the a special +// marker for further restoring. It's done via string scanning +// instead of regexps to speed up the process. +FreeTextProcessor.prototype.escape = function (data) { + var self = this; + var breaksCount; + var lastBreakAt; + var indent; + var metadata; + var saveWaypoints = this.saveWaypoints; + + return new QuoteScanner(data).each(function (match, store) { + if (saveWaypoints) { + breaksCount = match.split(lineBreak).length - 1; + lastBreakAt = match.lastIndexOf(lineBreak); + indent = lastBreakAt > 0 ? + match.substring(lastBreakAt + lineBreak.length).length : + match.length; + metadata = [breaksCount, indent]; + } + + var placeholder = self.matches.store(match, metadata); + store.push(placeholder); + }); +}; + +function normalize(text, data, prefixContext, cursor) { + // FIXME: this is even a bigger hack now - see #407 + var searchIn = data; + if (prefixContext) { + searchIn = prefixContext + data.substring(0, data.indexOf('__ESCAPED_FREE_TEXT_CLEAN_CSS')); + cursor = searchIn.length; + } + + var lastSemicolon = searchIn.lastIndexOf(';', cursor); + var lastOpenBrace = searchIn.lastIndexOf('{', cursor); + var lastOne = 0; + + if (lastSemicolon > -1 && lastOpenBrace > -1) + lastOne = Math.max(lastSemicolon, lastOpenBrace); + else if (lastSemicolon == -1) + lastOne = lastOpenBrace; + else + lastOne = lastSemicolon; + + var context = searchIn.substring(lastOne + 1, cursor); + + if (/\[[\w\d\-]+[\*\|\~\^\$]?=$/.test(context)) { + text = text + .replace(/\\\n|\\\r\n/g, '') + .replace(/\n|\r\n/g, ''); + } + + if (/^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/.test(text) && !/format\($/.test(context)) { + var isFont = /^(font|font\-family):/.test(context); + var isAttribute = /\[[\w\d\-]+[\*\|\~\^\$]?=$/.test(context); + var isKeyframe = /@(-moz-|-o-|-webkit-)?keyframes /.test(context); + var isAnimation = /^(-moz-|-o-|-webkit-)?animation(-name)?:/.test(context); + + if (isFont || isAttribute || isKeyframe || isAnimation) + text = text.substring(1, text.length - 1); + } + + return text; +} + +FreeTextProcessor.prototype.restore = function (data, prefixContext) { + var tempData = []; + var cursor = 0; + + for (; cursor < data.length;) { + var nextMatch = this.matches.nextMatch(data, cursor); + if (nextMatch.start < 0) + break; + + tempData.push(data.substring(cursor, nextMatch.start)); + var text = normalize(this.matches.restore(nextMatch.match), data, prefixContext, nextMatch.start); + tempData.push(text); + + cursor = nextMatch.end; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +}; + +module.exports = FreeTextProcessor; + +},{"../utils/quote-scanner":63,"./escape-store":49,"os":75}],52:[function(require,module,exports){ +var EscapeStore = require('./escape-store'); +var reduceUrls = require('../urls/reduce'); + +var lineBreak = require('os').EOL; + +function UrlsProcessor(context, saveWaypoints, keepUrlQuotes) { + this.urls = new EscapeStore('URL'); + this.context = context; + this.saveWaypoints = saveWaypoints; + this.keepUrlQuotes = keepUrlQuotes; +} + +// Strip urls by replacing them by a special +// marker for further restoring. It's done via string scanning +// instead of regexps to speed up the process. +UrlsProcessor.prototype.escape = function (data) { + var breaksCount; + var lastBreakAt; + var indent; + var saveWaypoints = this.saveWaypoints; + var self = this; + + return reduceUrls(data, this.context, function (url, tempData) { + if (saveWaypoints) { + breaksCount = url.split(lineBreak).length - 1; + lastBreakAt = url.lastIndexOf(lineBreak); + indent = lastBreakAt > 0 ? + url.substring(lastBreakAt + lineBreak.length).length : + url.length; + } + + var placeholder = self.urls.store(url, saveWaypoints ? [breaksCount, indent] : null); + tempData.push(placeholder); + }); +}; + +function normalize(url, keepUrlQuotes) { + url = url + .replace(/^url/gi, 'url') + .replace(/\\?\n|\\?\r\n/g, '') + .replace(/(\s{2,}|\s)/g, ' ') + .replace(/^url\((['"])? /, 'url($1') + .replace(/ (['"])?\)$/, '$1)'); + + if (!keepUrlQuotes && !/^['"].+['"]$/.test(url) && !/url\(.*[\s\(\)].*\)/.test(url) && !/url\(['"]data:[^;]+;charset/.test(url)) + url = url.replace(/["']/g, ''); + + return url; +} + +UrlsProcessor.prototype.restore = function (data) { + var tempData = []; + var cursor = 0; + + for (; cursor < data.length;) { + var nextMatch = this.urls.nextMatch(data, cursor); + if (nextMatch.start < 0) + break; + + tempData.push(data.substring(cursor, nextMatch.start)); + var url = normalize(this.urls.restore(nextMatch.match), this.keepUrlQuotes); + tempData.push(url); + + cursor = nextMatch.end; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +}; + +module.exports = UrlsProcessor; + +},{"../urls/reduce":57,"./escape-store":49,"os":75}],53:[function(require,module,exports){ +var split = require('../utils/split'); + +var COMMA = ','; +var FORWARD_SLASH = '/'; + +var AT_RULE = 'at-rule'; + +function selectorName(value) { + return value[0]; +} + +function noop() {} + +function withoutComments(string, into, heading, context) { + var matcher = heading ? /^__ESCAPED_COMMENT_/ : /__ESCAPED_COMMENT_/; + var track = heading ? context.track : noop; // don't track when comment not in a heading as we do it later in `trackComments` + + while (matcher.test(string)) { + var startOfComment = string.indexOf('__'); + var endOfComment = string.indexOf('__', startOfComment + 1) + 2; + var comment = string.substring(startOfComment, endOfComment); + string = string.substring(0, startOfComment) + string.substring(endOfComment); + + track(comment); + into.push(comment); + } + + return string; +} + +function withoutHeadingComments(string, into, context) { + return withoutComments(string, into, true, context); +} + +function withoutInnerComments(string, into, context) { + return withoutComments(string, into, false, context); +} + +function trackComments(comments, into, context) { + for (var i = 0, l = comments.length; i < l; i++) { + context.track(comments[i]); + into.push(comments[i]); + } +} + +function extractProperties(string, selectors, context) { + var list = []; + var innerComments = []; + var valueSeparator = /[ ,\/]/; + + if (typeof string != 'string') + return []; + + if (string.indexOf(')') > -1) + string = string.replace(/\)([^\s_;:,\)])/g, context.sourceMap ? ') __ESCAPED_COMMENT_CLEAN_CSS(0,-1)__ $1' : ') $1'); + + if (string.indexOf('ESCAPED_URL_CLEAN_CSS') > -1) + string = string.replace(/(ESCAPED_URL_CLEAN_CSS[^_]+?__)/g, context.sourceMap ? '$1 __ESCAPED_COMMENT_CLEAN_CSS(0,-1)__ ' : '$1 '); + + var candidates = split(string, ';', false, '{', '}'); + + for (var i = 0, l = candidates.length; i < l; i++) { + var candidate = candidates[i]; + var firstColonAt = candidate.indexOf(':'); + + var atRule = candidate.trim()[0] == '@'; + if (atRule) { + context.track(candidate); + list.push([AT_RULE, candidate.trim()]); + continue; + } + + if (firstColonAt == -1) { + context.track(candidate); + if (candidate.indexOf('__ESCAPED_COMMENT_SPECIAL') > -1) + list.push(candidate.trim()); + continue; + } + + if (candidate.indexOf('{') > 0 && candidate.indexOf('{') < firstColonAt) { + context.track(candidate); + continue; + } + + var body = []; + var name = candidate.substring(0, firstColonAt); + + innerComments = []; + + if (name.indexOf('__ESCAPED_COMMENT') > -1) + name = withoutHeadingComments(name, list, context); + + if (name.indexOf('__ESCAPED_COMMENT') > -1) + name = withoutInnerComments(name, innerComments, context); + + body.push([name.trim()].concat(context.track(name, true))); + context.track(':'); + + trackComments(innerComments, list, context); + + var firstBraceAt = candidate.indexOf('{'); + var isVariable = name.trim().indexOf('--') === 0; + if (isVariable && firstBraceAt > 0) { + var blockPrefix = candidate.substring(firstColonAt + 1, firstBraceAt + 1); + var blockSuffix = candidate.substring(candidate.indexOf('}')); + var blockContent = candidate.substring(firstBraceAt + 1, candidate.length - blockSuffix.length); + + context.track(blockPrefix); + body.push(extractProperties(blockContent, selectors, context)); + list.push(body); + context.track(blockSuffix); + context.track(i < l - 1 ? ';' : ''); + + continue; + } + + var values = split(candidate.substring(firstColonAt + 1), valueSeparator, true); + + if (values.length == 1 && values[0] === '') { + context.warnings.push('Empty property \'' + name + '\' inside \'' + selectors.filter(selectorName).join(',') + '\' selector. Ignoring.'); + continue; + } + + for (var j = 0, m = values.length; j < m; j++) { + var value = values[j]; + var trimmed = value.trim(); + + if (trimmed.length === 0) + continue; + + var lastCharacter = trimmed[trimmed.length - 1]; + var endsWithNonSpaceSeparator = trimmed.length > 1 && (lastCharacter == COMMA || lastCharacter == FORWARD_SLASH); + + if (endsWithNonSpaceSeparator) + trimmed = trimmed.substring(0, trimmed.length - 1); + + if (trimmed.indexOf('__ESCAPED_COMMENT_CLEAN_CSS(0,-') > -1) { + context.track(trimmed); + continue; + } + + innerComments = []; + + if (trimmed.indexOf('__ESCAPED_COMMENT') > -1) + trimmed = withoutHeadingComments(trimmed, list, context); + + if (trimmed.indexOf('__ESCAPED_COMMENT') > -1) + trimmed = withoutInnerComments(trimmed, innerComments, context); + + if (trimmed.length === 0) { + trackComments(innerComments, list, context); + continue; + } + + var pos = body.length - 1; + if (trimmed == 'important' && body[pos][0] == '!') { + context.track(trimmed); + body[pos - 1][0] += '!important'; + body.pop(); + continue; + } + + if (trimmed == '!important' || (trimmed == 'important' && body[pos][0][body[pos][0].length - 1] == '!')) { + context.track(trimmed); + body[pos][0] += trimmed; + continue; + } + + body.push([trimmed].concat(context.track(value, true))); + + trackComments(innerComments, list, context); + + if (endsWithNonSpaceSeparator) { + body.push([lastCharacter]); + context.track(lastCharacter); + } + } + + if (i < l - 1) + context.track(';'); + + list.push(body); + } + + return list; +} + +module.exports = extractProperties; + +},{"../utils/split":66}],54:[function(require,module,exports){ +var split = require('../utils/split'); + +function extractSelectors(string, context) { + var list = []; + var metadata; + var selectors = split(string, ','); + + for (var i = 0, l = selectors.length; i < l; i++) { + metadata = context.track(selectors[i], true, i); + context.track(','); + list.push([selectors[i].trim()].concat(metadata)); + } + + return list; +} + +module.exports = extractSelectors; + +},{"../utils/split":66}],55:[function(require,module,exports){ +var extractProperties = require('./extract-properties'); +var extractSelectors = require('./extract-selectors'); +var track = require('../source-maps/track'); +var split = require('../utils/split'); + +var path = require('path'); + +var flatBlock = /(@(font\-face|page|\-ms\-viewport|\-o\-viewport|viewport|counter\-style)|\\@.+?)/; + +function tokenize(data, outerContext) { + var chunks = split(normalize(data), '}', true, '{', '}'); + if (chunks.length === 0) + return []; + + var context = { + chunk: chunks.shift(), + chunks: chunks, + column: 0, + cursor: 0, + line: 1, + mode: 'top', + resolvePath: outerContext.options.explicitTarget ? + relativePathResolver(outerContext.options.root, outerContext.options.target) : + null, + source: undefined, + sourceMap: outerContext.options.sourceMap, + sourceMapInlineSources: outerContext.options.sourceMapInlineSources, + sourceMapTracker: outerContext.inputSourceMapTracker, + sourceReader: outerContext.sourceReader, + sourceTracker: outerContext.sourceTracker, + state: [], + track: outerContext.options.sourceMap ? + function (data, snapshotMetadata, fallbacks) { return [[track(data, context, snapshotMetadata, fallbacks)]]; } : + function () { return []; }, + warnings: outerContext.warnings + }; + + return intoTokens(context); +} + +function normalize(data) { + return data.replace(/\r\n/g, '\n'); +} + +function relativePathResolver(root, target) { + var rebaseTo = path.relative(root, target); + + return function (relativeTo, sourcePath) { + return relativeTo != sourcePath ? + path.normalize(path.join(path.relative(rebaseTo, path.dirname(relativeTo)), sourcePath)) : + sourcePath; + }; +} + +function whatsNext(context) { + var mode = context.mode; + var chunk = context.chunk; + var closest; + + if (chunk.length == context.cursor) { + if (context.chunks.length === 0) + return null; + + context.chunk = chunk = context.chunks.shift(); + context.cursor = 0; + } + + if (mode == 'body') { + if (chunk[context.cursor] == '}') + return [context.cursor, 'bodyEnd']; + + if (chunk.indexOf('}', context.cursor) == -1) + return null; + + closest = context.cursor + split(chunk.substring(context.cursor - 1), '}', true, '{', '}')[0].length - 2; + return [closest, 'bodyEnd']; + } + + var nextSpecial = chunk.indexOf('@', context.cursor); + var nextEscape = chunk.indexOf('__ESCAPED_', context.cursor); + var nextBodyStart = chunk.indexOf('{', context.cursor); + var nextBodyEnd = chunk.indexOf('}', context.cursor); + + if (nextEscape > -1 && /\S/.test(chunk.substring(context.cursor, nextEscape))) + nextEscape = -1; + + closest = nextSpecial; + if (closest == -1 || (nextEscape > -1 && nextEscape < closest)) + closest = nextEscape; + if (closest == -1 || (nextBodyStart > -1 && nextBodyStart < closest)) + closest = nextBodyStart; + if (closest == -1 || (nextBodyEnd > -1 && nextBodyEnd < closest)) + closest = nextBodyEnd; + + if (closest == -1) + return; + if (nextEscape === closest) + return [closest, 'escape']; + if (nextBodyStart === closest) + return [closest, 'bodyStart']; + if (nextBodyEnd === closest) + return [closest, 'bodyEnd']; + if (nextSpecial === closest) + return [closest, 'special']; +} + +function intoTokens(context) { + var chunk = context.chunk; + var tokenized = []; + var newToken; + var value; + + while (true) { + var next = whatsNext(context); + if (!next) { + var whatsLeft = context.chunk.substring(context.cursor); + if (whatsLeft.trim().length > 0) { + if (context.mode == 'body') { + context.warnings.push('Missing \'}\' after \'' + whatsLeft + '\'. Ignoring.'); + } else { + tokenized.push(['text', [whatsLeft]]); + } + context.cursor += whatsLeft.length; + } + break; + } + + var nextSpecial = next[0]; + var what = next[1]; + var nextEnd; + var oldMode; + + chunk = context.chunk; + + if (context.cursor != nextSpecial && what != 'bodyEnd') { + var spacing = chunk.substring(context.cursor, nextSpecial); + var leadingWhitespace = /^\s+/.exec(spacing); + + if (leadingWhitespace) { + context.cursor += leadingWhitespace[0].length; + context.track(leadingWhitespace[0]); + } + } + + if (what == 'special') { + var firstOpenBraceAt = chunk.indexOf('{', nextSpecial); + var firstSemicolonAt = chunk.indexOf(';', nextSpecial); + var isSingle = firstSemicolonAt > -1 && (firstOpenBraceAt == -1 || firstSemicolonAt < firstOpenBraceAt); + var isBroken = firstOpenBraceAt == -1 && firstSemicolonAt == -1; + if (isBroken) { + context.warnings.push('Broken declaration: \'' + chunk.substring(context.cursor) + '\'.'); + context.cursor = chunk.length; + } else if (isSingle) { + nextEnd = chunk.indexOf(';', nextSpecial + 1); + value = chunk.substring(context.cursor, nextEnd + 1); + + tokenized.push([ + 'at-rule', + [value].concat(context.track(value, true)) + ]); + + context.track(';'); + context.cursor = nextEnd + 1; + } else { + nextEnd = chunk.indexOf('{', nextSpecial + 1); + value = chunk.substring(context.cursor, nextEnd); + + var trimmedValue = value.trim(); + var isFlat = flatBlock.test(trimmedValue); + oldMode = context.mode; + context.cursor = nextEnd + 1; + context.mode = isFlat ? 'body' : 'block'; + + newToken = [ + isFlat ? 'flat-block' : 'block' + ]; + + newToken.push([trimmedValue].concat(context.track(value, true))); + context.track('{'); + newToken.push(intoTokens(context)); + + if (typeof newToken[2] == 'string') + newToken[2] = extractProperties(newToken[2], [[trimmedValue]], context); + + context.mode = oldMode; + context.track('}'); + + tokenized.push(newToken); + } + } else if (what == 'escape') { + nextEnd = chunk.indexOf('__', nextSpecial + 1); + var escaped = chunk.substring(context.cursor, nextEnd + 2); + var isStartSourceMarker = !!context.sourceTracker.nextStart(escaped); + var isEndSourceMarker = !!context.sourceTracker.nextEnd(escaped); + + if (isStartSourceMarker) { + context.track(escaped); + context.state.push({ + source: context.source, + line: context.line, + column: context.column + }); + context.source = context.sourceTracker.nextStart(escaped).filename; + context.line = 1; + context.column = 0; + } else if (isEndSourceMarker) { + var oldState = context.state.pop(); + context.source = oldState.source; + context.line = oldState.line; + context.column = oldState.column; + context.track(escaped); + } else { + if (escaped.indexOf('__ESCAPED_COMMENT_SPECIAL') === 0) + tokenized.push(['text', [escaped]]); + + context.track(escaped); + } + + context.cursor = nextEnd + 2; + } else if (what == 'bodyStart') { + var selectors = extractSelectors(chunk.substring(context.cursor, nextSpecial), context); + + oldMode = context.mode; + context.cursor = nextSpecial + 1; + context.mode = 'body'; + + var body = extractProperties(intoTokens(context), selectors, context); + + context.track('{'); + context.mode = oldMode; + + tokenized.push([ + 'selector', + selectors, + body + ]); + } else if (what == 'bodyEnd') { + // extra closing brace at the top level can be safely ignored + if (context.mode == 'top') { + var at = context.cursor; + var warning = chunk[context.cursor] == '}' ? + 'Unexpected \'}\' in \'' + chunk.substring(at - 20, at + 20) + '\'. Ignoring.' : + 'Unexpected content: \'' + chunk.substring(at, nextSpecial + 1) + '\'. Ignoring.'; + + context.warnings.push(warning); + context.cursor = nextSpecial + 1; + continue; + } + + if (context.mode == 'block') + context.track(chunk.substring(context.cursor, nextSpecial)); + if (context.mode != 'block') + tokenized = chunk.substring(context.cursor, nextSpecial); + + context.cursor = nextSpecial + 1; + + break; + } + } + + return tokenized; +} + +module.exports = tokenize; + +},{"../source-maps/track":43,"../utils/split":66,"./extract-properties":53,"./extract-selectors":54,"path":76}],56:[function(require,module,exports){ +var path = require('path'); + +var rewriteUrls = require('./rewrite'); + +function rebaseUrls(data, context) { + var rebaseOpts = { + absolute: context.options.explicitRoot, + relative: !context.options.explicitRoot && context.options.explicitTarget, + fromBase: context.options.relativeTo + }; + + if (!rebaseOpts.absolute && !rebaseOpts.relative) + return data; + + if (rebaseOpts.absolute && context.options.explicitTarget) + context.warnings.push('Both \'root\' and output file given so rebasing URLs as absolute paths'); + + if (rebaseOpts.absolute) + rebaseOpts.toBase = path.resolve(context.options.root); + + if (rebaseOpts.relative) + rebaseOpts.toBase = path.resolve(context.options.target); + + if (!rebaseOpts.fromBase || !rebaseOpts.toBase) + return data; + + return rewriteUrls(data, rebaseOpts, context); +} + +module.exports = rebaseUrls; + +},{"./rewrite":58,"path":76}],57:[function(require,module,exports){ +var URL_PREFIX = 'url('; +var UPPERCASE_URL_PREFIX = 'URL('; +var URL_SUFFIX = ')'; +var DATA_URI_PREFIX = 'data:'; + +var IMPORT_URL_PREFIX = '@import'; +var UPPERCASE_IMPORT_URL_PREFIX = '@IMPORT'; + +var COMMENT_END_MARKER = /\*\//; + +function byUrl(data, context, callback) { + var nextStart = 0; + var nextStartUpperCase = 0; + var nextEnd = 0; + var nextEndAhead = 0; + var isDataURI = false; + var cursor = 0; + var tempData = []; + var hasUppercaseUrl = data.indexOf(UPPERCASE_URL_PREFIX) > -1; + + for (; nextEnd < data.length;) { + nextStart = data.indexOf(URL_PREFIX, nextEnd); + nextStartUpperCase = hasUppercaseUrl ? data.indexOf(UPPERCASE_URL_PREFIX, nextEnd) : -1; + if (nextStart == -1 && nextStartUpperCase == -1) + break; + + if (nextStart == -1 && nextStartUpperCase > -1) + nextStart = nextStartUpperCase; + + + if (data[nextStart + URL_PREFIX.length] == '"') { + nextEnd = data.indexOf('"', nextStart + URL_PREFIX.length + 1); + } else if (data[nextStart + URL_PREFIX.length] == '\'') { + nextEnd = data.indexOf('\'', nextStart + URL_PREFIX.length + 1); + } else { + isDataURI = data.substring(nextStart + URL_PREFIX.length).trim().indexOf(DATA_URI_PREFIX) === 0; + nextEnd = data.indexOf(URL_SUFFIX, nextStart); + + if (isDataURI) { + // this is a fuzzy matching logic for unqoted data URIs + while (true) { + nextEndAhead = data.indexOf(URL_SUFFIX, nextEnd + 1); + // if it has whitespace, curly braces, or semicolon then we should be out of URL, + // otherwise keep iterating if it has not but content is not escaped, + // it has to be quoted so it will be captured by either of two clauses above + if (nextEndAhead == -1 || /[\s\{\};]/.test(data.substring(nextEnd, nextEndAhead))) + break; + + nextEnd = nextEndAhead; + } + } + } + + + // Following lines are a safety mechanism to ensure + // incorrectly terminated urls are processed correctly. + if (nextEnd == -1) { + nextEnd = data.indexOf('}', nextStart); + + if (nextEnd == -1) + nextEnd = data.length; + else + nextEnd--; + + context.warnings.push('Broken URL declaration: \'' + data.substring(nextStart, nextEnd + 1) + '\'.'); + } else { + if (data[nextEnd] != URL_SUFFIX) + nextEnd = data.indexOf(URL_SUFFIX, nextEnd); + } + + tempData.push(data.substring(cursor, nextStart)); + + var url = data.substring(nextStart, nextEnd + 1); + callback(url, tempData); + + cursor = nextEnd + 1; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +} + +function byImport(data, context, callback) { + var nextImport = 0; + var nextImportUpperCase = 0; + var nextStart = 0; + var nextEnd = 0; + var cursor = 0; + var tempData = []; + var nextSingleQuote = 0; + var nextDoubleQuote = 0; + var untilNextQuote; + var withQuote; + var SINGLE_QUOTE = '\''; + var DOUBLE_QUOTE = '"'; + + for (; nextEnd < data.length;) { + nextImport = data.indexOf(IMPORT_URL_PREFIX, nextEnd); + nextImportUpperCase = data.indexOf(UPPERCASE_IMPORT_URL_PREFIX, nextEnd); + if (nextImport == -1 && nextImportUpperCase == -1) + break; + + if (nextImport > -1 && nextImportUpperCase > -1 && nextImportUpperCase < nextImport) + nextImport = nextImportUpperCase; + + nextSingleQuote = data.indexOf(SINGLE_QUOTE, nextImport); + nextDoubleQuote = data.indexOf(DOUBLE_QUOTE, nextImport); + + if (nextSingleQuote > -1 && nextDoubleQuote > -1 && nextSingleQuote < nextDoubleQuote) { + nextStart = nextSingleQuote; + withQuote = SINGLE_QUOTE; + } else if (nextSingleQuote > -1 && nextDoubleQuote > -1 && nextSingleQuote > nextDoubleQuote) { + nextStart = nextDoubleQuote; + withQuote = DOUBLE_QUOTE; + } else if (nextSingleQuote > -1) { + nextStart = nextSingleQuote; + withQuote = SINGLE_QUOTE; + } else if (nextDoubleQuote > -1) { + nextStart = nextDoubleQuote; + withQuote = DOUBLE_QUOTE; + } else { + break; + } + + tempData.push(data.substring(cursor, nextStart)); + nextEnd = data.indexOf(withQuote, nextStart + 1); + + untilNextQuote = data.substring(nextImport, nextEnd); + if (nextEnd == -1 || /^@import\s+(url\(|__ESCAPED)/i.test(untilNextQuote) || COMMENT_END_MARKER.test(untilNextQuote)) { + cursor = nextStart; + break; + } + + var url = data.substring(nextStart, nextEnd + 1); + callback(url, tempData); + + cursor = nextEnd + 1; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +} + +function reduceAll(data, context, callback) { + data = byUrl(data, context, callback); + data = byImport(data, context, callback); + return data; +} + +module.exports = reduceAll; + +},{}],58:[function(require,module,exports){ +(function (process){ +var path = require('path'); +var url = require('url'); + +var reduceUrls = require('./reduce'); + +var isWindows = process.platform == 'win32'; + +function isAbsolute(uri) { + return uri[0] == '/'; +} + +function isSVGMarker(uri) { + return uri[0] == '#'; +} + +function isEscaped(uri) { + return uri.indexOf('__ESCAPED_URL_CLEAN_CSS__') === 0; +} + +function isInternal(uri) { + return /^\w+:\w+/.test(uri); +} + +function isRemote(uri) { + return /^[^:]+?:\/\//.test(uri) || uri.indexOf('//') === 0; +} + +function isSameOrigin(uri1, uri2) { + return url.parse(uri1).protocol == url.parse(uri2).protocol && + url.parse(uri1).host == url.parse(uri2).host; +} + +function isImport(uri) { + return uri.lastIndexOf('.css') === uri.length - 4; +} + +function isData(uri) { + return uri.indexOf('data:') === 0; +} + +function absolute(uri, options) { + return path + .resolve(path.join(options.fromBase || '', uri)) + .replace(options.toBase, ''); +} + +function relative(uri, options) { + return path.relative(options.toBase, path.join(options.fromBase || '', uri)); +} + +function normalize(uri) { + return isWindows ? uri.replace(/\\/g, '/') : uri; +} + +function rebase(uri, options) { + if (isAbsolute(uri) || isSVGMarker(uri) || isEscaped(uri) || isInternal(uri)) + return uri; + + if (options.rebase === false && !isImport(uri)) + return uri; + + if (!options.imports && isImport(uri)) + return uri; + + if (isData(uri)) + return '\'' + uri + '\''; + + if (isRemote(uri) && !isRemote(options.toBase)) + return uri; + + if (isRemote(uri) && !isSameOrigin(uri, options.toBase)) + return uri; + + if (!isRemote(uri) && isRemote(options.toBase)) + return url.resolve(options.toBase, uri); + + return options.absolute ? + normalize(absolute(uri, options)) : + normalize(relative(uri, options)); +} + +function quoteFor(url) { + if (url.indexOf('\'') > -1) + return '"'; + else if (url.indexOf('"') > -1) + return '\''; + else if (/\s/.test(url) || /[\(\)]/.test(url)) + return '\''; + else + return ''; +} + +function rewriteUrls(data, options, context) { + return reduceUrls(data, context, function (originUrl, tempData) { + var url = originUrl.replace(/^(url\()?\s*['"]?|['"]?\s*\)?$/g, ''); + var match = originUrl.match(/^(url\()?\s*(['"]).*?(['"])\s*\)?$/); + var quote; + if (!!options.urlQuotes && match && match[2] === match[3]) { + quote = match[2]; + } else { + quote = quoteFor(url); + } + tempData.push('url(' + quote + rebase(url, options) + quote + ')'); + }); +} + +module.exports = rewriteUrls; + +}).call(this,require('_process')) +},{"./reduce":57,"_process":78,"path":76,"url":140}],59:[function(require,module,exports){ +function cloneArray(array) { + var cloned = array.slice(0); + + for (var i = 0, l = cloned.length; i < l; i++) { + if (Array.isArray(cloned[i])) + cloned[i] = cloneArray(cloned[i]); + } + + return cloned; +} + +module.exports = cloneArray; + +},{}],60:[function(require,module,exports){ +var util = require('util'); + +var DEFAULTS = { + '*': { + colors: { + opacity: true // rgba / hsla + }, + properties: { + backgroundClipMerging: false, // background-clip to shorthand + backgroundOriginMerging: false, // background-origin to shorthand + backgroundSizeMerging: false, // background-size to shorthand + colors: true, // any kind of color transformations, like `#ff00ff` to `#f0f` or `#fff` into `red` + ieBangHack: false, // !ie suffix hacks on IE<8 + iePrefixHack: false, // underscore / asterisk prefix hacks on IE + ieSuffixHack: true, // \9 suffix hacks on IE6-9 + merging: true, // merging properties into one + shorterLengthUnits: false, // optimize pixel units into `pt`, `pc` or `in` units + spaceAfterClosingBrace: true, // 'url() no-repeat' to 'url()no-repeat' + urlQuotes: false, // whether to wrap content of `url()` into quotes or not + zeroUnits: true // 0[unit] -> 0 + }, + selectors: { + adjacentSpace: false, // div+ nav Android stock browser hack + ie7Hack: false, // *+html hack + special: /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:dir\([a-z-]*\)|:first(?![a-z-])|:fullscreen|:left|:read-only|:read-write|:right|:placeholder|:host|::content|\/deep\/|::shadow)/ // special selectors which prevent merging + }, + units: { + ch: true, + in: true, + pc: true, + pt: true, + rem: true, + vh: true, + vm: true, // vm is vmin on IE9+ see https://developer.mozilla.org/en-US/docs/Web/CSS/length + vmax: true, + vmin: true, + vw: true + } + }, + 'ie8': { + colors: { + opacity: false + }, + properties: { + backgroundClipMerging: false, + backgroundOriginMerging: false, + backgroundSizeMerging: false, + colors: true, + ieBangHack: false, + iePrefixHack: true, + ieSuffixHack: true, + merging: false, + shorterLengthUnits: false, + spaceAfterClosingBrace: true, + urlQuotes: false, + zeroUnits: true + }, + selectors: { + adjacentSpace: false, + ie7Hack: false, + special: /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not|:placeholder|:host|::content|\/deep\/|::shadow)/ + }, + units: { + ch: false, + in: true, + pc: true, + pt: true, + rem: false, + vh: false, + vm: false, + vmax: false, + vmin: false, + vw: false + } + }, + 'ie7': { + colors: { + opacity: false + }, + properties: { + backgroundClipMerging: false, + backgroundOriginMerging: false, + backgroundSizeMerging: false, + colors: true, + ieBangHack: true, + iePrefixHack: true, + ieSuffixHack: true, + merging: false, + shorterLengthUnits: false, + spaceAfterClosingBrace: true, + urlQuotes: false, + zeroUnits: true + }, + selectors: { + adjacentSpace: false, + ie7Hack: true, + special: /(\-moz\-|\-ms\-|\-o\-|\-webkit\-|:focus|:before|:after|:root|:nth|:first\-of|:last|:only|:empty|:target|:checked|::selection|:enabled|:disabled|:not|:placeholder|:host|::content|\/deep\/|::shadow)/ + }, + units: { + ch: false, + in: true, + pc: true, + pt: true, + rem: false, + vh: false, + vm: false, + vmax: false, + vmin: false, + vw: false, + } + } +}; + +function Compatibility(source) { + this.source = source || {}; +} + +function merge(source, target) { + for (var key in source) { + var value = source[key]; + + if (typeof value === 'object' && !util.isRegExp(value)) + target[key] = merge(value, target[key] || {}); + else + target[key] = key in target ? target[key] : value; + } + + return target; +} + +function calculateSource(source) { + if (typeof source == 'object') + return source; + + if (!/[,\+\-]/.test(source)) + return DEFAULTS[source] || DEFAULTS['*']; + + var parts = source.split(','); + var template = parts[0] in DEFAULTS ? + DEFAULTS[parts.shift()] : + DEFAULTS['*']; + + source = {}; + + parts.forEach(function (part) { + var isAdd = part[0] == '+'; + var key = part.substring(1).split('.'); + var group = key[0]; + var option = key[1]; + + source[group] = source[group] || {}; + source[group][option] = isAdd; + }); + + return merge(template, source); +} + +Compatibility.prototype.toOptions = function () { + return merge(DEFAULTS['*'], calculateSource(this.source)); +}; + +module.exports = Compatibility; + +},{"util":144}],61:[function(require,module,exports){ +(function (process,global,Buffer){ +var SourceMapConsumer = require('source-map').SourceMapConsumer; + +var fs = require('fs'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var url = require('url'); + +var override = require('../utils/object.js').override; + +var MAP_MARKER = /\/\*# sourceMappingURL=(\S+) \*\//; +var REMOTE_RESOURCE = /^(https?:)?\/\//; +var DATA_URI = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/; + +var unescape = global.unescape; + +function InputSourceMapStore(outerContext) { + this.options = outerContext.options; + this.errors = outerContext.errors; + this.warnings = outerContext.warnings; + this.sourceTracker = outerContext.sourceTracker; + this.timeout = this.options.inliner.timeout; + this.requestOptions = this.options.inliner.request; + this.localOnly = outerContext.localOnly; + this.relativeTo = outerContext.options.target || process.cwd(); + + this.maps = {}; + this.sourcesContent = {}; +} + +function fromString(self, _, whenDone) { + self.trackLoaded(undefined, undefined, self.options.sourceMap); + return whenDone(); +} + +function fromSource(self, data, whenDone, context) { + var nextAt = 0; + + function proceedToNext() { + context.cursor += nextAt + 1; + fromSource(self, data, whenDone, context); + } + + while (context.cursor < data.length) { + var fragment = data.substring(context.cursor); + + var markerStartMatch = self.sourceTracker.nextStart(fragment) || { index: -1 }; + var markerEndMatch = self.sourceTracker.nextEnd(fragment) || { index: -1 }; + var mapMatch = MAP_MARKER.exec(fragment) || { index: -1 }; + var sourceMapFile = mapMatch[1]; + + nextAt = data.length; + if (markerStartMatch.index > -1) + nextAt = markerStartMatch.index; + if (markerEndMatch.index > -1 && markerEndMatch.index < nextAt) + nextAt = markerEndMatch.index; + if (mapMatch.index > -1 && mapMatch.index < nextAt) + nextAt = mapMatch.index; + + if (nextAt == data.length) + break; + + if (nextAt == markerStartMatch.index) { + context.files.push(markerStartMatch.filename); + } else if (nextAt == markerEndMatch.index) { + context.files.pop(); + } else if (nextAt == mapMatch.index) { + var isRemote = /^https?:\/\//.test(sourceMapFile) || /^\/\//.test(sourceMapFile); + var isDataUri = DATA_URI.test(sourceMapFile); + + if (isRemote) { + return fetchMapFile(self, sourceMapFile, context, proceedToNext); + } else { + var sourceFile = context.files[context.files.length - 1]; + var sourceMapPath, sourceMapData; + var sourceDir = sourceFile ? path.dirname(sourceFile) : self.options.relativeTo; + + if (isDataUri) { + // source map's path is the same as the source file it comes from + sourceMapPath = path.resolve(self.options.root, sourceFile || ''); + sourceMapData = fromDataUri(sourceMapFile); + } else { + sourceMapPath = path.resolve(self.options.root, path.join(sourceDir || '', sourceMapFile)); + sourceMapData = fs.readFileSync(sourceMapPath, 'utf-8'); + } + self.trackLoaded(sourceFile || undefined, sourceMapPath, sourceMapData); + } + } + + context.cursor += nextAt + 1; + } + + return whenDone(); +} + +function fromDataUri(uriString) { + var match = DATA_URI.exec(uriString); + var charset = match[2] ? match[2].split(/[=;]/)[2] : 'us-ascii'; + var encoding = match[3] ? match[3].split(';')[1] : 'utf8'; + var data = encoding == 'utf8' ? unescape(match[4]) : match[4]; + + var buffer = new Buffer(data, encoding); + buffer.charset = charset; + + return buffer.toString(); +} + +function fetchMapFile(self, sourceUrl, context, done) { + fetch(self, sourceUrl, function (data) { + self.trackLoaded(context.files[context.files.length - 1] || undefined, sourceUrl, data); + done(); + }, function (message) { + context.errors.push('Broken source map at "' + sourceUrl + '" - ' + message); + return done(); + }); +} + +function fetch(self, path, onSuccess, onFailure) { + var protocol = path.indexOf('https') === 0 ? https : http; + var requestOptions = override(url.parse(path), self.requestOptions); + var errorHandled = false; + + protocol + .get(requestOptions, function (res) { + if (res.statusCode < 200 || res.statusCode > 299) + return onFailure(res.statusCode); + + var chunks = []; + res.on('data', function (chunk) { + chunks.push(chunk.toString()); + }); + res.on('end', function () { + onSuccess(chunks.join('')); + }); + }) + .on('error', function (res) { + if (errorHandled) + return; + + onFailure(res.message); + errorHandled = true; + }) + .on('timeout', function () { + if (errorHandled) + return; + + onFailure('timeout'); + errorHandled = true; + }) + .setTimeout(self.timeout); +} + +function originalPositionIn(trackedSource, line, column, token, allowNFallbacks) { + var originalPosition; + var maxRange = token.length; + var position = { + line: line, + column: column + maxRange + }; + + while (maxRange-- > 0) { + position.column--; + originalPosition = trackedSource.data.originalPositionFor(position); + + if (originalPosition) + break; + } + + if (originalPosition.line === null && line > 1 && allowNFallbacks > 0) + return originalPositionIn(trackedSource, line - 1, column, token, allowNFallbacks - 1); + + if (trackedSource.path && originalPosition.source) { + originalPosition.source = REMOTE_RESOURCE.test(trackedSource.path) ? + url.resolve(trackedSource.path, originalPosition.source) : + path.join(trackedSource.path, originalPosition.source); + + originalPosition.sourceResolved = true; + } + + return originalPosition; +} + +function trackContentSources(self, sourceFile) { + var consumer = self.maps[sourceFile].data; + var isRemote = REMOTE_RESOURCE.test(sourceFile); + var sourcesMapping = {}; + + consumer.sources.forEach(function (file, index) { + var uniquePath = isRemote ? + url.resolve(path.dirname(sourceFile), file) : + path.relative(self.relativeTo, path.resolve(path.dirname(sourceFile), file)); + + sourcesMapping[uniquePath] = consumer.sourcesContent && consumer.sourcesContent[index]; + }); + self.sourcesContent[sourceFile] = sourcesMapping; +} + +function _resolveSources(self, remaining, whenDone) { + function processNext() { + return _resolveSources(self, remaining, whenDone); + } + + if (remaining.length === 0) + return whenDone(); + + var current = remaining.shift(); + var sourceFile = current[0]; + var originalFile = current[1]; + var isRemote = REMOTE_RESOURCE.test(sourceFile); + + if (isRemote && self.localOnly) { + self.warnings.push('No callback given to `#minify` method, cannot fetch a remote file from "' + originalFile + '"'); + return processNext(); + } + + if (isRemote) { + fetch(self, originalFile, function (data) { + self.sourcesContent[sourceFile][originalFile] = data; + processNext(); + }, function (message) { + self.warnings.push('Broken original source file at "' + originalFile + '" - ' + message); + processNext(); + }); + } else { + var fullPath = path.join(self.options.root, originalFile); + if (fs.existsSync(fullPath)) + self.sourcesContent[sourceFile][originalFile] = fs.readFileSync(fullPath, 'utf-8'); + else + self.warnings.push('Missing original source file at "' + fullPath + '".'); + return processNext(); + } +} + +InputSourceMapStore.prototype.track = function (data, whenDone) { + return typeof this.options.sourceMap == 'string' ? + fromString(this, data, whenDone) : + fromSource(this, data, whenDone, { files: [], cursor: 0, errors: this.errors }); +}; + +InputSourceMapStore.prototype.trackLoaded = function (sourcePath, mapPath, mapData) { + var relativeTo = this.options.explicitTarget ? this.options.target : this.options.root; + var isRemote = REMOTE_RESOURCE.test(sourcePath); + + if (mapPath) { + mapPath = isRemote ? + path.dirname(mapPath) : + path.dirname(path.relative(relativeTo, mapPath)); + } + + this.maps[sourcePath] = { + path: mapPath, + data: new SourceMapConsumer(mapData) + }; + + trackContentSources(this, sourcePath); +}; + +InputSourceMapStore.prototype.isTracking = function (source) { + return !!this.maps[source]; +}; + +InputSourceMapStore.prototype.originalPositionFor = function (sourceInfo, token, allowNFallbacks) { + return originalPositionIn(this.maps[sourceInfo.source], sourceInfo.line, sourceInfo.column, token, allowNFallbacks); +}; + +InputSourceMapStore.prototype.sourcesContentFor = function (contextSource) { + return this.sourcesContent[contextSource]; +}; + +InputSourceMapStore.prototype.resolveSources = function (whenDone) { + var toResolve = []; + + for (var sourceFile in this.sourcesContent) { + var contents = this.sourcesContent[sourceFile]; + for (var originalFile in contents) { + if (!contents[originalFile]) + toResolve.push([sourceFile, originalFile]); + } + } + + return _resolveSources(this, toResolve, whenDone); +}; + +module.exports = InputSourceMapStore; + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"../utils/object.js":62,"_process":78,"buffer":5,"fs":4,"http":122,"https":69,"path":76,"source-map":110,"url":140}],62:[function(require,module,exports){ +module.exports = { + override: function (source1, source2) { + var target = {}; + for (var key1 in source1) + target[key1] = source1[key1]; + for (var key2 in source2) + target[key2] = source2[key2]; + + return target; + } +}; + +},{}],63:[function(require,module,exports){ +function QuoteScanner(data) { + this.data = data; +} + +var findQuoteEnd = function (data, matched, cursor, oldCursor) { + var commentStartMark = '/*'; + var commentEndMark = '*/'; + var escapeMark = '\\'; + var blockEndMark = '}'; + var dataPrefix = data.substring(oldCursor, cursor); + var commentEndedAt = dataPrefix.lastIndexOf(commentEndMark, cursor); + var commentStartedAt = dataPrefix.lastIndexOf(commentStartMark, cursor); + var commentStarted = false; + + if (commentEndedAt >= cursor && commentStartedAt > -1) + commentStarted = true; + if (commentStartedAt < cursor && commentStartedAt > commentEndedAt) + commentStarted = true; + + if (commentStarted) { + var commentEndsAt = data.indexOf(commentEndMark, cursor); + if (commentEndsAt > -1) + return commentEndsAt; + + commentEndsAt = data.indexOf(blockEndMark, cursor); + return commentEndsAt > -1 ? commentEndsAt - 1 : data.length; + } + + while (true) { + if (data[cursor] === undefined) + break; + if (data[cursor] == matched && (data[cursor - 1] != escapeMark || data[cursor - 2] == escapeMark)) + break; + + cursor++; + } + + return cursor; +}; + +function findNext(data, mark, startAt) { + var escapeMark = '\\'; + var candidate = startAt; + + while (true) { + candidate = data.indexOf(mark, candidate + 1); + if (candidate == -1) + return -1; + if (data[candidate - 1] != escapeMark) + return candidate; + } +} + +QuoteScanner.prototype.each = function (callback) { + var data = this.data; + var tempData = []; + var nextStart = 0; + var nextEnd = 0; + var cursor = 0; + var matchedMark = null; + var singleMark = '\''; + var doubleMark = '"'; + var dataLength = data.length; + + for (; nextEnd < data.length;) { + var nextStartSingle = findNext(data, singleMark, nextEnd); + var nextStartDouble = findNext(data, doubleMark, nextEnd); + + if (nextStartSingle == -1) + nextStartSingle = dataLength; + if (nextStartDouble == -1) + nextStartDouble = dataLength; + + if (nextStartSingle < nextStartDouble) { + nextStart = nextStartSingle; + matchedMark = singleMark; + } else { + nextStart = nextStartDouble; + matchedMark = doubleMark; + } + + if (nextStart == -1) + break; + + nextEnd = findQuoteEnd(data, matchedMark, nextStart + 1, cursor); + if (nextEnd == -1) + break; + + var text = data.substring(nextStart, nextEnd + 1); + tempData.push(data.substring(cursor, nextStart)); + if (text.length > 0) + callback(text, tempData, nextStart); + + cursor = nextEnd + 1; + } + + return tempData.length > 0 ? + tempData.join('') + data.substring(cursor, data.length) : + data; +}; + +module.exports = QuoteScanner; + +},{}],64:[function(require,module,exports){ +(function (Buffer){ +var path = require('path'); +var rewriteUrls = require('../urls/rewrite'); + +var REMOTE_RESOURCE = /^(https?:)?\/\//; + +function SourceReader(context, data) { + this.outerContext = context; + this.data = data; + this.sources = {}; +} + +SourceReader.prototype.sourceAt = function (path) { + return this.sources[path]; +}; + +SourceReader.prototype.trackSource = function (path, source) { + this.sources[path] = {}; + this.sources[path][path] = source; +}; + +SourceReader.prototype.toString = function () { + if (typeof this.data == 'string') + return fromString(this); + if (Buffer.isBuffer(this.data)) + return fromBuffer(this); + if (Array.isArray(this.data)) + return fromArray(this); + + return fromHash(this); +}; + +function fromString(self) { + var data = self.data; + self.trackSource(undefined, data); + return data; +} + +function fromBuffer(self) { + var data = self.data.toString(); + self.trackSource(undefined, data); + return data; +} + +function fromArray(self) { + return self.data + .map(function (source) { + return self.outerContext.options.processImport === false ? + source + '@shallow' : + source; + }) + .map(function (source) { + return !self.outerContext.options.relativeTo || /^https?:\/\//.test(source) ? + source : + path.relative(self.outerContext.options.relativeTo, source); + }) + .map(function (source) { return '@import url(' + source + ');'; }) + .join(''); +} + +function fromHash(self) { + var data = []; + var toBase = path.resolve(self.outerContext.options.target || self.outerContext.options.root); + + for (var source in self.data) { + var styles = self.data[source].styles; + var inputSourceMap = self.data[source].sourceMap; + var isRemote = REMOTE_RESOURCE.test(source); + var absoluteSource = isRemote ? source : path.resolve(source); + var absoluteSourcePath = path.dirname(absoluteSource); + + var rewriteOptions = { + absolute: self.outerContext.options.explicitRoot, + relative: !self.outerContext.options.explicitRoot, + imports: true, + rebase: self.outerContext.options.rebase, + fromBase: absoluteSourcePath, + toBase: isRemote ? absoluteSourcePath : toBase, + urlQuotes: self.outerContext.options.compatibility.properties.urlQuotes + }; + styles = rewriteUrls(styles, rewriteOptions, self.outerContext); + + self.trackSource(source, styles); + + styles = self.outerContext.sourceTracker.store(source, styles); + + // here we assume source map lies in the same directory as `source` does + if (self.outerContext.options.sourceMap && inputSourceMap) + self.outerContext.inputSourceMapTracker.trackLoaded(source, source, inputSourceMap); + + data.push(styles); + } + + return data.join(''); +} + +module.exports = SourceReader; + +}).call(this,{"isBuffer":require("../../../is-buffer/index.js")}) +},{"../../../is-buffer/index.js":72,"../urls/rewrite":58,"path":76}],65:[function(require,module,exports){ +function SourceTracker() { + this.sources = []; +} + +SourceTracker.prototype.store = function (filename, data) { + this.sources.push(filename); + + return '__ESCAPED_SOURCE_CLEAN_CSS' + (this.sources.length - 1) + '__' + + data + + '__ESCAPED_SOURCE_END_CLEAN_CSS__'; +}; + +SourceTracker.prototype.nextStart = function (data) { + var next = /__ESCAPED_SOURCE_CLEAN_CSS(\d+)__/.exec(data); + + return next ? + { index: next.index, filename: this.sources[~~next[1]] } : + null; +}; + +SourceTracker.prototype.nextEnd = function (data) { + return /__ESCAPED_SOURCE_END_CLEAN_CSS__/g.exec(data); +}; + +SourceTracker.prototype.removeAll = function (data) { + return data + .replace(/__ESCAPED_SOURCE_CLEAN_CSS\d+__/g, '') + .replace(/__ESCAPED_SOURCE_END_CLEAN_CSS__/g, ''); +}; + +module.exports = SourceTracker; + +},{}],66:[function(require,module,exports){ +function split(value, separator, includeSeparator, openLevel, closeLevel) { + var withRegex = typeof separator != 'string'; + var hasSeparator = withRegex ? + separator.test(value) : + value.indexOf(separator); + + if (!hasSeparator) + return [value]; + + openLevel = openLevel || '('; + closeLevel = closeLevel || ')'; + + if (value.indexOf(openLevel) == -1 && !includeSeparator) + return value.split(separator); + + var level = 0; + var cursor = 0; + var lastStart = 0; + var len = value.length; + var tokens = []; + + while (cursor < len) { + if (value[cursor] == openLevel) { + level++; + } else if (value[cursor] == closeLevel) { + level--; + } + + if (level === 0 && cursor > 0 && cursor + 1 < len && (withRegex ? separator.test(value[cursor]) : value[cursor] == separator)) { + tokens.push(value.substring(lastStart, cursor + (includeSeparator ? 1 : 0))); + lastStart = cursor + 1; + } + + cursor++; + } + + if (lastStart < cursor + 1) { + var lastValue = value.substring(lastStart); + var lastCharacter = lastValue[lastValue.length - 1]; + if (!includeSeparator && (withRegex ? separator.test(lastCharacter) : lastCharacter == separator)) + lastValue = lastValue.substring(0, lastValue.length - 1); + + tokens.push(lastValue); + } + + return tokens; +} + +module.exports = split; + +},{}],67:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":72}],68:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],69:[function(require,module,exports){ +var http = require('http'); + +var https = module.exports; + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key]; +}; + +https.request = function (params, cb) { + if (!params) params = {}; + params.scheme = 'https'; + params.protocol = 'https:'; + return http.request.call(this, params, cb); +} + +},{"http":122}],70:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],71:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],72:[function(require,module,exports){ +/** + * Determine if an object is Buffer + * + * Author: Feross Aboukhadijeh + * License: MIT + * + * `npm install is-buffer` + */ + +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) +} + +},{}],73:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],74:[function(require,module,exports){ +'use strict'; +var xmlChars = require('xml-char-classes'); + +function getRange(re) { + return re.source.slice(1, -1); +} + +// http://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-NCName +module.exports = new RegExp('^[' + getRange(xmlChars.letter) + '_][' + getRange(xmlChars.letter) + getRange(xmlChars.digit) + '\\.\\-_' + getRange(xmlChars.combiningChar) + getRange(xmlChars.extender) + ']*$'); + +},{"xml-char-classes":145}],75:[function(require,module,exports){ +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +},{}],76:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":78}],77:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn) { + var args = new Array(arguments.length - 1); + var i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + process.nextTick(function afterTick() { + fn.apply(null, args); + }); +} + +}).call(this,require('_process')) +},{"_process":78}],78:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = setTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + clearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + setTimeout(drainQueue, 0); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],79:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],80:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],81:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],82:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":80,"./encode":81}],83:[function(require,module,exports){ +module.exports = require("./lib/_stream_duplex.js") + +},{"./lib/_stream_duplex.js":84}],84:[function(require,module,exports){ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":86,"./_stream_writable":88,"core-util-is":67,"inherits":71,"process-nextick-args":77}],85:[function(require,module,exports){ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":87,"core-util-is":67,"inherits":71}],86:[function(require,module,exports){ +(function (process){ +'use strict'; + +module.exports = Readable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events'); + +/**/ +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = undefined; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +var Duplex; +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +var Duplex; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) return 0; + + if (state.objectMode) return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) return state.buffer[0].length;else return state.length; + } + + if (n <= 0) return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else { + return state.length; + } + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; + + if (typeof n !== 'number' || n > 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } + + if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (doRead && !state.reading) n = howMuchToRead(nOrig, state); + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) endReadable(this); + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + if (state.pipesCount === 1 && state.pipes[0] === dest && src.listenerCount('data') === 1 && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) dest.on('error', onerror);else if (isArray(dest._events.error)) dest._events.error.unshift(onerror);else dest._events.error = [onerror, dest._events.error]; + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } + + if (ev === 'readable' && !this._readableState.endEmitted) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) return null; + + if (length === 0) ret = null;else if (objectMode) ret = list.shift();else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) ret = list.join('');else if (list.length === 1) ret = list[0];else ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) ret = '';else ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) ret += buf.slice(0, cpy);else buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) list[0] = buf.slice(cpy);else list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process')) +},{"./_stream_duplex":84,"_process":78,"buffer":5,"core-util-is":67,"events":68,"inherits":71,"isarray":73,"process-nextick-args":77,"string_decoder/":126,"util":3}],87:[function(require,module,exports){ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":84,"core-util-is":67,"inherits":71}],88:[function(require,module,exports){ +(function (process){ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; + +util.inherits(Writable, Stream); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +var Duplex; +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // create the two objects needed to store the corked requests + // they are not a linked list, as no new elements are inserted in there + this.corkedRequestsFree = new CorkedRequest(this); + this.corkedRequestsFree.next = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +var Duplex; +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} +}).call(this,require('_process')) +},{"./_stream_duplex":84,"_process":78,"buffer":5,"core-util-is":67,"events":68,"inherits":71,"process-nextick-args":77,"util-deprecate":142}],89:[function(require,module,exports){ +module.exports = require("./lib/_stream_passthrough.js") + +},{"./lib/_stream_passthrough.js":85}],90:[function(require,module,exports){ +var Stream = (function (){ + try { + return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify + } catch(_){} +}()); +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream || exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":84,"./lib/_stream_passthrough.js":85,"./lib/_stream_readable.js":86,"./lib/_stream_transform.js":87,"./lib/_stream_writable.js":88}],91:[function(require,module,exports){ +module.exports = require("./lib/_stream_transform.js") + +},{"./lib/_stream_transform.js":87}],92:[function(require,module,exports){ +module.exports = require("./lib/_stream_writable.js") + +},{"./lib/_stream_writable.js":88}],93:[function(require,module,exports){ +"use strict"; + +module.exports = +{ + // Output + ABSOLUTE: "absolute", + PATH_RELATIVE: "pathRelative", + ROOT_RELATIVE: "rootRelative", + SHORTEST: "shortest" +}; + +},{}],94:[function(require,module,exports){ +"use strict"; + +var constants = require("./constants"); + + + +function formatAuth(urlObj, options) +{ + if (urlObj.auth && !options.removeAuth && (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE)) + { + return urlObj.auth + "@"; + } + + return ""; +} + + + +function formatHash(urlObj, options) +{ + return urlObj.hash ? urlObj.hash : ""; +} + + + +function formatHost(urlObj, options) +{ + if (urlObj.host.full && (urlObj.extra.relation.maximumAuth || options.output===constants.ABSOLUTE)) + { + return urlObj.host.full; + } + + return ""; +} + + + +function formatPath(urlObj, options) +{ + var str = ""; + + var absolutePath = urlObj.path.absolute.string; + var relativePath = urlObj.path.relative.string; + var resource = showResource(urlObj, options); + + if (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE || options.output===constants.ROOT_RELATIVE) + { + str = absolutePath; + } + else if (relativePath.length<=absolutePath.length && options.output===constants.SHORTEST || options.output===constants.PATH_RELATIVE) + { + str = relativePath; + + if (str === "") + { + var query = showQuery(urlObj,options) && !!getQuery(urlObj,options); + + if (urlObj.extra.relation.maximumPath && !resource) + { + str = "./"; + } + else if (urlObj.extra.relation.overridesQuery && !resource && !query) + { + str = "./"; + } + } + } + else + { + str = absolutePath; + } + + if ( str==="/" && !resource && options.removeRootTrailingSlash && (!urlObj.extra.relation.minimumPort || options.output===constants.ABSOLUTE) ) + { + str = ""; + } + + return str; +} + + + +function formatPort(urlObj, options) +{ + if (urlObj.port && !urlObj.extra.portIsDefault && urlObj.extra.relation.maximumHost) + { + return ":" + urlObj.port; + } + + return ""; +} + + + +function formatQuery(urlObj, options) +{ + return showQuery(urlObj,options) ? getQuery(urlObj, options) : ""; +} + + + +function formatResource(urlObj, options) +{ + return showResource(urlObj,options) ? urlObj.resource : ""; +} + + + +function formatScheme(urlObj, options) +{ + var str = ""; + + if (urlObj.extra.relation.maximumHost || options.output===constants.ABSOLUTE) + { + if (!urlObj.extra.relation.minimumScheme || !options.schemeRelative || options.output===constants.ABSOLUTE) + { + str += urlObj.scheme + "://"; + } + else + { + str += "//"; + } + } + + return str; +} + + + +function formatUrl(urlObj, options) +{ + var url = ""; + + url += formatScheme(urlObj, options); + url += formatAuth(urlObj, options); + url += formatHost(urlObj, options); + url += formatPort(urlObj, options); + url += formatPath(urlObj, options); + url += formatResource(urlObj, options); + url += formatQuery(urlObj, options); + url += formatHash(urlObj, options); + + return url; +} + + + +function getQuery(urlObj, options) +{ + var stripQuery = options.removeEmptyQueries && urlObj.extra.relation.minimumPort; + + return urlObj.query.string[ stripQuery ? "stripped" : "full" ]; +} + + + +function showQuery(urlObj, options) +{ + return !urlObj.extra.relation.minimumQuery || options.output===constants.ABSOLUTE || options.output===constants.ROOT_RELATIVE; +} + + + +function showResource(urlObj, options) +{ + var removeIndex = options.removeDirectoryIndexes && urlObj.extra.resourceIsIndex; + var removeMatchingResource = urlObj.extra.relation.minimumResource && options.output!==constants.ABSOLUTE && options.output!==constants.ROOT_RELATIVE; + + return !!urlObj.resource && !removeMatchingResource && !removeIndex; +} + + + +module.exports = formatUrl; + +},{"./constants":93}],95:[function(require,module,exports){ +"use strict"; + +var constants = require("./constants"); +var formatUrl = require("./format"); +var getOptions = require("./options"); +var objUtils = require("./util/object"); +var parseUrl = require("./parse"); +var relateUrl = require("./relate"); + + + +function RelateUrl(from, options) +{ + this.options = getOptions(options, + { + defaultPorts: {ftp:21, http:80, https:443}, + directoryIndexes: ["index.html"], + ignore_www: false, + output: RelateUrl.SHORTEST, + rejectedSchemes: ["data","javascript","mailto"], + removeAuth: false, + removeDirectoryIndexes: true, + removeEmptyQueries: false, + removeRootTrailingSlash: true, + schemeRelative: true, + site: undefined, + slashesDenoteHost: true + }); + + this.from = parseUrl.from(from, this.options, null); +} + + + +/* + Usage: instance=new RelateUrl(); instance.relate(); +*/ +RelateUrl.prototype.relate = function(from, to, options) +{ + // relate(to,options) + if ( objUtils.isPlainObject(to) ) + { + options = to; + to = from; + from = null; + } + // relate(to) + else if (!to) + { + to = from; + from = null; + } + + options = getOptions(options, this.options); + from = from || options.site; + from = parseUrl.from(from, options, this.from); + + if (!from || !from.href) + { + throw new Error("from value not defined."); + } + else if (from.extra.hrefInfo.minimumPathOnly) + { + throw new Error("from value supplied is not absolute: "+from.href); + } + + to = parseUrl.to(to, options); + + if (to.valid===false) return to.href; + + to = relateUrl(from, to, options); + to = formatUrl(to, options); + + return to; +} + + + +/* + Usage: RelateUrl.relate(); +*/ +RelateUrl.relate = function(from, to, options) +{ + return new RelateUrl().relate(from, to, options); +} + + + +// Make constants accessible from API +objUtils.shallowMerge(RelateUrl, constants); + + + +module.exports = RelateUrl; + +},{"./constants":93,"./format":94,"./options":96,"./parse":99,"./relate":106,"./util/object":108}],96:[function(require,module,exports){ +"use strict"; + +var objUtils = require("./util/object"); + + + +function getOptions(options, defaults) +{ + if ( objUtils.isPlainObject(options) ) + { + var newOptions = {}; + + for (var i in defaults) + { + if ( defaults.hasOwnProperty(i) ) + { + if (options[i] !== undefined) + { + newOptions[i] = mergeOption(options[i], defaults[i]); + } + else + { + newOptions[i] = defaults[i]; + } + } + } + + return newOptions; + } + else + { + return defaults; + } +} + + + +function mergeOption(newValues, defaultValues) +{ + if (defaultValues instanceof Object && newValues instanceof Object) + { + if (defaultValues instanceof Array && newValues instanceof Array) + { + return defaultValues.concat(newValues); + } + else + { + return objUtils.shallowMerge(newValues, defaultValues); + } + } + + return newValues; +} + + + +module.exports = getOptions; + +},{"./util/object":108}],97:[function(require,module,exports){ +"use strict"; + +function parseHost(urlObj, options) +{ + // TWEAK :: condition only for speed optimization + if (options.ignore_www) + { + var host = urlObj.host.full; + + if (host) + { + var stripped = host; + + if (host.indexOf("www.") === 0) + { + stripped = host.substr(4); + } + + urlObj.host.stripped = stripped; + } + } +} + + + +module.exports = parseHost; + +},{}],98:[function(require,module,exports){ +"use strict"; + +function hrefInfo(urlObj) +{ + var minimumPathOnly = (!urlObj.scheme && !urlObj.auth && !urlObj.host.full && !urlObj.port); + var minimumResourceOnly = (minimumPathOnly && !urlObj.path.absolute.string); + var minimumQueryOnly = (minimumResourceOnly && !urlObj.resource); + var minimumHashOnly = (minimumQueryOnly && !urlObj.query.string.full.length); + var empty = (minimumHashOnly && !urlObj.hash); + + urlObj.extra.hrefInfo.minimumPathOnly = minimumPathOnly; + urlObj.extra.hrefInfo.minimumResourceOnly = minimumResourceOnly; + urlObj.extra.hrefInfo.minimumQueryOnly = minimumQueryOnly; + urlObj.extra.hrefInfo.minimumHashOnly = minimumHashOnly; + urlObj.extra.hrefInfo.empty = empty; +} + + + +module.exports = hrefInfo; + +},{}],99:[function(require,module,exports){ +"use strict"; + +var hrefInfo = require("./hrefInfo"); +var parseHost = require("./host"); +var parsePath = require("./path"); +var parsePort = require("./port"); +var parseQuery = require("./query"); +var parseUrlString = require("./urlstring"); +var pathUtils = require("../util/path"); + + + +function parseFromUrl(url, options, fallback) +{ + if (url) + { + var urlObj = parseUrl(url, options); + + // Because the following occurs in the relate stage for "to" URLs, + // such had to be mostly duplicated here + + var pathArray = pathUtils.resolveDotSegments(urlObj.path.absolute.array); + + urlObj.path.absolute.array = pathArray; + urlObj.path.absolute.string = "/" + pathUtils.join(pathArray); + + return urlObj; + } + else + { + return fallback; + } +} + + + +function parseUrl(url, options) +{ + var urlObj = parseUrlString(url, options); + + if (urlObj.valid===false) return urlObj; + + parseHost(urlObj, options); + parsePort(urlObj, options); + parsePath(urlObj, options); + parseQuery(urlObj, options); + hrefInfo(urlObj); + + return urlObj; +} + + + +module.exports = +{ + from: parseFromUrl, + to: parseUrl +}; + +},{"../util/path":109,"./host":97,"./hrefInfo":98,"./path":100,"./port":101,"./query":102,"./urlstring":103}],100:[function(require,module,exports){ +"use strict"; + +function isDirectoryIndex(resource, options) +{ + var verdict = false; + + options.directoryIndexes.every( function(index) + { + if (index === resource) + { + verdict = true; + return false; + } + + return true; + }); + + return verdict; +} + + + +function parsePath(urlObj, options) +{ + var path = urlObj.path.absolute.string; + + if (path) + { + var lastSlash = path.lastIndexOf("/"); + + if (lastSlash > -1) + { + if (++lastSlash < path.length) + { + var resource = path.substr(lastSlash); + + if (resource!=="." && resource!=="..") + { + urlObj.resource = resource; + path = path.substr(0, lastSlash); + } + else + { + path += "/"; + } + } + + urlObj.path.absolute.string = path; + urlObj.path.absolute.array = splitPath(path); + } + else if (path==="." || path==="..") + { + // "..?var", "..#anchor", etc ... not "..index.html" + path += "/"; + + urlObj.path.absolute.string = path; + urlObj.path.absolute.array = splitPath(path); + } + else + { + // Resource-only + urlObj.resource = path; + urlObj.path.absolute.string = null; + } + + urlObj.extra.resourceIsIndex = isDirectoryIndex(urlObj.resource, options); + } + // Else: query/hash-only or empty +} + + + +function splitPath(path) +{ + // TWEAK :: condition only for speed optimization + if (path !== "/") + { + var cleaned = []; + + path.split("/").forEach( function(dir) + { + // Cleanup -- splitting "/dir/" becomes ["","dir",""] + if (dir !== "") + { + cleaned.push(dir); + } + }); + + return cleaned; + } + else + { + // Faster to skip the above block and just create an array + return []; + } +} + + + +module.exports = parsePath; + +},{}],101:[function(require,module,exports){ +"use strict"; + +function parsePort(urlObj, options) +{ + var defaultPort = -1; + + for (var i in options.defaultPorts) + { + if ( i===urlObj.scheme && options.defaultPorts.hasOwnProperty(i) ) + { + defaultPort = options.defaultPorts[i]; + break; + } + } + + if (defaultPort > -1) + { + // Force same type as urlObj.port + defaultPort = defaultPort.toString(); + + if (urlObj.port === null) + { + urlObj.port = defaultPort; + } + + urlObj.extra.portIsDefault = (urlObj.port === defaultPort); + } +} + + + +module.exports = parsePort; + +},{}],102:[function(require,module,exports){ +"use strict"; + +function parseQuery(urlObj, options) +{ + urlObj.query.string.full = stringify(urlObj.query.object, false); + + // TWEAK :: condition only for speed optimization + if (options.removeEmptyQueries) + { + urlObj.query.string.stripped = stringify(urlObj.query.object, true); + } +} + + + +function stringify(queryObj, removeEmptyQueries) +{ + var count = 0; + var str = ""; + + for (var i in queryObj) + { + if ( i!=="" && queryObj.hasOwnProperty(i) ) + { + var value = queryObj[i]; + + if (value !== "" || !removeEmptyQueries) + { + str += (++count===1) ? "?" : "&"; + + i = encodeURIComponent(i); + + if (value !== "") + { + str += i +"="+ encodeURIComponent(value).replace(/%20/g,"+"); + } + else + { + str += i; + } + } + } + } + + return str; +} + + + +module.exports = parseQuery; + +},{}],103:[function(require,module,exports){ +"use strict"; + +var _parseUrl = require("url").parse; + + + +/* + Customize the URL object that Node generates + because: + + * necessary data for later + * urlObj.host is useless + * urlObj.hostname is too long + * urlObj.path is useless + * urlObj.pathname is too long + * urlObj.protocol is inaccurate; should be called "scheme" + * urlObj.search is mostly useless +*/ +function clean(urlObj) +{ + var scheme = urlObj.protocol; + + if (scheme) + { + // Remove ":" suffix + if (scheme.indexOf(":") === scheme.length-1) + { + scheme = scheme.substr(0, scheme.length-1); + } + } + + urlObj.host = + { + // TODO :: unescape(encodeURIComponent(s)) ? ... http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html + full: urlObj.hostname, + stripped: null + }; + + urlObj.path = + { + absolute: + { + array: null, + string: urlObj.pathname + }, + relative: + { + array: null, + string: null + } + }; + + urlObj.query = + { + object: urlObj.query, + string: + { + full: null, + stripped: null + } + }; + + urlObj.extra = + { + hrefInfo: + { + minimumPathOnly: null, + minimumResourceOnly: null, + minimumQueryOnly: null, + minimumHashOnly: null, + empty: null, + + separatorOnlyQuery: urlObj.search==="?" + }, + portIsDefault: null, + relation: + { + maximumScheme: null, + maximumAuth: null, + maximumHost: null, + maximumPort: null, + maximumPath: null, + maximumResource: null, + maximumQuery: null, + maximumHash: null, + + minimumScheme: null, + minimumAuth: null, + minimumHost: null, + minimumPort: null, + minimumPath: null, + minimumResource: null, + minimumQuery: null, + minimumHash: null, + + overridesQuery: null + }, + resourceIsIndex: null, + slashes: urlObj.slashes + }; + + urlObj.resource = null; + urlObj.scheme = scheme; + delete urlObj.hostname; + delete urlObj.pathname; + delete urlObj.protocol; + delete urlObj.search; + delete urlObj.slashes; + + return urlObj; +} + + + +function validScheme(url, options) +{ + var valid = true; + + options.rejectedSchemes.every( function(rejectedScheme) + { + valid = !(url.indexOf(rejectedScheme+":") === 0); + + // Break loop + return valid; + }); + + return valid; +} + + + +function parseUrlString(url, options) +{ + if ( validScheme(url,options) ) + { + return clean( _parseUrl(url, true, options.slashesDenoteHost) ); + } + else + { + return {href:url, valid:false}; + } +} + + + +module.exports = parseUrlString; + +},{"url":140}],104:[function(require,module,exports){ +"use strict"; + +var findRelation = require("./findRelation"); +var objUtils = require("../util/object"); +var pathUtils = require("../util/path"); + + + +function absolutize(urlObj, siteUrlObj, options) +{ + findRelation.upToPath(urlObj, siteUrlObj, options); + + // Fill in relative URLs + if (urlObj.extra.relation.minimumScheme) urlObj.scheme = siteUrlObj.scheme; + if (urlObj.extra.relation.minimumAuth) urlObj.auth = siteUrlObj.auth; + if (urlObj.extra.relation.minimumHost) urlObj.host = objUtils.clone(siteUrlObj.host); + if (urlObj.extra.relation.minimumPort) copyPort(urlObj, siteUrlObj); + if (urlObj.extra.relation.minimumScheme) copyPath(urlObj, siteUrlObj); + + // Check remaining relativeness now that path has been copied and/or resolved + findRelation.pathOn(urlObj, siteUrlObj, options); + + // Fill in relative URLs + if (urlObj.extra.relation.minimumResource) copyResource(urlObj, siteUrlObj); + if (urlObj.extra.relation.minimumQuery) urlObj.query = objUtils.clone(siteUrlObj.query); + if (urlObj.extra.relation.minimumHash) urlObj.hash = siteUrlObj.hash; +} + + + +/* + Get an absolute path that's relative to site url. +*/ +function copyPath(urlObj, siteUrlObj) +{ + if (urlObj.extra.relation.maximumHost || !urlObj.extra.hrefInfo.minimumResourceOnly) + { + var pathArray = urlObj.path.absolute.array; + var pathString = "/"; + + // If not erroneous URL + if (pathArray) + { + // If is relative path + if (urlObj.extra.hrefInfo.minimumPathOnly && urlObj.path.absolute.string.indexOf("/")!==0) + { + // Append path to site path + pathArray = siteUrlObj.path.absolute.array.concat(pathArray); + } + + pathArray = pathUtils.resolveDotSegments(pathArray); + pathString += pathUtils.join(pathArray); + } + else + { + pathArray = []; + } + + urlObj.path.absolute.array = pathArray; + urlObj.path.absolute.string = pathString; + } + else + { + // Resource-, query- or hash-only or empty + urlObj.path = objUtils.clone(siteUrlObj.path); + } +} + + + +function copyPort(urlObj, siteUrlObj) +{ + urlObj.port = siteUrlObj.port; + + urlObj.extra.portIsDefault = siteUrlObj.extra.portIsDefault; +} + + + +function copyResource(urlObj, siteUrlObj) +{ + urlObj.resource = siteUrlObj.resource; + + urlObj.extra.resourceIsIndex = siteUrlObj.extra.resourceIsIndex; +} + + + +module.exports = absolutize; + +},{"../util/object":108,"../util/path":109,"./findRelation":105}],105:[function(require,module,exports){ +"use strict"; + +function findRelation_upToPath(urlObj, siteUrlObj, options) +{ + // Path- or root-relative URL + var pathOnly = urlObj.extra.hrefInfo.minimumPathOnly; + + // Matching scheme, scheme-relative or path-only + var minimumScheme = (urlObj.scheme===siteUrlObj.scheme || !urlObj.scheme); + + // Matching auth, ignoring auth or path-only + var minimumAuth = minimumScheme && (urlObj.auth===siteUrlObj.auth || options.removeAuth || pathOnly); + + // Matching host or path-only + var www = options.ignore_www ? "stripped" : "full"; + var minimumHost = minimumAuth && (urlObj.host[www]===siteUrlObj.host[www] || pathOnly); + + // Matching port or path-only + var minimumPort = minimumHost && (urlObj.port===siteUrlObj.port || pathOnly); + + urlObj.extra.relation.minimumScheme = minimumScheme; + urlObj.extra.relation.minimumAuth = minimumAuth; + urlObj.extra.relation.minimumHost = minimumHost; + urlObj.extra.relation.minimumPort = minimumPort; + + urlObj.extra.relation.maximumScheme = !minimumScheme || minimumScheme && !minimumAuth; + urlObj.extra.relation.maximumAuth = !minimumScheme || minimumScheme && !minimumHost; + urlObj.extra.relation.maximumHost = !minimumScheme || minimumScheme && !minimumPort; +} + + + +function findRelation_pathOn(urlObj, siteUrlObj, options) +{ + var queryOnly = urlObj.extra.hrefInfo.minimumQueryOnly; + var hashOnly = urlObj.extra.hrefInfo.minimumHashOnly; + var empty = urlObj.extra.hrefInfo.empty; // not required, but self-documenting + + // From upToPath() + var minimumPort = urlObj.extra.relation.minimumPort; + var minimumScheme = urlObj.extra.relation.minimumScheme; + + // Matching port and path + var minimumPath = minimumPort && urlObj.path.absolute.string===siteUrlObj.path.absolute.string; + + // Matching resource or query/hash-only or empty + var matchingResource = (urlObj.resource===siteUrlObj.resource || !urlObj.resource && siteUrlObj.extra.resourceIsIndex) || (options.removeDirectoryIndexes && urlObj.extra.resourceIsIndex && !siteUrlObj.resource); + var minimumResource = minimumPath && (matchingResource || queryOnly || hashOnly || empty); + + // Matching query or hash-only/empty + var query = options.removeEmptyQueries ? "stripped" : "full"; + var urlQuery = urlObj.query.string[query]; + var siteUrlQuery = siteUrlObj.query.string[query]; + var minimumQuery = (minimumResource && !!urlQuery && urlQuery===siteUrlQuery) || ((hashOnly || empty) && !urlObj.extra.hrefInfo.separatorOnlyQuery); + + var minimumHash = minimumQuery && urlObj.hash===siteUrlObj.hash; + + urlObj.extra.relation.minimumPath = minimumPath; + urlObj.extra.relation.minimumResource = minimumResource; + urlObj.extra.relation.minimumQuery = minimumQuery; + urlObj.extra.relation.minimumHash = minimumHash; + + urlObj.extra.relation.maximumPort = !minimumScheme || minimumScheme && !minimumPath; + urlObj.extra.relation.maximumPath = !minimumScheme || minimumScheme && !minimumResource; + urlObj.extra.relation.maximumResource = !minimumScheme || minimumScheme && !minimumQuery; + urlObj.extra.relation.maximumQuery = !minimumScheme || minimumScheme && !minimumHash; + urlObj.extra.relation.maximumHash = !minimumScheme || minimumScheme && !minimumHash; // there's nothing after hash, so it's the same as maximumQuery + + // Matching path and/or resource with existing but non-matching site query + urlObj.extra.relation.overridesQuery = minimumPath && urlObj.extra.relation.maximumResource && !minimumQuery && !!siteUrlQuery; +} + + + +module.exports = +{ + pathOn: findRelation_pathOn, + upToPath: findRelation_upToPath +}; + +},{}],106:[function(require,module,exports){ +"use strict"; + +var absolutize = require("./absolutize"); +var relativize = require("./relativize"); + + + +function relateUrl(siteUrlObj, urlObj, options) +{ + absolutize(urlObj, siteUrlObj, options); + relativize(urlObj, siteUrlObj, options); + + return urlObj; +} + + + +module.exports = relateUrl; + +},{"./absolutize":104,"./relativize":107}],107:[function(require,module,exports){ +"use strict"; + +var pathUtils = require("../util/path"); + + + +/* + Get a path relative to the site path. +*/ +function relatePath(absolutePath, siteAbsolutePath) +{ + var relativePath = []; + + // At this point, it's related to the host/port + var related = true; + var parentIndex = -1; + + // Find parents + siteAbsolutePath.forEach( function(siteAbsoluteDir, i) + { + if (related) + { + if (absolutePath[i] !== siteAbsoluteDir) + { + related = false; + } + else + { + parentIndex = i; + } + } + + if (!related) + { + // Up one level + relativePath.push(".."); + } + }); + + // Form path + absolutePath.forEach( function(dir, i) + { + if (i > parentIndex) + { + relativePath.push(dir); + } + }); + + return relativePath; +} + + + +function relativize(urlObj, siteUrlObj, options) +{ + if (urlObj.extra.relation.minimumScheme) + { + var pathArray = relatePath(urlObj.path.absolute.array, siteUrlObj.path.absolute.array); + + urlObj.path.relative.array = pathArray; + urlObj.path.relative.string = pathUtils.join(pathArray); + } +} + + + +module.exports = relativize; + +},{"../util/path":109}],108:[function(require,module,exports){ +"use strict"; + +/* + Deep-clone an object. +*/ +function clone(obj) +{ + if (obj instanceof Object) + { + var clonedObj = (obj instanceof Array) ? [] : {}; + + for (var i in obj) + { + if ( obj.hasOwnProperty(i) ) + { + clonedObj[i] = clone( obj[i] ); + } + } + + return clonedObj; + } + + return obj; +} + + + +/* + https://github.com/jonschlinkert/is-plain-object +*/ +function isPlainObject(obj) +{ + return !!obj && typeof obj==="object" && obj.constructor===Object; +} + + + +/* + Shallow-merge two objects. +*/ +function shallowMerge(target, source) +{ + if (target instanceof Object && source instanceof Object) + { + for (var i in source) + { + if ( source.hasOwnProperty(i) ) + { + target[i] = source[i]; + } + } + } + + return target; +} + + + +module.exports = +{ + clone: clone, + isPlainObject: isPlainObject, + shallowMerge: shallowMerge +}; + +},{}],109:[function(require,module,exports){ +"use strict"; + +function joinPath(pathArray) +{ + if (pathArray.length) + { + return pathArray.join("/") + "/"; + } + else + { + return ""; + } +} + + + +function resolveDotSegments(pathArray) +{ + var pathAbsolute = []; + + pathArray.forEach( function(dir) + { + if (dir !== "..") + { + if (dir !== ".") + { + pathAbsolute.push(dir); + } + } + else + { + // Remove parent + if (pathAbsolute.length) + { + pathAbsolute.splice(pathAbsolute.length-1, 1); + } + } + }); + + return pathAbsolute; +} + + + +module.exports = +{ + join: joinPath, + resolveDotSegments: resolveDotSegments +}; + +},{}],110:[function(require,module,exports){ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./source-map/source-node').SourceNode; + +},{"./source-map/source-map-consumer":117,"./source-map/source-map-generator":118,"./source-map/source-node":119}],111:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = {}; + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var isDuplicate = this.has(aStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[util.toSetString(aStr)] = idx; + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + return Object.prototype.hasOwnProperty.call(this._set, + util.toSetString(aStr)); + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (this.has(aStr)) { + return this._set[util.toSetString(aStr)]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + +}); + +},{"./util":120,"amdefine":1}],112:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64 = require('./base64'); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + +}); + +},{"./base64":113,"amdefine":1}],113:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + aNumber); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + +}); + +},{"amdefine":1}],114:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + +}); + +},{"amdefine":1}],115:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + var mapping; + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + +}); + +},{"./util":120,"amdefine":1}],116:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + +}); + +},{"amdefine":1}],117:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var util = require('./util'); + var binarySearch = require('./binary-search'); + var ArraySet = require('./array-set').ArraySet; + var base64VLQ = require('./base64-vlq'); + var quickSort = require('./quick-sort').quickSort; + + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + sources = sources.map(util.normalize); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names, true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * availible. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + }; + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[i]; + + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.column + + (section.generatedOffset.generatedLine === mapping.generatedLine) + ? section.generatedOffset.generatedColumn - 1 + : 0, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + }; + }; + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + +}); + +},{"./array-set":111,"./base64-vlq":112,"./binary-search":114,"./quick-sort":116,"./util":120,"amdefine":1}],118:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var base64VLQ = require('./base64-vlq'); + var util = require('./util'); + var ArraySet = require('./array-set').ArraySet; + var MappingList = require('./mapping-list').MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null && !this._sources.has(source)) { + this._sources.add(source); + } + + if (name != null && !this._names.has(name)) { + this._names.add(name); + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = {}; + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var mapping; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + result += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + result += ','; + } + } + + result += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + result += base64VLQ.encode(this._sources.indexOf(mapping.source) + - previousSource); + previousSource = this._sources.indexOf(mapping.source); + + // lines are stored 0-based in SourceMap spec version 3 + result += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + result += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + result += base64VLQ.encode(this._names.indexOf(mapping.name) + - previousName); + previousName = this._names.indexOf(mapping.name); + } + } + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, + key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + +}); + +},{"./array-set":111,"./base64-vlq":112,"./mapping-list":115,"./util":120,"amdefine":1}],119:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; + var util = require('./util'); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + var code = ""; + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + +}); + +},{"./source-map-generator":118,"./util":120,"amdefine":1}],120:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +if (typeof define !== 'function') { + var define = require('amdefine')(module, require); +} +define(function (require, exports, module) { + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consequtive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = (path.charAt(0) === '/'); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + return '$' + aStr; + } + exports.toSetString = toSetString; + + function fromSetString(aStr) { + return aStr.substr(1); + } + exports.fromSetString = fromSetString; + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + }; + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + }; + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + }; + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +}); + +},{"amdefine":1}],121:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":68,"inherits":71,"readable-stream/duplex.js":83,"readable-stream/passthrough.js":89,"readable-stream/readable.js":90,"readable-stream/transform.js":91,"readable-stream/writable.js":92}],122:[function(require,module,exports){ +(function (global){ +var ClientRequest = require('./lib/request') +var extend = require('xtend') +var statusCodes = require('builtin-status-codes') +var url = require('url') + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./lib/request":124,"builtin-status-codes":6,"url":140,"xtend":146}],123:[function(require,module,exports){ +(function (global){ +exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableByteStream) + +exports.blobConstructor = false +try { + new Blob([new ArrayBuffer(1)]) + exports.blobConstructor = true +} catch (e) {} + +var xhr = new global.XMLHttpRequest() +// If location.host is empty, e.g. if this page/worker was loaded +// from a Blob, then use example.com to avoid an error +xhr.open('GET', global.location.host ? '/' : 'https://example.com') + +function checkTypeSupport (type) { + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. +// Safari 7.1 appears to have fixed this bug. +var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' +var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) + +exports.arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer') +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && + checkTypeSupport('moz-chunked-arraybuffer') +exports.overrideMimeType = isFunction(xhr.overrideMimeType) +exports.vbArray = isFunction(global.VBArray) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],124:[function(require,module,exports){ +(function (process,global,Buffer){ +// var Base64 = require('Base64') +var capability = require('./capability') +var inherits = require('inherits') +var response = require('./response') +var stream = require('stream') +var toArrayBuffer = require('to-arraybuffer') + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary) { + if (capability.fetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (capability.vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary) + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var self = this + return self._headers[name.toLowerCase()].value +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + var headersObj = self._headers + var body + if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { + if (capability.blobConstructor) { + body = new global.Blob(self._body.map(function (buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }) + } else { + // get utf8 string + body = Buffer.concat(self._body).toString() + } + } + + if (self._mode === 'fetch') { + var headers = Object.keys(headersObj).map(function (name) { + return [headersObj[name].name, headersObj[name].value] + }) + + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headers, + body: body, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin' + }).then(function (response) { + self._fetchResponse = response + self._connect() + }, function (reason) { + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0] + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + Object.keys(headersObj).forEach(function (name) { + xhr.setRequestHeader(headersObj[name].name, headersObj[name].value) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress() +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { + var self = this + self._destroyed = true + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + // Currently, there isn't a way to truly abort a fetch. + // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setTimeout = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'user-agent', + 'via' +] + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"./capability":123,"./response":125,"_process":78,"buffer":5,"inherits":71,"stream":121,"to-arraybuffer":127}],125:[function(require,module,exports){ +(function (process,global,Buffer){ +var capability = require('./capability') +var inherits = require('inherits') +var stream = require('stream') + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.statusCode = response.status + self.statusMessage = response.statusText + // backwards compatible version of for ( of ): + // for (var ,_i,_it = [Symbol.iterator](); = (_i = _it.next()).value,!_i.done;) + for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) { + self.headers[header[0].toLowerCase()] = header[1] + self.rawHeaders.push(header[0], header[1]) + } + + // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + if (result.done) { + self.push(null) + return + } + self.push(new Buffer(result.value)) + read() + }) + } + read() + + } else { + self._xhr = xhr + self._pos = 0 + + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () {} + +IncomingMessage.prototype._onXHRProgress = function () { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global.VBArray(xhr.responseBody).toArray() + } catch (e) {} + if (response !== null) { + self.push(new Buffer(response)) + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText + } catch (e) { + self._mode = 'text:vbarray' + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = new Buffer(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE) + break + response = xhr.response + self.push(new Buffer(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null) + } +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"./capability":123,"_process":78,"buffer":5,"inherits":71,"stream":121}],126:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +},{"buffer":5}],127:[function(require,module,exports){ +var Buffer = require('buffer').Buffer + +module.exports = function (buf) { + // If the buffer is backed by a Uint8Array, a faster version will work + if (buf instanceof Uint8Array) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) + } + } + + if (Buffer.isBuffer(buf)) { + // This is the slow version that will work with any Buffer + // implementation (even in old browsers) + var arrayCopy = new Uint8Array(buf.length) + var len = buf.length + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i] + } + return arrayCopy.buffer + } else { + throw new Error('Argument must be a Buffer') + } +} + +},{"buffer":5}],128:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + var util = require('./util'); + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = {}; + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = util.toSetString(aStr); + var isDuplicate = this._set.hasOwnProperty(sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[sStr] = idx; + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + var sStr = util.toSetString(aStr); + return this._set.hasOwnProperty(sStr); + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + var sStr = util.toSetString(aStr); + if (this._set.hasOwnProperty(sStr)) { + return this._set[sStr]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; +} + +},{"./util":137}],129:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +{ + var base64 = require('./base64'); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; +} + +},{"./base64":130}],130:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; +} + +},{}],131:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; +} + +},{}],132:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + var util = require('./util'); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; +} + +},{"./util":137}],133:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; +} + +},{}],134:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + var util = require('./util'); + var binarySearch = require('./binary-search'); + var ArraySet = require('./array-set').ArraySet; + var base64VLQ = require('./base64-vlq'); + var quickSort = require('./quick-sort').quickSort; + + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + sources = sources + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names, true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; +} + +},{"./array-set":128,"./base64-vlq":129,"./binary-search":131,"./quick-sort":133,"./util":137}],135:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + var base64VLQ = require('./base64-vlq'); + var util = require('./util'); + var ArraySet = require('./array-set').ArraySet; + var MappingList = require('./mapping-list').MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null && !this._sources.has(source)) { + this._sources.add(source); + } + + if (name != null && !this._names.has(name)) { + this._names.add(name); + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = {}; + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + result += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + result += ','; + } + } + + result += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + result += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + result += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + result += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + result += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, + key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; +} + +},{"./array-set":128,"./base64-vlq":129,"./mapping-list":132,"./util":137}],136:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; + var util = require('./util'); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; +} + +},{"./source-map-generator":135,"./util":137}],137:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +{ + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consequtive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + return '$' + aStr; + } + exports.toSetString = toSetString; + + function fromSetString(aStr) { + return aStr.substr(1); + } + exports.fromSetString = fromSetString; + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; +} + +},{}],138:[function(require,module,exports){ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; + +},{"./lib/source-map-consumer":134,"./lib/source-map-generator":135,"./lib/source-node":136}],139:[function(require,module,exports){ +var sys = require("util"); +var MOZ_SourceMap = require("source-map"); +var UglifyJS = exports; +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function array_to_hash(a) { + var ret = Object.create(null); + for (var i = 0; i < a.length; ++i) + ret[a[i]] = true; + return ret; +}; + +function slice(a, start) { + return Array.prototype.slice.call(a, start || 0); +}; + +function characters(str) { + return str.split(""); +}; + +function member(name, array) { + for (var i = array.length; --i >= 0;) + if (array[i] == name) + return true; + return false; +}; + +function find_if(func, array) { + for (var i = 0, n = array.length; i < n; ++i) { + if (func(array[i])) + return array[i]; + } +}; + +function repeat_string(str, i) { + if (i <= 0) return ""; + if (i == 1) return str; + var d = repeat_string(str, i >> 1); + d += d; + if (i & 1) d += str; + return d; +}; + +function DefaultsError(msg, defs) { + Error.call(this, msg); + this.msg = msg; + this.defs = defs; +}; +DefaultsError.prototype = Object.create(Error.prototype); +DefaultsError.prototype.constructor = DefaultsError; + +DefaultsError.croak = function(msg, defs) { + throw new DefaultsError(msg, defs); +}; + +function defaults(args, defs, croak) { + if (args === true) + args = {}; + var ret = args || {}; + if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i)) + DefaultsError.croak("`" + i + "` is not a supported option", defs); + for (var i in defs) if (defs.hasOwnProperty(i)) { + ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i]; + } + return ret; +}; + +function merge(obj, ext) { + var count = 0; + for (var i in ext) if (ext.hasOwnProperty(i)) { + obj[i] = ext[i]; + count++; + } + return count; +}; + +function noop() {}; + +var MAP = (function(){ + function MAP(a, f, backwards) { + var ret = [], top = [], i; + function doit() { + var val = f(a[i], i); + var is_last = val instanceof Last; + if (is_last) val = val.v; + if (val instanceof AtTop) { + val = val.v; + if (val instanceof Splice) { + top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); + } else { + top.push(val); + } + } + else if (val !== skip) { + if (val instanceof Splice) { + ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); + } else { + ret.push(val); + } + } + return is_last; + }; + if (a instanceof Array) { + if (backwards) { + for (i = a.length; --i >= 0;) if (doit()) break; + ret.reverse(); + top.reverse(); + } else { + for (i = 0; i < a.length; ++i) if (doit()) break; + } + } + else { + for (i in a) if (a.hasOwnProperty(i)) if (doit()) break; + } + return top.concat(ret); + }; + MAP.at_top = function(val) { return new AtTop(val) }; + MAP.splice = function(val) { return new Splice(val) }; + MAP.last = function(val) { return new Last(val) }; + var skip = MAP.skip = {}; + function AtTop(val) { this.v = val }; + function Splice(val) { this.v = val }; + function Last(val) { this.v = val }; + return MAP; +})(); + +function push_uniq(array, el) { + if (array.indexOf(el) < 0) + array.push(el); +}; + +function string_template(text, props) { + return text.replace(/\{(.+?)\}/g, function(str, p){ + return props[p]; + }); +}; + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +}; + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + }; + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + }; + return _ms(array); +}; + +function set_difference(a, b) { + return a.filter(function(el){ + return b.indexOf(el) < 0; + }); +}; + +function set_intersection(a, b) { + return a.filter(function(el){ + return b.indexOf(el) >= 0; + }); +}; + +// this function is taken from Acorn [1], written by Marijn Haverbeke +// [1] https://github.com/marijnh/acorn +function makePredicate(words) { + if (!(words instanceof Array)) words = words.split(" "); + var f = "", cats = []; + out: for (var i = 0; i < words.length; ++i) { + for (var j = 0; j < cats.length; ++j) + if (cats[j][0].length == words[i].length) { + cats[j].push(words[i]); + continue out; + } + cats.push([words[i]]); + } + function compareTo(arr) { + if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; + f += "switch(str){"; + for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; + f += "return true}return false;"; + } + // When there are more than three length categories, an outer + // switch first dispatches on the lengths, to save on comparisons. + if (cats.length > 3) { + cats.sort(function(a, b) {return b.length - a.length;}); + f += "switch(str.length){"; + for (var i = 0; i < cats.length; ++i) { + var cat = cats[i]; + f += "case " + cat[0].length + ":"; + compareTo(cat); + } + f += "}"; + // Otherwise, simply generate a flat `switch` statement. + } else { + compareTo(words); + } + return new Function("str", f); +}; + +function all(array, predicate) { + for (var i = array.length; --i >= 0;) + if (!predicate(array[i])) + return false; + return true; +}; + +function Dictionary() { + this._values = Object.create(null); + this._size = 0; +}; +Dictionary.prototype = { + set: function(key, val) { + if (!this.has(key)) ++this._size; + this._values["$" + key] = val; + return this; + }, + add: function(key, val) { + if (this.has(key)) { + this.get(key).push(val); + } else { + this.set(key, [ val ]); + } + return this; + }, + get: function(key) { return this._values["$" + key] }, + del: function(key) { + if (this.has(key)) { + --this._size; + delete this._values["$" + key]; + } + return this; + }, + has: function(key) { return ("$" + key) in this._values }, + each: function(f) { + for (var i in this._values) + f(this._values[i], i.substr(1)); + }, + size: function() { + return this._size; + }, + map: function(f) { + var ret = []; + for (var i in this._values) + ret.push(f(this._values[i], i.substr(1))); + return ret; + }, + toObject: function() { return this._values } +}; +Dictionary.fromObject = function(obj) { + var dict = new Dictionary(); + dict._size = merge(dict._values, obj); + return dict; +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function DEFNODE(type, props, methods, base) { + if (arguments.length < 4) base = AST_Node; + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + var code = "return function AST_" + type + "(props){ if (props) { "; + for (var i = props.length; --i >= 0;) { + code += "this." + props[i] + " = props." + props[i] + ";"; + } + var proto = base && new base; + if (proto && proto.initialize || (methods && methods.initialize)) + code += "this.initialize();"; + code += "}}"; + var ctor = new Function(code)(); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (i in methods) if (methods.hasOwnProperty(i)) { + if (/^\$/.test(i)) { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + exports["AST_" + type] = ctor; + return ctor; +}; + +var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", { +}, null); + +var AST_Node = DEFNODE("Node", "start end", { + clone: function() { + return new this.CTOR(this); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + } +}, null); + +AST_Node.warn_function = null; +AST_Node.warn = function(txt, props) { + if (AST_Node.warn_function) + AST_Node.warn_function(string_template(txt, props)); +}; + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value scope quote", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + scope: "[AST_Scope/S] The scope that this directive affects", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +function walk_body(node, visitor) { + if (node.body instanceof AST_Statement) { + node.body._walk(visitor); + } + else node.body.forEach(function(stat){ + stat._walk(visitor); + }); +}; + +var AST_Block = DEFNODE("Block", "body", { + $documentation: "A body of statements (usually bracketed)", + $propdoc: { + body: "[AST_Statement*] an array of statements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + }); + } +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)", + _walk: function(visitor) { + return visitor._visit(this); + } +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.label._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE("IterationStatement", null, { + $documentation: "Internal class. All loops inherit from it." +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + this.condition._walk(visitor); + }); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init name object", { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_IterationStatement); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + directives: "[string*/S] an array of directives declared in this scope", + variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + functions: "[Object/S] like `variables`, but only lists function declarations", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_enclose: function(arg_parameter_pairs) { + var self = this; + var args = []; + var parameters = []; + + arg_parameter_pairs.forEach(function(pair) { + var splitAt = pair.lastIndexOf(":"); + + args.push(pair.substr(0, splitAt)); + parameters.push(pair.substr(splitAt + 1)); + }); + + var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(self.body); + } + })); + return wrapped_tl; + }, + wrap_commonjs: function(name, export_all) { + var self = this; + var to_export = []; + if (export_all) { + self.figure_out_scope(); + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_SymbolDeclaration && node.definition().global) { + if (!find_if(function(n){ return n.name == node.name }, to_export)) + to_export.push(node); + } + })); + } + var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_Directive) { + switch (node.value) { + case "$ORIG": + return MAP.splice(self.body); + case "$EXPORTS": + var body = []; + to_export.forEach(function(sym){ + body.push(new AST_SimpleStatement({ + body: new AST_Assign({ + left: new AST_Sub({ + expression: new AST_SymbolRef({ name: "exports" }), + property: new AST_String({ value: sym.name }), + }), + operator: "=", + right: new AST_SymbolRef(sym), + }), + })); + }); + return MAP.splice(body); + } + } + })); + return wrapped_tl; + } +}, AST_Scope); + +var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg*] array of function arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.name) this.name._walk(visitor); + this.argnames.forEach(function(arg){ + arg._walk(visitor); + }); + walk_body(this, visitor); + }); + } +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits” (`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function(){ + this.value._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function(){ + this.label._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminant”" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + } +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.argname._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.definitions.forEach(function(def){ + def._walk(visitor); + }); + }); + } +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + } +}); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE("Call", "expression args", { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.args.forEach(function(arg){ + arg._walk(visitor); + }); + }); + } +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Seq = DEFNODE("Seq", "car cdr", { + $documentation: "A sequence expression (two comma-separated expressions)", + $propdoc: { + car: "[AST_Node] first element in sequence", + cdr: "[AST_Node] second element in sequence" + }, + $cons: function(x, y) { + var seq = new AST_Seq(x); + seq.car = x; + seq.cdr = y; + return seq; + }, + $from_array: function(array) { + if (array.length == 0) return null; + if (array.length == 1) return array[0].clone(); + var list = null; + for (var i = array.length; --i >= 0;) { + list = AST_Seq.cons(array[i], list); + } + var p = list; + while (p) { + if (p.cdr && !p.cdr.cdr) { + p.cdr = p.cdr.car; + break; + } + p = p.cdr; + } + return list; + }, + to_array: function() { + var p = this, a = []; + while (p) { + a.push(p.car); + if (p.cdr && !(p.cdr instanceof AST_Seq)) { + a.push(p.cdr); + break; + } + p = p.cdr; + } + return a; + }, + add: function(node) { + var p = this; + while (p) { + if (!(p.cdr instanceof AST_Seq)) { + var cell = AST_Seq.cons(p.cdr, node); + return p.cdr = cell; + } + p = p.cdr; + } + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.car._walk(visitor); + if (this.cdr) this.cdr._walk(visitor); + }); + } +}); + +var AST_PropAccess = DEFNODE("PropAccess", "expression property", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container” expression", + property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" + } +}); + +var AST_Dot = DEFNODE("Dot", null, { + $documentation: "A dotted property access expression", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.property._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "left operator right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.left._walk(visitor); + this.right._walk(visitor); + }); + } +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + } +}); + +var AST_Assign = DEFNODE("Assign", null, { + $documentation: "An assignment expression — `a = b + 5`", +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.elements.forEach(function(el){ + el._walk(visitor); + }); + }); + } +}); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.properties.forEach(function(prop){ + prop._walk(visitor); + }); + }); + } +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.", + value: "[AST_Node] property value. For setters and getters this is an AST_Function." + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.value._walk(visitor); + }); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { + $documentation: "An object setter property", +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { + $documentation: "An object getter property", +}, AST_ObjectProperty); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols", +}); + +var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { + $documentation: "The name of a property accessor (setter/getter function)" +}, AST_Symbol); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", + $propdoc: { + init: "[AST_Node*/S] array of initializers for this declaration." + } +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "A constant declaration" +}, AST_SymbolDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolDeclaration); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value literal", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + literal: "[string] numeric value as string (optional)" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp" + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: (function(){}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: (function(){}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ TreeWalker ]----- */ + +function TreeWalker(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); +}; +TreeWalker.prototype = { + _visit: function(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function(){ + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(node); + return ret; + }, + parent: function(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + }, + push: function (node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive) { + this.directives[node.value] = this.directives[node.value] ? "up" : true; + } + this.stack.push(node); + }, + pop: function(node) { + this.stack.pop(); + if (node instanceof AST_Lambda) { + this.directives = Object.getPrototypeOf(this.directives); + } + }, + self: function() { + return this.stack[this.stack.length - 1]; + }, + find_parent: function(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + }, + has_directive: function(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return true; + } + } + }, + in_boolean_context: function() { + var stack = this.stack; + var i = stack.length, self = stack[--i]; + while (i > 0) { + var p = stack[--i]; + if ((p instanceof AST_If && p.condition === self) || + (p instanceof AST_Conditional && p.condition === self) || + (p instanceof AST_DWLoop && p.condition === self) || + (p instanceof AST_For && p.condition === self) || + (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) + { + return true; + } + if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) + return false; + self = p; + } + }, + loopcontrol_target: function(label) { + var stack = this.stack; + if (label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == label.name) { + return x.body; + } + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_Switch || x instanceof AST_IterationStatement) + return x; + } + } +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with'; +var KEYWORDS_ATOM = 'false null true'; +var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield' + + " " + KEYWORDS_ATOM + " " + KEYWORDS; +var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case'; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); + +var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); + +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "||" +]); + +var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF")); + +var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +var REGEXP_MODIFIERS = makePredicate(characters("gmsiy")); + +/* -----[ Tokenizer ]----- */ + +// regexps adapted from http://xregexp.com/plugins/#unicode +var UNICODE = { + letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), + digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"), + non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), + space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), + connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]") +}; + +function is_letter(code) { + return (code >= 97 && code <= 122) + || (code >= 65 && code <= 90) + || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code))); +}; + +function is_digit(code) { + return code >= 48 && code <= 57; +}; + +function is_alphanumeric_char(code) { + return is_digit(code) || is_letter(code); +}; + +function is_unicode_digit(code) { + return UNICODE.digit.test(String.fromCharCode(code)); +} + +function is_unicode_combining_mark(ch) { + return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch); +}; + +function is_unicode_connector_punctuation(ch) { + return UNICODE.connector_punctuation.test(ch); +}; + +function is_identifier(name) { + return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name); +}; + +function is_identifier_start(code) { + return code == 36 || code == 95 || is_letter(code); +}; + +function is_identifier_char(ch) { + var code = ch.charCodeAt(0); + return is_identifier_start(code) + || is_digit(code) + || code == 8204 // \u200c: zero-width non-joiner + || code == 8205 // \u200d: zero-width joiner (in my ECMA-262 PDF, this is also 200c) + || is_unicode_combining_mark(ch) + || is_unicode_connector_punctuation(ch) + || is_unicode_digit(code) + ; +}; + +function is_identifier_string(str){ + return /^[a-z_$][a-z0-9_$]*$/i.test(str); +}; + +function parse_js_number(num) { + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else { + var val = parseFloat(num); + if (val == num) return val; + } +}; + +function JS_Parse_Error(message, filename, line, col, pos) { + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; + this.stack = new Error().stack; +}; + +JS_Parse_Error.prototype.toString = function() { + return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; +}; + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +}; + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +}; + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + comments_before : [] + }; + + function peek() { return S.text.charAt(S.pos); }; + + function next(signal_eof, in_string) { + var ch = S.text.charAt(S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if ("\r\n\u2028\u2029".indexOf(ch) >= 0) { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + if (!in_string && ch == "\r" && peek() == "\n") { + // treat a \r\n sequence as a single \n + ++S.pos; + ch = "\n"; + } + } else { + ++S.col; + } + return ch; + }; + + function forward(i) { + while (i-- > 0) next(); + }; + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + }; + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + }; + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + }; + + var prev_was_dot = false; + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) || + (type == "punc" && PUNC_BEFORE_EXPRESSION(value))); + prev_was_dot = (type == "punc" && value == "."); + var ret = { + type : type, + value : value, + line : S.tokline, + col : S.tokcol, + pos : S.tokpos, + endline : S.line, + endcol : S.col, + endpos : S.pos, + nlb : S.newline_before, + file : filename + }; + if (/^(?:num|string|regexp)$/i.test(type)) { + ret.raw = $TEXT.substring(ret.pos, ret.endpos); + } + if (!is_comment) { + ret.comments_before = S.comments_before; + S.comments_before = []; + // make note of any newlines in the comments that came before + for (var i = 0, len = ret.comments_before.length; i < len; i++) { + ret.nlb = ret.nlb || ret.comments_before[i].nlb; + } + } + S.newline_before = false; + return new AST_Token(ret); + }; + + function skip_whitespace() { + var ch; + while (WHITESPACE_CHARS(ch = peek()) || ch == "\u2028" || ch == "\u2029") + next(); + }; + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + }; + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + }; + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; + var num = read_while(function(ch, i){ + var code = ch.charCodeAt(0); + switch (code) { + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + return is_alphanumeric_char(code); + }); + if (prefix) num = prefix + num; + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + }; + + function read_escaped_char(in_string) { + var ch = next(true, in_string); + switch (ch.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 48 : return "\0"; + case 120 : return String.fromCharCode(hex_bytes(2)); // \x + case 117 : return String.fromCharCode(hex_bytes(4)); // \u + case 10 : return ""; // newline + case 13 : // \r + if (peek() == "\n") { // DOS newline + next(true, in_string); + return ""; + } + } + return ch; + }; + + function hex_bytes(n) { + var num = 0; + for (; n > 0; --n) { + var digit = parseInt(next(true), 16); + if (isNaN(digit)) + parse_error("Invalid hex-character pattern in string"); + num = (num << 4) | digit; + } + return num; + }; + + var read_string = with_eof_error("Unterminated string constant", function(quote_char){ + var quote = next(), ret = ""; + for (;;) { + var ch = next(true, true); + if (ch == "\\") { + // read OctalEscapeSequence (XXX: deprecated if "strict mode") + // https://github.com/mishoo/UglifyJS/issues/178 + var octal_len = 0, first = null; + ch = read_while(function(ch){ + if (ch >= "0" && ch <= "7") { + if (!first) { + first = ch; + return ++octal_len; + } + else if (first <= "3" && octal_len <= 2) return ++octal_len; + else if (first >= "4" && octal_len <= 1) return ++octal_len; + } + return false; + }); + if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8)); + else ch = read_escaped_char(true); + } + else if ("\r\n\u2028\u2029".indexOf(ch) >= 0) parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret += ch; + } + var tok = token("string", ret); + tok.quote = quote_char; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find("\n"), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token(); + }; + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){ + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i); + var a = text.split("\n"), n = a.length; + // update stream position + S.pos = i + 2; + S.line += n - 1; + if (n > 1) S.col = a[n - 1].length; + else S.col += a[n - 1].length; + S.col += 2; + var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0; + S.comments_before.push(token("comment2", text, true)); + S.regex_allowed = regex_allowed; + S.newline_before = nlb; + return next_token(); + }); + + function read_name() { + var backslash = false, name = "", ch, escaped = false, hex; + while ((ch = peek()) != null) { + if (!backslash) { + if (ch == "\\") escaped = backslash = true, next(); + else if (is_identifier_char(ch)) name += next(); + else break; + } + else { + if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); + ch = read_escaped_char(); + if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); + name += ch; + backslash = false; + } + } + if (KEYWORDS(name) && escaped) { + hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + }; + + var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){ + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (prev_backslash) { + regexp += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + regexp += ch; + } else if (ch == "]" && in_class) { + in_class = false; + regexp += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + regexp += ch; + } + var mods = read_name(); + try { + return token("regexp", new RegExp(regexp, mods)); + } catch(e) { + parse_error(e.message); + } + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS(bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + }; + return token("operator", grow(prefix || next())); + }; + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + }; + + function handle_dot() { + next(); + return is_digit(peek().charCodeAt(0)) + ? read_num(".") + : token("punc", "."); + }; + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM(word) ? token("atom", word) + : !KEYWORDS(word) ? token("name", word) + : OPERATORS(word) ? token("operator", word) + : token("keyword", word); + }; + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + }; + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("") && S.newline_before) { + forward(3); + return skip_line_comment("comment4"); + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(ch); + case 46: return handle_dot(); + case 47: return handle_slash(); + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS(ch)) return token("punc", next()); + if (OPERATOR_CHARS(ch)) return read_operator(); + if (code == 92 || is_identifier_start(code)) return read_word(); + + if (shebang) { + if (S.pos == 0 && looking_at("#!")) { + forward(2); + return skip_line_comment("comment5"); + } + } + parse_error("Unexpected character '" + ch + "'"); + }; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + return next_token; + +}; + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var PRECEDENCE = (function(a, ret){ + for (var i = 0; i < a.length; ++i) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ], + {} +); + +var STATEMENTS_WITH_LABELS = array_to_hash([ "fo" + "r", "do", "while", "switch" ]); + +var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + + options = defaults(options, { + strict : false, + filename : null, + toplevel : null, + expression : false, + html5_comments : true, + bare_returns : false, + shebang : true, + }); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + }; + + function peek() { return S.peeked || (S.peeked = S.input()); }; + + function next() { + S.prev = S.token; + if (S.peeked) { + S.token = S.peeked; + S.peeked = null; + } else { + S.token = S.input(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + }; + + function prev() { + return S.prev; + }; + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + }; + + function token_error(token, msg) { + croak(msg, token.line, token.col); + }; + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + }; + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + }; + + function expect(punc) { return expect_token("punc", punc); }; + + function can_insert_semicolon() { + return !options.strict && ( + S.token.nlb || is("eof") || is("punc", "}") + ); + }; + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + }; + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + }; + + function embed_tokens(parser) { + return function() { + var start = S.token; + var expr = parser(); + var end = prev(); + expr.start = start; + expr.end = end; + return expr; + }; + }; + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + }; + + var statement = embed_tokens(function() { + var tmp; + handle_regexp(); + switch (S.token.type) { + case "string": + var dir = S.in_directives, stat = simple_statement(); + // XXXv2: decide how to fix directives + if (dir && stat.body instanceof AST_String && !is("punc", ",")) { + return new AST_Directive({ + start : stat.body.start, + end : stat.body.end, + quote : stat.body.quote, + value : stat.body.value, + }); + } + return stat; + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (tmp = S.token.value, next(), tmp) { + case "break": + return break_cont(AST_Break); + + case "continue": + return break_cont(AST_Continue); + + case "debugger": + semicolon(); + return new AST_Debugger(); + + case "do": + return new AST_Do({ + body : in_loop(statement), + condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(true), tmp) + }); + + case "while": + return new AST_While({ + condition : parenthesised(), + body : in_loop(statement) + }); + + case "fo" + "r": + return for_(); + + case "function": + return function_(AST_Defun); + + case "if": + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + return new AST_Return({ + value: ( is("punc", ";") + ? (next(), null) + : can_insert_semicolon() + ? null + : (tmp = expression(true), semicolon(), tmp) ) + }); + + case "switch": + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + if (S.token.nlb) + croak("Illegal newline after 'throw'"); + return new AST_Throw({ + value: (tmp = expression(true), semicolon(), tmp) + }); + + case "try": + return try_(); + + case "var": + return tmp = var_(), semicolon(), tmp; + + case "const": + return tmp = const_(), semicolon(), tmp; + + case "with": + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + + default: + unexpected(); + } + } + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (find_if(function(l){ return l.name == label.name }, S.labels)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref){ + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + }; + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + }; + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = find_if(function(l){ return l.name == label.name }, S.labels); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } + else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + }; + + function for_() { + expect("("); + var init = null; + if (!is("punc", ";")) { + init = is("keyword", "var") + ? (next(), var_(true)) + : expression(true, true); + if (is("operator", "in")) { + if (init instanceof AST_Var && init.definitions.length > 1) + croak("Only one variable declaration allowed in for..in loop"); + next(); + return for_in(init); + } + } + return regular_for(init); + }; + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(statement) + }); + }; + + function for_in(init) { + var lhs = init instanceof AST_Var ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + name : lhs, + object : obj, + body : in_loop(statement) + }); + }; + + var function_ = function(ctor) { + var in_statement = ctor === AST_Defun; + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) + unexpected(); + expect("("); + return new ctor({ + name: name, + argnames: (function(first, a){ + while (!is("punc", ")")) { + if (first) first = false; else expect(","); + a.push(as_symbol(AST_SymbolFunarg)); + } + next(); + return a; + })(true, []), + body: (function(loop, labels){ + ++S.in_function; + S.in_directives = true; + S.in_loop = 0; + S.labels = []; + var a = block_(); + --S.in_function; + S.in_loop = loop; + S.labels = labels; + return a; + })(S.in_loop, S.labels) + }); + }; + + function if_() { + var cond = parenthesised(), body = statement(), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + }; + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + }; + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } + else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } + else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + }; + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + expect("("); + var name = as_symbol(AST_SymbolCatch); + expect(")"); + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + }; + + function vardefs(no_in, in_const) { + var a = []; + for (;;) { + a.push(new AST_VarDef({ + start : S.token, + name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), + value : is("operator", "=") ? (next(), expression(false, no_in)) : null, + end : prev() + })); + if (!is("punc", ",")) + break; + next(); + } + return a; + }; + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, false), + end : prev() + }); + }; + + var const_ = function() { + return new AST_Const({ + start : prev(), + definitions : vardefs(false, true), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")"); + } else { + args = []; + } + return subscripts(new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }), allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + case "keyword": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + break; + case "regexp": + ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + case "operator": + if (!is_identifier_string(tok.value)) { + throw new JS_Parse_Error("Invalid getter/setter name: " + tok.value, + tok.file, tok.line, tok.col, tok.pos); + } + ret = _make_symbol(AST_SymbolRef); + break; + } + next(); + return ret; + }; + + var expr_atom = function(allow_calls) { + if (is("operator", "new")) { + return new_(allow_calls); + } + var start = S.token; + if (is("punc")) { + switch (start.value) { + case "(": + next(); + var ex = expression(true); + ex.start = start; + ex.end = S.token; + expect(")"); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (ATOMIC_START_TOKEN[S.token.type]) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else { + a.push(expression(false)); + } + } + next(); + return a; + }; + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var object_ = embed_tokens(function() { + expect("{"); + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + var start = S.token; + var type = start.type; + var name = as_property_name(); + if (type == "name" && !is("punc", ":")) { + if (name == "get") { + a.push(new AST_ObjectGetter({ + start : start, + key : as_atom_node(), + value : function_(AST_Accessor), + end : prev() + })); + continue; + } + if (name == "set") { + a.push(new AST_ObjectSetter({ + start : start, + key : as_atom_node(), + value : function_(AST_Accessor), + end : prev() + })); + continue; + } + } + expect(":"); + a.push(new AST_ObjectKeyVal({ + start : start, + quote : start.quote, + key : name, + value : expression(false), + end : prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function as_property_name() { + var tmp = S.token; + next(); + switch (tmp.type) { + case "num": + case "string": + case "name": + case "operator": + case "keyword": + case "atom": + return tmp.value; + default: + unexpected(); + } + }; + + function as_name() { + var tmp = S.token; + next(); + switch (tmp.type) { + case "name": + case "operator": + case "keyword": + case "atom": + return tmp.value; + default: + unexpected(); + } + }; + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : type)({ + name : String(name), + start : S.token, + end : S.token + }); + }; + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + next(); + return sym; + }; + + var subscripts = function(expr, allow_calls) { + var start = expr.start; + if (is("punc", ".")) { + next(); + return subscripts(new AST_Dot({ + start : start, + expression : expr, + property : as_name(), + end : prev() + }), allow_calls); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + property : prop, + end : prev() + }), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + return subscripts(new AST_Call({ + start : start, + expression : expr, + args : expr_list(")"), + end : prev() + }), true); + } + return expr; + }; + + var maybe_unary = function(allow_calls) { + var start = S.token; + if (is("operator") && UNARY_PREFIX(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls); + while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { + val = make_unary(AST_UnaryPostfix, S.token.value, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, op, expr) { + if ((op == "++" || op == "--") && !is_assignable(expr)) + croak("Invalid use of " + op + " operator"); + return new ctor({ operator: op, expression: expr }); + }; + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && prec > min_prec) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true), 0, no_in); + }; + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + if (!options.strict) return true; + if (expr instanceof AST_This) return false; + return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol); + }; + + var maybe_assign = function(no_in) { + var start = S.token; + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && ASSIGNMENT(val)) { + if (is_assignable(left)) { + next(); + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var expr = maybe_assign(no_in); + if (commas && is("punc", ",")) { + next(); + return new AST_Seq({ + start : start, + car : expr, + cdr : expression(true, no_in), + end : peek() + }); + } + return expr; + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + }; + + if (options.expression) { + return expression(true); + } + + return (function(){ + var start = S.token; + var body = []; + while (!is("eof")) + body.push(statement()); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +// Tree transformer helpers. + +function TreeTransformer(before, after) { + TreeWalker.call(this); + this.before = before; + this.after = after; +} +TreeTransformer.prototype = new TreeWalker; + +(function(undefined){ + + function _(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list){ + var x, y; + tw.push(this); + if (tw.before) x = tw.before(this, descend, in_list); + if (x === undefined) { + if (!tw.after) { + x = this; + descend(x, tw); + } else { + tw.stack[tw.stack.length - 1] = x = this; + descend(x, tw); + y = tw.after(x, in_list); + if (y !== undefined) x = y; + } + } + tw.pop(this); + return x; + }); + }; + + function do_list(list, tw) { + return MAP(list, function(node){ + return node.transform(tw, true); + }); + }; + + _(AST_Node, noop); + + _(AST_LabeledStatement, function(self, tw){ + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_SimpleStatement, function(self, tw){ + self.body = self.body.transform(tw); + }); + + _(AST_Block, function(self, tw){ + self.body = do_list(self.body, tw); + }); + + _(AST_DWLoop, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_For, function(self, tw){ + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_ForIn, function(self, tw){ + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_With, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_Exit, function(self, tw){ + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_LoopControl, function(self, tw){ + if (self.label) self.label = self.label.transform(tw); + }); + + _(AST_If, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); + }); + + _(AST_Switch, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Case, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Try, function(self, tw){ + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); + }); + + _(AST_Catch, function(self, tw){ + self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Definitions, function(self, tw){ + self.definitions = do_list(self.definitions, tw); + }); + + _(AST_VarDef, function(self, tw){ + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_Lambda, function(self, tw){ + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Call, function(self, tw){ + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); + }); + + _(AST_Seq, function(self, tw){ + self.car = self.car.transform(tw); + self.cdr = self.cdr.transform(tw); + }); + + _(AST_Dot, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Sub, function(self, tw){ + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); + }); + + _(AST_Unary, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Binary, function(self, tw){ + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); + }); + + _(AST_Conditional, function(self, tw){ + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); + }); + + _(AST_Array, function(self, tw){ + self.elements = do_list(self.elements, tw); + }); + + _(AST_Object, function(self, tw){ + self.properties = do_list(self.properties, tw); + }); + + _(AST_ObjectProperty, function(self, tw){ + self.value = self.value.transform(tw); + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function SymbolDef(scope, index, orig) { + this.name = orig.name; + this.orig = [ orig ]; + this.scope = scope; + this.references = []; + this.global = false; + this.mangled_name = null; + this.undeclared = false; + this.constant = false; + this.index = index; +}; + +SymbolDef.prototype = { + unmangleable: function(options) { + if (!options) options = {}; + + return (this.global && !options.toplevel) + || this.undeclared + || (!options.eval && (this.scope.uses_eval || this.scope.uses_with)) + || (options.keep_fnames + && (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun)); + }, + mangle: function(options) { + var cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } + else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda) + s = s.parent_scope; + this.mangled_name = s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + } +}; + +AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){ + options = defaults(options, { + screw_ie8: false, + cache: null + }); + + // pass 1: setup scope chaining and handle definitions + var self = this; + var scope = self.parent_scope = null; + var labels = new Dictionary(); + var defun = null; + var last_var_had_const_pragma = false; + var nesting = 0; + var tw = new TreeWalker(function(node, descend){ + if (options.screw_ie8 && node instanceof AST_Catch) { + var save_scope = scope; + scope = new AST_Scope(node); + scope.init_scope_vars(nesting); + scope.parent_scope = save_scope; + descend(); + scope = save_scope; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(nesting); + var save_scope = node.parent_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Dictionary(); + ++nesting; descend(); --nesting; + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.del(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node); + } + else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + (node.scope = defun.parent_scope).def_function(node); + } + else if (node instanceof AST_Var) { + last_var_had_const_pragma = node.has_const_pragma(); + } + else if (node instanceof AST_SymbolVar + || node instanceof AST_SymbolConst) { + var def = defun.def_variable(node); + def.constant = node instanceof AST_SymbolConst || last_var_had_const_pragma; + def.init = tw.parent().value; + } + else if (node instanceof AST_SymbolCatch) { + (options.screw_ie8 ? scope : defun) + .def_variable(node); + } + else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + }); + self.walk(tw); + + // pass 2: find back references and eval + var func = null; + var globals = self.globals = new Dictionary(); + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Lambda) { + var prev_func = func; + func = node; + descend(); + func = prev_func; + return true; + } + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym = node.scope.find_variable(name); + if (!sym) { + var g; + if (globals.has(name)) { + g = globals.get(name); + } else { + g = new SymbolDef(self, globals.size(), node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + } + node.thedef = g; + if (func && name == "arguments") { + func.uses_arguments = true; + } + } else { + node.thedef = sym; + } + node.reference(); + return true; + } + }); + self.walk(tw); + + if (options.cache) { + this.cname = options.cache.cname; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){ + this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = null; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables + this.nesting = nesting; // the nesting level of this scope (0 means toplevel) +}); + +AST_Lambda.DEFMETHOD("init_scope_vars", function(){ + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + + var symbol = new AST_VarDef({ name: "arguments", start: this.start, end: this.end }); + var def = new SymbolDef(this, this.variables.size(), symbol); + this.variables.set(symbol.name, def); +}); + +AST_SymbolRef.DEFMETHOD("reference", function() { + var def = this.definition(); + def.references.push(this); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (s === def.scope) break; + s = s.parent_scope; + } + this.frame = this.scope.nesting - def.scope.nesting; +}); + +AST_Scope.DEFMETHOD("find_variable", function(name){ + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol){ + this.functions.set(symbol.name, this.def_variable(symbol)); +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol){ + var def; + if (!this.variables.has(symbol.name)) { + def = new SymbolDef(this, this.variables.size(), symbol); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } else { + def = this.variables.get(symbol.name); + def.orig.push(symbol); + } + return symbol.thedef = def; +}); + +AST_Scope.DEFMETHOD("next_mangled", function(options){ + var ext = this.enclosed; + out: while (true) { + var m = base54(++this.cname); + if (!is_identifier(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name excepted from mangling. + if (options.except.indexOf(m) >= 0) continue; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (var i = ext.length; --i >= 0;) { + var sym = ext[i]; + var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); + if (m == name) continue out; + } + return m; + } +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def){ + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + while (true) { + var name = AST_Lambda.prototype.next_mangled.call(this, options, def); + if (!(tricky_def && tricky_def.mangled_name == name)) + return name; + } +}); + +AST_Scope.DEFMETHOD("references", function(sym){ + if (sym instanceof AST_Symbol) sym = sym.definition(); + return this.enclosed.indexOf(sym) < 0 ? null : sym; +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options){ + return this.definition().unmangleable(options); +}); + +// property accessors are not mangleable +AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){ + return true; +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("unreferenced", function(){ + return this.definition().references.length == 0 + && !(this.scope.uses_eval || this.scope.uses_with); +}); + +AST_Symbol.DEFMETHOD("undeclared", function(){ + return this.definition().undeclared; +}); + +AST_LabelRef.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Label.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("definition", function(){ + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function(){ + return this.definition().global; +}); + +AST_Var.DEFMETHOD("has_const_pragma", function() { + var comments_before = this.start && this.start.comments_before; + var lastComment = comments_before && comments_before[comments_before.length - 1]; + return lastComment && /@const\b/.test(lastComment.value); +}); + +AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ + return defaults(options, { + except : [], + eval : false, + sort : false, + toplevel : false, + screw_ie8 : false, + keep_fnames : false + }); +}); + +AST_Toplevel.DEFMETHOD("mangle_names", function(options){ + options = this._default_mangler_options(options); + + // Never mangle arguments + options.except.push('arguments'); + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + if (options.cache) { + this.globals.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + to_mangle.push(symbol); + } + }); + } + + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_Scope) { + var p = tw.parent(), a = []; + node.variables.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + a.push(symbol); + } + }); + if (options.sort) a.sort(function(a, b){ + return b.references.length - a.references.length; + }); + to_mangle.push.apply(to_mangle, a); + return; + } + if (node instanceof AST_Label) { + var name; + do name = base54(++lname); while (!is_identifier(name)); + node.mangled_name = name; + return true; + } + if (options.screw_ie8 && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + this.walk(tw); + to_mangle.forEach(function(def){ def.mangle(options) }); + + if (options.cache) { + options.cache.cname = this.cname; + } +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ + options = this._default_mangler_options(options); + var tw = new TreeWalker(function(node){ + if (node instanceof AST_Constant) + base54.consider(node.print_to_string()); + else if (node instanceof AST_Return) + base54.consider("return"); + else if (node instanceof AST_Throw) + base54.consider("throw"); + else if (node instanceof AST_Continue) + base54.consider("continue"); + else if (node instanceof AST_Break) + base54.consider("break"); + else if (node instanceof AST_Debugger) + base54.consider("debugger"); + else if (node instanceof AST_Directive) + base54.consider(node.value); + else if (node instanceof AST_While) + base54.consider("while"); + else if (node instanceof AST_Do) + base54.consider("do while"); + else if (node instanceof AST_If) { + base54.consider("if"); + if (node.alternative) base54.consider("else"); + } + else if (node instanceof AST_Var) + base54.consider("var"); + else if (node instanceof AST_Const) + base54.consider("const"); + else if (node instanceof AST_Lambda) + base54.consider("function"); + else if (node instanceof AST_For) + base54.consider("fo" + "r"); + else if (node instanceof AST_ForIn) + base54.consider("for in"); + else if (node instanceof AST_Switch) + base54.consider("switch"); + else if (node instanceof AST_Case) + base54.consider("case"); + else if (node instanceof AST_Default) + base54.consider("default"); + else if (node instanceof AST_With) + base54.consider("with"); + else if (node instanceof AST_ObjectSetter) + base54.consider("set" + node.key); + else if (node instanceof AST_ObjectGetter) + base54.consider("get" + node.key); + else if (node instanceof AST_ObjectKeyVal) + base54.consider(node.key); + else if (node instanceof AST_New) + base54.consider("new"); + else if (node instanceof AST_This) + base54.consider("this"); + else if (node instanceof AST_Try) + base54.consider("try"); + else if (node instanceof AST_Catch) + base54.consider("catch"); + else if (node instanceof AST_Finally) + base54.consider("finally"); + else if (node instanceof AST_Symbol && node.unmangleable(options)) + base54.consider(node.name); + else if (node instanceof AST_Unary || node instanceof AST_Binary) + base54.consider(node.operator); + else if (node instanceof AST_Dot) + base54.consider(node.property); + }); + this.walk(tw); + base54.sort(); +}); + +var base54 = (function() { + var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; + var chars, frequency; + function reset() { + frequency = Object.create(null); + chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); + chars.forEach(function(ch){ frequency[ch] = 0 }); + } + base54.consider = function(str){ + for (var i = str.length; --i >= 0;) { + var code = str.charCodeAt(i); + if (code in frequency) ++frequency[code]; + } + }; + base54.sort = function() { + chars = mergeSort(chars, function(a, b){ + if (is_digit(a) && !is_digit(b)) return 1; + if (is_digit(b) && !is_digit(a)) return -1; + return frequency[b] - frequency[a]; + }); + }; + base54.reset = reset; + reset(); + base54.get = function(){ return chars }; + base54.freq = function(){ return frequency }; + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += String.fromCharCode(chars[num % base]); + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + }; + return base54; +})(); + +AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ + options = defaults(options, { + undeclared : false, // this makes a lot of noise + unreferenced : true, + assign_to_global : true, + func_arguments : true, + nested_defuns : true, + eval : true + }); + var tw = new TreeWalker(function(node){ + if (options.undeclared + && node instanceof AST_SymbolRef + && node.undeclared()) + { + // XXX: this also warns about JS standard names, + // i.e. Object, Array, parseInt etc. Should add a list of + // exceptions. + AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.assign_to_global) + { + var sym = null; + if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) + sym = node.left; + else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) + sym = node.init; + if (sym + && (sym.undeclared() + || (sym.global() && sym.scope !== sym.definition().scope))) { + AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { + msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", + name: sym.name, + file: sym.start.file, + line: sym.start.line, + col: sym.start.col + }); + } + } + if (options.eval + && node instanceof AST_SymbolRef + && node.undeclared() + && node.name == "eval") { + AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); + } + if (options.unreferenced + && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) + && !(node instanceof AST_SymbolCatch) + && node.unreferenced()) { + AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { + type: node instanceof AST_Label ? "Label" : "Symbol", + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.func_arguments + && node instanceof AST_Lambda + && node.uses_arguments) { + AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { + name: node.name ? node.name.name : "anonymous", + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.nested_defuns + && node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope)) { + AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { + name: node.name.name, + type: tw.parent().TYPE, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + }); + this.walk(tw); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function OutputStream(options) { + + options = defaults(options, { + indent_start : 0, + indent_level : 4, + quote_keys : false, + space_colon : true, + ascii_only : false, + unescape_regexps : false, + inline_script : false, + width : 80, + max_line_len : 32000, + beautify : false, + source_map : null, + bracketize : false, + semicolons : true, + comments : false, + shebang : true, + preserve_line : false, + screw_ie8 : false, + preamble : null, + quote_style : 0 + }, true); + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = ""; + + function to_ascii(str, identifier) { + return str.replace(/[\u0080-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, function(s){ + switch (s) { + case "\\": return "\\\\"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\0": return "\\x00"; + case "\ufeff": return "\\ufeff"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + if (options.ascii_only) str = to_ascii(str); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + }; + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + }; + + function make_name(name) { + name = name.toString(); + if (options.ascii_only) + name = to_ascii(name, true); + return name; + }; + + function make_indent(back) { + return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); + }; + + /* -----[ beautification/minification ]----- */ + + var might_need_space = false; + var might_need_semicolon = false; + var last = null; + + function last_char() { + return last.charAt(last.length - 1); + }; + + function maybe_newline() { + if (options.max_line_len && current_col > options.max_line_len) + print("\n"); + }; + + var requireSemicolonChars = makePredicate("( [ + * / - , ."); + + function print(str) { + str = String(str); + var ch = str.charAt(0); + if (might_need_semicolon) { + might_need_semicolon = false; + + if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) { + if (options.semicolons || requireSemicolonChars(ch)) { + OUTPUT += ";"; + current_col++; + current_pos++; + } else { + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { + var target_line = stack[stack.length - 1].start.line; + while (current_line < target_line) { + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + might_need_space = false; + } + } + + if (might_need_space) { + var prev = last_char(); + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (/^[\+\-\/]$/.test(ch) && ch == prev)) + { + OUTPUT += " "; + current_col++; + current_pos++; + } + might_need_space = false; + } + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + if (n == 0) { + current_col += a[n].length; + } else { + current_col = a[n].length; + } + current_pos += str.length; + last = str; + OUTPUT += str; + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont() }; + + var newline = options.beautify ? function() { + print("\n"); + } : maybe_newline; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + }; + + function next_indent() { + return indentation + options.indent_level; + }; + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function(){ + ret = cont(); + }); + indent(); + print("}"); + return ret; + }; + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + }; + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + }; + + function comma() { + print(","); + space(); + }; + + function colon() { + print(":"); + if (options.space_colon) space(); + }; + + var add_mapping = options.source_map ? function(token, name) { + try { + if (token) options.source_map.add( + token.file || "?", + current_line, current_col, + token.line, token.col, + (!name && token.type == "name") ? token.value : name + ); + } catch(ex) { + AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { + file: token.file, + line: token.line, + col: token.col, + cline: current_line, + ccol: current_col, + name: name || "" + }) + } + } : noop; + + function get() { + return OUTPUT; + }; + + if (options.preamble) { + print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + indentation : function() { return indentation }, + current_width : function() { return current_col - indentation }, + should_break : function() { return options.width && this.current_width() >= options.width }, + newline : newline, + print : print, + space : space, + comma : comma, + colon : colon, + last : function() { return last }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_ascii : to_ascii, + print_name : function(name) { print(make_name(name)) }, + print_string : function(str, quote) { print(encode_string(str, quote)) }, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt] }, + line : function() { return current_line }, + col : function() { return current_col }, + pos : function() { return current_pos }, + push_node : function(node) { stack.push(node) }, + pop_node : function() { return stack.pop() }, + stack : function() { return stack }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +}; + +/* -----[ code generators ]----- */ + +(function(){ + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + }; + + var use_asm = false; + + AST_Node.DEFMETHOD("print", function(stream, force_parens){ + var self = this, generator = self._codegen, prev_use_asm = use_asm; + if (self instanceof AST_Directive && self.value == "use asm") { + use_asm = true; + } + function doit() { + self.add_comments(stream); + self.add_source_map(stream); + generator(self, stream); + } + stream.push_node(self); + if (force_parens || self.needs_parens(stream)) { + stream.with_parens(doit); + } else { + doit(); + } + stream.pop_node(); + if (self instanceof AST_Lambda) { + use_asm = prev_use_asm; + } + }); + + AST_Node.DEFMETHOD("print_to_string", function(options){ + var s = OutputStream(options); + this.print(s); + return s.get(); + }); + + /* -----[ comments ]----- */ + + AST_Node.DEFMETHOD("add_comments", function(output){ + var c = output.option("comments"), self = this; + var start = self.start; + if (start && !start._comments_dumped) { + start._comments_dumped = true; + var comments = start.comments_before || []; + + // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 + // and https://github.com/mishoo/UglifyJS2/issues/372 + if (self instanceof AST_Exit && self.value) { + self.value.walk(new TreeWalker(function(node){ + if (node.start && node.start.comments_before) { + comments = comments.concat(node.start.comments_before); + node.start.comments_before = []; + } + if (node instanceof AST_Function || + node instanceof AST_Array || + node instanceof AST_Object) + { + return true; // don't go inside. + } + })); + } + + if (!c) { + comments = comments.filter(function(comment) { + return comment.type == "comment5"; + }); + } else if (c.test) { + comments = comments.filter(function(comment){ + return comment.type == "comment5" || c.test(comment.value); + }); + } else if (typeof c == "function") { + comments = comments.filter(function(comment){ + return comment.type == "comment5" || c(self, comment); + }); + } + + // Keep single line comments after nlb, after nlb + if (!output.option("beautify") && comments.length > 0 && + /comment[134]/.test(comments[0].type) && + output.col() !== 0 && comments[0].nlb) + { + output.print("\n"); + } + + comments.forEach(function(c){ + if (/comment[134]/.test(c.type)) { + output.print("//" + c.value + "\n"); + output.indent(); + } + else if (c.type == "comment2") { + output.print("/*" + c.value + "*/"); + if (start.nlb) { + output.print("\n"); + output.indent(); + } else { + output.space(); + } + } + else if (output.pos() === 0 && c.type == "comment5" && output.option("shebang")) { + output.print("#!" + c.value + "\n"); + output.indent(); + } + }); + } + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype){ + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + }; + + PARENS(AST_Node, function(){ + return false; + }); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output){ + return first_in_statement(output); + }); + + // same goes for an object literal, because otherwise it would be + // interpreted as a block of code. + PARENS(AST_Object, function(output){ + return first_in_statement(output); + }); + + PARENS([ AST_Unary, AST_Undefined ], function(output){ + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this; + }); + + PARENS(AST_Seq, function(output){ + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + ; + }); + + PARENS(AST_Binary, function(output){ + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + var po = p.operator, pp = PRECEDENCE[po]; + var so = this.operator, sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && this === p.right)) { + return true; + } + } + }); + + PARENS(AST_PropAccess, function(output){ + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + try { + this.walk(new TreeWalker(function(node){ + if (node instanceof AST_Call) throw p; + })); + } catch(ex) { + if (ex !== p) throw ex; + return true; + } + } + }); + + PARENS(AST_Call, function(output){ + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output){ + var p = output.parent(); + if (no_constructor_parens(this, output) + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output){ + var p = output.parent(); + if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + PARENS([ AST_Assign, AST_Conditional ], function (output){ + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output){ + output.print_string(self.value, self.quote); + output.semicolon(); + }); + DEFPRINT(AST_Debugger, function(self, output){ + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output) { + var last = body.length - 1; + body.forEach(function(stmt, i){ + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + }); + }; + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output){ + display_body(self.body, true, output); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output){ + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + function print_bracketed(body, output) { + if (body.length > 0) output.with_block(function(){ + display_body(body, false, output); + }); + else output.print("{}"); + }; + DEFPRINT(AST_BlockStatement, function(self, output){ + print_bracketed(self.body, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output){ + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output){ + output.print("do"); + output.space(); + self._do_print_body(output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output){ + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output){ + output.print("fo" + "r"); + output.space(); + output.with_parens(function(){ + if (self.init && !(self.init instanceof AST_EmptyStatement)) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output){ + output.print("fo" + "r"); + output.space(); + output.with_parens(function(){ + self.init.print(output); + output.space(); + output.print("in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output){ + output.print("with"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ + var self = this; + if (!nokeyword) { + output.print("function"); + } + if (self.name) { + output.space(); + self.name.print(output); + } + output.with_parens(function(){ + self.argnames.forEach(function(arg, i){ + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_bracketed(self.body, output); + }); + DEFPRINT(AST_Lambda, function(self, output){ + self._do_print(output); + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.value) { + output.space(); + this.value.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output){ + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output){ + self._do_print(output, "throw"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output){ + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output){ + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + if (output.option("bracketize")) { + make_block(self.body, output); + return; + } + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block brackets if needed. + if (!self.body) + return output.force_semicolon(); + if (self.body instanceof AST_Do + && !output.option("screw_ie8")) { + // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE + // croaks with "syntax error" on code like this: if (foo) + // do ... while(cond); else ... we need block brackets + // around do/while + make_block(self.body, output); + return; + } + var b = self.body; + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } + else if (b instanceof AST_StatementWithBody) { + b = b.body; + } + else break; + } + force_statement(self.body, output); + }; + DEFPRINT(AST_If, function(self, output){ + output.print("if"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output){ + output.print("switch"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + if (self.body.length > 0) output.with_block(function(){ + self.body.forEach(function(stmt, i){ + if (i) output.newline(); + output.indent(true); + stmt.print(output); + }); + }); + else output.print("{}"); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ + if (this.body.length > 0) { + output.newline(); + this.body.forEach(function(stmt){ + output.indent(); + stmt.print(output); + output.newline(); + }); + } + }); + DEFPRINT(AST_Default, function(self, output){ + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output){ + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output){ + output.print("try"); + output.space(); + print_bracketed(self.body, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output){ + output.print("catch"); + output.space(); + output.with_parens(function(){ + self.argname.print(output); + }); + output.space(); + print_bracketed(self.body, output); + }); + DEFPRINT(AST_Finally, function(self, output){ + output.print("finally"); + output.space(); + print_bracketed(self.body, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i){ + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var avoid_semicolon = in_for && p.init === this; + if (!avoid_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Var, function(self, output){ + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output){ + self._do_print(output, "const"); + }); + + function parenthesize_for_noin(node, output, noin) { + if (!noin) node.print(output); + else try { + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw output; + })); + node.print(output); + } catch(ex) { + if (ex !== output) throw ex; + node.print(output, true); + } + }; + + DEFPRINT(AST_VarDef, function(self, output){ + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output){ + self.expression.print(output); + if (self instanceof AST_New && no_constructor_parens(self, output)) + return; + output.with_parens(function(){ + self.args.forEach(function(expr, i){ + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output){ + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Seq.DEFMETHOD("_do_print", function(output){ + this.car.print(output); + if (this.cdr) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + this.cdr.print(output); + } + }); + DEFPRINT(AST_Seq, function(self, output){ + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output){ + var expr = self.expression; + expr.print(output); + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.]/i.test(output.last())) { + output.print("."); + } + } + output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(self.property); + }); + DEFPRINT(AST_Sub, function(self, output){ + self.expression.print(output); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output){ + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && self.expression instanceof AST_UnaryPrefix + && /^[+-]/.test(self.expression.operator))) { + output.space(); + } + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output){ + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output){ + var op = self.operator; + self.left.print(output); + if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ + && self.left instanceof AST_UnaryPostfix + && self.left.operator == "--") { + // space is mandatory to avoid outputting --> + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + if ((op == "<" || op == "<<") + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "!" + && self.right.expression instanceof AST_UnaryPrefix + && self.right.expression.operator == "--") { + // space is mandatory to avoid outputting x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // y?1:1 --> 1 + if (consequent.is_constant(compressor) + && alternative.is_constant(compressor) + && consequent.equivalent_to(alternative)) { + var consequent_value = consequent.constant_value(); + if (self.condition.has_side_effects(compressor)) { + return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent_value, self)]); + } else { + return make_node_from_constant(compressor, consequent_value, self); + } + } + + // y?true:false --> !!y + if (is_true(consequent) && is_false(alternative)) { + if (self.condition.is_boolean()) { + // boolean_expression ? true : false --> boolean_expression + return self.condition; + } + self.condition = self.condition.negate(compressor); + return make_node(AST_UnaryPrefix, self.condition, { + operator: "!", + expression: self.condition + }); + } + // y?false:true --> !y + if (is_false(consequent) && is_true(alternative)) { + return self.condition.negate(compressor) + } + return self; + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.value); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !!node.expression.value); + } + }); + + OPT(AST_Boolean, function(self, compressor){ + if (compressor.option("booleans")) { + var p = compressor.parent(); + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { + operator : p.operator, + value : self.value, + file : p.start.file, + line : p.start.line, + col : p.start.col, + }); + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; + }); + + OPT(AST_Sub, function(self, compressor){ + var prop = self.property; + if (prop instanceof AST_String && compressor.option("properties")) { + prop = prop.getValue(); + if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) { + return make_node(AST_Dot, self, { + expression : self.expression, + property : prop + }).optimize(compressor); + } + var v = parseFloat(prop); + if (!isNaN(v) && v.toString() == prop) { + self.property = make_node(AST_Number, self.property, { + value: v + }); + } + } + return self; + }); + + OPT(AST_Dot, function(self, compressor){ + var prop = self.property; + if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) { + return make_node(AST_Sub, self, { + expression : self.expression, + property : make_node(AST_String, self, { + value: prop + }) + }).optimize(compressor); + } + return self.evaluate(compressor)[0]; + }); + + function literals_in_boolean_context(self, compressor) { + if (compressor.option("booleans") && compressor.in_boolean_context() && !self.has_side_effects(compressor)) { + return make_node(AST_True, self); + } + return self; + }; + OPT(AST_Array, literals_in_boolean_context); + OPT(AST_Object, literals_in_boolean_context); + OPT(AST_RegExp, literals_in_boolean_context); + + OPT(AST_Return, function(self, compressor){ + if (self.value instanceof AST_Undefined) { + self.value = null; + } + return self; + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +// a small wrapper around fitzgen's source-map library +function SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + + orig_line_diff : 0, + dest_line_diff : 0, + }); + var generator = new MOZ_SourceMap.SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : { line: gen_line + options.dest_line_diff, column: gen_col }, + original : { line: orig_line + options.orig_line_diff, column: orig_col }, + source : source, + name : name + }); + }; + return { + add : add, + get : function() { return generator }, + toString : function() { return JSON.stringify(generator.toJSON()); } + }; +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +(function(){ + + var MOZ_TO_ME = { + ExpressionStatement: function(M) { + var expr = M.expression; + if (expr.type === "Literal" && typeof expr.value === "string") { + return new AST_Directive({ + start: my_start_token(M), + end: my_end_token(M), + value: expr.value + }); + } + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(expr) + }); + }, + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + Property: function(M) { + var key = M.key; + var name = key.type == "Identifier" ? key.name : key.value; + var args = { + start : my_start_token(key), + end : my_end_token(M.value), + key : name, + value : from_moz(M.value) + }; + switch (M.kind) { + case "init": + return new AST_ObjectKeyVal(args); + case "set": + args.value.name = from_moz(key); + return new AST_ObjectSetter(args); + case "get": + args.value.name = from_moz(key); + return new AST_ObjectGetter(args); + } + }, + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop){ + prop.type = "Property"; + return from_moz(prop) + }) + }); + }, + SequenceExpression: function(M) { + return AST_Seq.from_array(M.expressions.map(from_moz)); + }, + MemberExpression: function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object) + }); + }, + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + default: + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = new RegExp(rx.pattern, rx.flags).toString(); + } else { + // support legacy RegExp + args.value = M.regex && M.raw ? M.raw : val; + } + return new AST_RegExp(args); + } + }, + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + map("Program", AST_Toplevel, "body@body"); + map("EmptyStatement", AST_EmptyStatement); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("DebuggerStatement", AST_Debugger); + map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body"); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + map("CatchClause", AST_Catch, "param>argname, body%body"); + + map("ThisExpression", AST_This); + map("ArrayExpression", AST_Array, "elements@elements"); + map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body"); + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args"); + map("CallExpression", AST_Call, "callee>expression, arguments@args"); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value + } + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: M instanceof AST_Const ? "const" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.to_array().map(to_moz) + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property} + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + return { + type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression", + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) { + var key = ( + is_identifier(M.key) + ? {type: "Identifier", name: M.key} + : {type: "Literal", value: M.key} + ); + var kind; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + return { + type: "Property", + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M) { + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: value.toString(), + regex: { + pattern: value.source, + flags: value.toString().match(/[gimuy]*$/)[0] + } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) { + return { + type: "UnaryExpression", + operator: "-", + prefix: true, + argument: { + type: "Literal", + value: -value, + raw: M.start.raw + } + }; + } + return { + type: "Literal", + value: value, + raw: M.start.raw + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function raw_token(moznode) { + if (moznode.type == "Literal") { + return moznode.raw != null ? moznode.raw : moznode.value + ""; + } + } + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : start && start.line, + col : start && start.column, + pos : range ? range[0] : moznode.start, + endline : start && start.line, + endcol : start && start.column, + endpos : range ? range[0] : moznode.start, + raw : raw_token(moznode), + }); + }; + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : end && end.line, + col : end && end.column, + pos : range ? range[1] : moznode.end, + endline : end && end.line, + endcol : end && end.column, + endpos : range ? range[1] : moznode.end, + raw : raw_token(moznode), + }); + }; + + function map(moztype, mytype, propmap) { + var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; + moz_to_me += "return new U2." + mytype.name + "({\n" + + "start: my_start_token(M),\n" + + "end: my_end_token(M)"; + + var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; + me_to_moz += "return {\n" + + "type: " + JSON.stringify(moztype); + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ + var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = m[1], how = m[2], my = m[3]; + moz_to_me += ",\n" + my + ": "; + me_to_moz += ",\n" + moz + ": "; + switch (how) { + case "@": + moz_to_me += "M." + moz + ".map(from_moz)"; + me_to_moz += "M." + my + ".map(to_moz)"; + break; + case ">": + moz_to_me += "from_moz(M." + moz + ")"; + me_to_moz += "to_moz(M." + my + ")"; + break; + case "=": + moz_to_me += "M." + moz; + me_to_moz += "M." + my; + break; + case "%": + moz_to_me += "from_moz(M." + moz + ").body"; + me_to_moz += "to_moz_block(M)"; + break; + default: + throw new Error("Can't understand operator in propmap: " + prop); + } + }); + + moz_to_me += "\n})\n}"; + me_to_moz += "\n}\n}"; + + //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); + //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true }); + //console.log(moz_to_me); + + moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( + exports, my_start_token, my_end_token, from_moz + ); + me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")( + to_moz, to_moz_block + ); + MOZ_TO_ME[moztype] = moz_to_me; + def_to_moz(mytype, me_to_moz); + }; + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + }; + + AST_Node.from_mozilla_ast = function(node){ + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode, myparent) { + var start = mynode.start; + var end = mynode.end; + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + }; + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function() { + return set_moz_loc(this, handler(this)); + }); + }; + + function to_moz(node) { + return node != null ? node.to_mozilla_ast() : null; + }; + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + }; + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +"use strict"; + +function find_builtins() { + var a = []; + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp + ].forEach(function(ctor){ + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + push_uniq(a, name); + } + return a; +} + +function mangle_properties(ast, options) { + options = defaults(options, { + reserved : null, + cache : null, + only_cache : false, + regex : null + }); + + var reserved = options.reserved; + if (reserved == null) + reserved = find_builtins(); + + var cache = options.cache; + if (cache == null) { + cache = { + cname: -1, + props: new Dictionary() + }; + } + + var regex = options.regex; + + var names_to_mangle = []; + var unmangleable = []; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node){ + if (node instanceof AST_ObjectKeyVal) { + add(node.key); + } + else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + add(node.key.name); + } + else if (node instanceof AST_Dot) { + if (this.parent() instanceof AST_Assign) { + add(node.property); + } + } + else if (node instanceof AST_Sub) { + if (this.parent() instanceof AST_Assign) { + addStrings(node.property); + } + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node){ + if (node instanceof AST_ObjectKeyVal) { + node.key = mangle(node.key); + } + else if (node instanceof AST_ObjectProperty) { + // setter or getter + node.key.name = mangle(node.key.name); + } + else if (node instanceof AST_Dot) { + node.property = mangle(node.property); + } + else if (node instanceof AST_Sub) { + node.property = mangleStrings(node.property); + } + // else if (node instanceof AST_String) { + // if (should_mangle(node.value)) { + // AST_Node.warn( + // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", { + // file : node.start.file, + // line : node.start.line, + // col : node.start.col, + // prop : node.value + // } + // ); + // } + // } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.indexOf(name) >= 0) return false; + if (reserved.indexOf(name) >= 0) return false; + if (options.only_cache) { + return cache.props.has(name); + } + if (/^[0-9.]+$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (regex && !regex.test(name)) return false; + if (reserved.indexOf(name) >= 0) return false; + return cache.props.has(name) + || names_to_mangle.indexOf(name) >= 0; + } + + function add(name) { + if (can_mangle(name)) + push_uniq(names_to_mangle, name); + + if (!should_mangle(name)) { + push_uniq(unmangleable, name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.props.get(name); + if (!mangled) { + do { + mangled = base54(++cache.cname); + } while (!can_mangle(mangled)); + cache.props.set(name, mangled); + } + return mangled; + } + + function addStrings(node) { + var out = {}; + try { + (function walk(node){ + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Seq) { + walk(node.cdr); + return true; + } + if (node instanceof AST_String) { + add(node.value); + return true; + } + if (node instanceof AST_Conditional) { + walk(node.consequent); + walk(node.alternative); + return true; + } + throw out; + })); + })(node); + } catch(ex) { + if (ex !== out) throw ex; + } + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node){ + if (node instanceof AST_Seq) { + node.cdr = mangleStrings(node.cdr); + } + else if (node instanceof AST_String) { + node.value = mangle(node.value); + } + else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } + +} + +exports["Compressor"] = Compressor; +exports["DefaultsError"] = DefaultsError; +exports["Dictionary"] = Dictionary; +exports["JS_Parse_Error"] = JS_Parse_Error; +exports["MAP"] = MAP; +exports["OutputStream"] = OutputStream; +exports["SourceMap"] = SourceMap; +exports["TreeTransformer"] = TreeTransformer; +exports["TreeWalker"] = TreeWalker; +exports["base54"] = base54; +exports["defaults"] = defaults; +exports["mangle_properties"] = mangle_properties; +exports["merge"] = merge; +exports["parse"] = parse; +exports["push_uniq"] = push_uniq; +exports["string_template"] = string_template; +exports["is_identifier"] = is_identifier; +exports["SymbolDef"] = SymbolDef; + + +exports.sys = sys; +exports.MOZ_SourceMap = MOZ_SourceMap; +exports.UglifyJS = UglifyJS; +exports.array_to_hash = array_to_hash; +exports.slice = slice; +exports.characters = characters; +exports.member = member; +exports.find_if = find_if; +exports.repeat_string = repeat_string; +exports.DefaultsError = DefaultsError; +exports.defaults = defaults; +exports.merge = merge; +exports.noop = noop; +exports.MAP = MAP; +exports.push_uniq = push_uniq; +exports.string_template = string_template; +exports.remove = remove; +exports.mergeSort = mergeSort; +exports.set_difference = set_difference; +exports.set_intersection = set_intersection; +exports.makePredicate = makePredicate; +exports.all = all; +exports.Dictionary = Dictionary; +exports.DEFNODE = DEFNODE; +exports.AST_Token = AST_Token; +exports.AST_Node = AST_Node; +exports.AST_Statement = AST_Statement; +exports.AST_Debugger = AST_Debugger; +exports.AST_Directive = AST_Directive; +exports.AST_SimpleStatement = AST_SimpleStatement; +exports.walk_body = walk_body; +exports.AST_Block = AST_Block; +exports.AST_BlockStatement = AST_BlockStatement; +exports.AST_EmptyStatement = AST_EmptyStatement; +exports.AST_StatementWithBody = AST_StatementWithBody; +exports.AST_LabeledStatement = AST_LabeledStatement; +exports.AST_IterationStatement = AST_IterationStatement; +exports.AST_DWLoop = AST_DWLoop; +exports.AST_Do = AST_Do; +exports.AST_While = AST_While; +exports.AST_For = AST_For; +exports.AST_ForIn = AST_ForIn; +exports.AST_With = AST_With; +exports.AST_Scope = AST_Scope; +exports.AST_Toplevel = AST_Toplevel; +exports.AST_Lambda = AST_Lambda; +exports.AST_Accessor = AST_Accessor; +exports.AST_Function = AST_Function; +exports.AST_Defun = AST_Defun; +exports.AST_Jump = AST_Jump; +exports.AST_Exit = AST_Exit; +exports.AST_Return = AST_Return; +exports.AST_Throw = AST_Throw; +exports.AST_LoopControl = AST_LoopControl; +exports.AST_Break = AST_Break; +exports.AST_Continue = AST_Continue; +exports.AST_If = AST_If; +exports.AST_Switch = AST_Switch; +exports.AST_SwitchBranch = AST_SwitchBranch; +exports.AST_Default = AST_Default; +exports.AST_Case = AST_Case; +exports.AST_Try = AST_Try; +exports.AST_Catch = AST_Catch; +exports.AST_Finally = AST_Finally; +exports.AST_Definitions = AST_Definitions; +exports.AST_Var = AST_Var; +exports.AST_Const = AST_Const; +exports.AST_VarDef = AST_VarDef; +exports.AST_Call = AST_Call; +exports.AST_New = AST_New; +exports.AST_Seq = AST_Seq; +exports.AST_PropAccess = AST_PropAccess; +exports.AST_Dot = AST_Dot; +exports.AST_Sub = AST_Sub; +exports.AST_Unary = AST_Unary; +exports.AST_UnaryPrefix = AST_UnaryPrefix; +exports.AST_UnaryPostfix = AST_UnaryPostfix; +exports.AST_Binary = AST_Binary; +exports.AST_Conditional = AST_Conditional; +exports.AST_Assign = AST_Assign; +exports.AST_Array = AST_Array; +exports.AST_Object = AST_Object; +exports.AST_ObjectProperty = AST_ObjectProperty; +exports.AST_ObjectKeyVal = AST_ObjectKeyVal; +exports.AST_ObjectSetter = AST_ObjectSetter; +exports.AST_ObjectGetter = AST_ObjectGetter; +exports.AST_Symbol = AST_Symbol; +exports.AST_SymbolAccessor = AST_SymbolAccessor; +exports.AST_SymbolDeclaration = AST_SymbolDeclaration; +exports.AST_SymbolVar = AST_SymbolVar; +exports.AST_SymbolConst = AST_SymbolConst; +exports.AST_SymbolFunarg = AST_SymbolFunarg; +exports.AST_SymbolDefun = AST_SymbolDefun; +exports.AST_SymbolLambda = AST_SymbolLambda; +exports.AST_SymbolCatch = AST_SymbolCatch; +exports.AST_Label = AST_Label; +exports.AST_SymbolRef = AST_SymbolRef; +exports.AST_LabelRef = AST_LabelRef; +exports.AST_This = AST_This; +exports.AST_Constant = AST_Constant; +exports.AST_String = AST_String; +exports.AST_Number = AST_Number; +exports.AST_RegExp = AST_RegExp; +exports.AST_Atom = AST_Atom; +exports.AST_Null = AST_Null; +exports.AST_NaN = AST_NaN; +exports.AST_Undefined = AST_Undefined; +exports.AST_Hole = AST_Hole; +exports.AST_Infinity = AST_Infinity; +exports.AST_Boolean = AST_Boolean; +exports.AST_False = AST_False; +exports.AST_True = AST_True; +exports.TreeWalker = TreeWalker; +exports.KEYWORDS = KEYWORDS; +exports.KEYWORDS_ATOM = KEYWORDS_ATOM; +exports.RESERVED_WORDS = RESERVED_WORDS; +exports.KEYWORDS_BEFORE_EXPRESSION = KEYWORDS_BEFORE_EXPRESSION; +exports.OPERATOR_CHARS = OPERATOR_CHARS; +exports.RE_HEX_NUMBER = RE_HEX_NUMBER; +exports.RE_OCT_NUMBER = RE_OCT_NUMBER; +exports.OPERATORS = OPERATORS; +exports.WHITESPACE_CHARS = WHITESPACE_CHARS; +exports.PUNC_BEFORE_EXPRESSION = PUNC_BEFORE_EXPRESSION; +exports.PUNC_CHARS = PUNC_CHARS; +exports.REGEXP_MODIFIERS = REGEXP_MODIFIERS; +exports.UNICODE = UNICODE; +exports.is_letter = is_letter; +exports.is_digit = is_digit; +exports.is_alphanumeric_char = is_alphanumeric_char; +exports.is_unicode_digit = is_unicode_digit; +exports.is_unicode_combining_mark = is_unicode_combining_mark; +exports.is_unicode_connector_punctuation = is_unicode_connector_punctuation; +exports.is_identifier = is_identifier; +exports.is_identifier_start = is_identifier_start; +exports.is_identifier_char = is_identifier_char; +exports.is_identifier_string = is_identifier_string; +exports.parse_js_number = parse_js_number; +exports.JS_Parse_Error = JS_Parse_Error; +exports.js_error = js_error; +exports.is_token = is_token; +exports.EX_EOF = EX_EOF; +exports.tokenizer = tokenizer; +exports.UNARY_PREFIX = UNARY_PREFIX; +exports.UNARY_POSTFIX = UNARY_POSTFIX; +exports.ASSIGNMENT = ASSIGNMENT; +exports.PRECEDENCE = PRECEDENCE; +exports.STATEMENTS_WITH_LABELS = STATEMENTS_WITH_LABELS; +exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN; +exports.parse = parse; +exports.TreeTransformer = TreeTransformer; +exports.SymbolDef = SymbolDef; +exports.base54 = base54; +exports.OutputStream = OutputStream; +exports.Compressor = Compressor; +exports.SourceMap = SourceMap; +exports.find_builtins = find_builtins; +exports.mangle_properties = mangle_properties; + +exports.AST_Node.warn_function = function (txt) { if (typeof console != "undefined" && typeof console.warn === "function") console.warn(txt) } + +exports.minify = function (files, options) { + options = UglifyJS.defaults(options, { + spidermonkey : false, + outSourceMap : null, + sourceRoot : null, + inSourceMap : null, + fromString : false, + warnings : false, + mangle : {}, + mangleProperties : false, + nameCache : null, + output : null, + compress : {}, + parse : {} + }); + UglifyJS.base54.reset(); + + // 1. parse + var toplevel = null, + sourcesContent = {}; + + if (options.spidermonkey) { + toplevel = UglifyJS.AST_Node.from_mozilla_ast(files); + } else { + if (typeof files == "string") + files = [ files ]; + files.forEach(function(file, i){ + var code = options.fromString + ? file + : fs.readFileSync(file, "utf8"); + sourcesContent[file] = code; + toplevel = UglifyJS.parse(code, { + filename: options.fromString ? i : file, + toplevel: toplevel, + bare_returns: options.parse ? options.parse.bare_returns : undefined + }); + }); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll); + } + + // 2. compress + if (options.compress) { + var compress = { warnings: options.warnings }; + UglifyJS.merge(compress, options.compress); + toplevel.figure_out_scope(); + var sq = UglifyJS.Compressor(compress); + toplevel = toplevel.transform(sq); + } + + // 3. mangle properties + if (options.mangleProperties || options.nameCache) { + options.mangleProperties.cache = UglifyJS.readNameCache(options.nameCache, "props"); + toplevel = UglifyJS.mangle_properties(toplevel, options.mangleProperties); + UglifyJS.writeNameCache(options.nameCache, "props", options.mangleProperties.cache); + } + + // 4. mangle + if (options.mangle) { + toplevel.figure_out_scope(options.mangle); + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + } + + // 5. output + var inMap = options.inSourceMap; + var output = {}; + if (typeof options.inSourceMap == "string") { + inMap = fs.readFileSync(options.inSourceMap, "utf8"); + } + if (options.outSourceMap) { + output.source_map = UglifyJS.SourceMap({ + file: options.outSourceMap, + orig: inMap, + root: options.sourceRoot + }); + if (options.sourceMapIncludeSources) { + for (var file in sourcesContent) { + if (sourcesContent.hasOwnProperty(file)) { + output.source_map.get().setSourceContent(file, sourcesContent[file]); + } + } + } + + } + if (options.output) { + UglifyJS.merge(output, options.output); + } + var stream = UglifyJS.OutputStream(output); + toplevel.print(stream); + + if (options.outSourceMap && "string" === typeof options.outSourceMap) { + stream += "\n//# sourceMappingURL=" + options.outSourceMap; + } + + var source_map = output.source_map; + if (source_map) { + source_map = source_map + ""; + } + + return { + code : stream + "", + map : source_map + }; +}; + +exports.describe_ast = function () { + var out = UglifyJS.OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + var props = ctor.SELF_PROPS.filter(function(prop){ + return !/^\$/.test(prop); + }); + if (props.length > 0) { + out.space(); + out.with_parens(function(){ + props.forEach(function(prop, i){ + if (i) out.space(); + out.print(prop); + }); + }); + } + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function(){ + ctor.SUBCLASSES.forEach(function(ctor, i){ + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + }; + doitem(UglifyJS.AST_Node); + return out + ""; +}; +},{"source-map":138,"util":144}],140:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":141,"punycode":79,"querystring":82}],141:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],142:[function(require,module,exports){ +(function (global){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],143:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],144:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":143,"_process":78,"inherits":71}],145:[function(require,module,exports){ +exports.baseChar = /[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7\u04C8\u04CB\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B36-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60\u0D61\u0E01-\u0E2E\u0E30\u0E32\u0E33\u0E40-\u0E45\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102\u1103\u1105-\u1107\u1109\u110B\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D\u116E\u1172\u1173\u1175\u119E\u11A8\u11AB\u11AE\u11AF\u11B7\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3]/; + +exports.ideographic = /[\u3007\u3021-\u3029\u4E00-\u9FA5]/; + +exports.letter = /[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7\u04C8\u04CB\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B36-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60\u0D61\u0E01-\u0E2E\u0E30\u0E32\u0E33\u0E40-\u0E45\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD\u0EAE\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102\u1103\u1105-\u1107\u1109\u110B\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D\u116E\u1172\u1173\u1175\u119E\u11A8\u11AB\u11AE\u11AF\u11B7\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A\u212B\u212E\u2180-\u2182\u3007\u3021-\u3029\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\u4E00-\u9FA5\uAC00-\uD7A3]/; + +exports.combiningChar = /[\u0300-\u0345\u0360\u0361\u0483-\u0486\u0591-\u05A1\u05A3-\u05B9\u05BB-\u05BD\u05BF\u05C1\u05C2\u05C4\u064B-\u0652\u0670\u06D6-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0901-\u0903\u093C\u093E-\u094D\u0951-\u0954\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A02\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A70\u0A71\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0B01-\u0B03\u0B3C\u0B3E-\u0B43\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B82\u0B83\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C01-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C82\u0C83\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0D02\u0D03\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86-\u0F8B\u0F90-\u0F95\u0F97\u0F99-\u0FAD\u0FB1-\u0FB7\u0FB9\u20D0-\u20DC\u20E1\u302A-\u302F\u3099\u309A]/; + +exports.digit = /[0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE7-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29]/; + +exports.extender = /[\xB7\u02D0\u02D1\u0387\u0640\u0E46\u0EC6\u3005\u3031-\u3035\u309D\u309E\u30FC-\u30FE]/; +},{}],146:[function(require,module,exports){ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} + +},{}],147:[function(require,module,exports){ +function createMap(values, ignoreCase) { + var map = {}; + values.forEach(function(value) { + map[value] = 1; + }); + return ignoreCase ? function(value) { + return map[value.toLowerCase()] === 1; + } : function(value) { + return map[value] === 1; + }; +} + +exports.createMap = createMap; +exports.createMapFromString = function(values, ignoreCase) { + return createMap(values.split(/,/), ignoreCase); +}; + +},{}],"html-minifier/src/htmllint":[function(require,module,exports){ +/*! + * HTMLLint (to be used in conjunction with HTMLMinifier) + * + * Copyright (c) 2010-2013 Juriy "kangax" Zaytsev + * Licensed under the MIT license. + * + */ + +'use strict'; + +function isPresentationalElement(tag) { + return (/^(?:big|small|hr|blink|marquee)$/).test(tag); +} +function isDeprecatedElement(tag) { + return (/^(?:applet|basefont|center|dir|font|isindex|strike)$/).test(tag); +} +function isEventAttribute(attrName) { + return (/^on[a-z]+/).test(attrName); +} +function isStyleAttribute(attrName) { + return (attrName.toLowerCase() === 'style'); +} +function isDeprecatedAttribute(tag, attrName) { + return ( + (attrName === 'align' && + (/^(?:caption|applet|iframe|img|imput|object|legend|table|hr|div|h[1-6]|p)$/).test(tag)) || + (attrName === 'alink' && tag === 'body') || + (attrName === 'alt' && tag === 'applet') || + (attrName === 'archive' && tag === 'applet') || + (attrName === 'background' && tag === 'body') || + (attrName === 'bgcolor' && (/^(?:table|t[rdh]|body)$/).test(tag)) || + (attrName === 'border' && (/^(?:img|object)$/).test(tag)) || + (attrName === 'clear' && tag === 'br') || + (attrName === 'code' && tag === 'applet') || + (attrName === 'codebase' && tag === 'applet') || + (attrName === 'color' && (/^(?:base(?:font)?)$/).test(tag)) || + (attrName === 'compact' && (/^(?:dir|[dou]l|menu)$/).test(tag)) || + (attrName === 'face' && (/^base(?:font)?$/).test(tag)) || + (attrName === 'height' && (/^(?:t[dh]|applet)$/).test(tag)) || + (attrName === 'hspace' && (/^(?:applet|img|object)$/).test(tag)) || + (attrName === 'language' && tag === 'script') || + (attrName === 'link' && tag === 'body') || + (attrName === 'name' && tag === 'applet') || + (attrName === 'noshade' && tag === 'hr') || + (attrName === 'nowrap' && (/^t[dh]$/).test(tag)) || + (attrName === 'object' && tag === 'applet') || + (attrName === 'prompt' && tag === 'isindex') || + (attrName === 'size' && (/^(?:hr|font|basefont)$/).test(tag)) || + (attrName === 'start' && tag === 'ol') || + (attrName === 'text' && tag === 'body') || + (attrName === 'type' && (/^(?:li|ol|ul)$/).test(tag)) || + (attrName === 'value' && tag === 'li') || + (attrName === 'version' && tag === 'html') || + (attrName === 'vlink' && tag === 'body') || + (attrName === 'vspace' && (/^(?:applet|img|object)$/).test(tag)) || + (attrName === 'width' && (/^(?:hr|td|th|applet|pre)$/).test(tag)) + ); +} +function isInaccessibleAttribute(attrName, attrValue) { + return ( + attrName === 'href' && + (/^\s*javascript\s*:\s*void\s*(\s+0|\(\s*0\s*\))\s*$/i).test(attrValue) + ); +} + +function Lint() { + this.log = [ ]; + this._lastElement = null; + this._isElementRepeated = false; +} + +Lint.prototype.testElement = function(tag) { + if (isDeprecatedElement(tag)) { + this.log.push( + 'Found deprecated <' + + tag + '> element' + ); + } + else if (isPresentationalElement(tag)) { + this.log.push( + 'Found presentational <' + + tag + '> element' + ); + } + else { + this.checkRepeatingElement(tag); + } +}; + +Lint.prototype.checkRepeatingElement = function(tag) { + if (tag === 'br' && this._lastElement === 'br') { + this._isElementRepeated = true; + } + else if (this._isElementRepeated) { + this._reportRepeatingElement(); + this._isElementRepeated = false; + } + this._lastElement = tag; +}; + +Lint.prototype._reportRepeatingElement = function() { + this.log.push('Found <br> sequence. Try replacing it with styling.'); +}; + +Lint.prototype.testAttribute = function(tag, attrName, attrValue) { + if (isEventAttribute(attrName)) { + this.log.push( + 'Found event attribute (' + + attrName + ') on <' + tag + '> element.' + ); + } + else if (isDeprecatedAttribute(tag, attrName)) { + this.log.push( + 'Found deprecated ' + + attrName + ' attribute on <' + tag + '> element.' + ); + } + else if (isStyleAttribute(attrName)) { + this.log.push( + 'Found style attribute on <' + + tag + '> element.' + ); + } + else if (isInaccessibleAttribute(attrName, attrValue)) { + this.log.push( + 'Found inaccessible attribute ' + + '(on <' + tag + '> element).' + ); + } +}; + +Lint.prototype.testChars = function(chars) { + this._lastElement = ''; + if (/( \s*){2,}/.test(chars)) { + this.log.push('Found repeating &nbsp; sequence. Try replacing it with styling.'); + } +}; + +Lint.prototype.test = function(tag, attrName, attrValue) { + this.testElement(tag); + this.testAttribute(tag, attrName, attrValue); +}; + +Lint.prototype.populate = function(writeToElement) { + if (this._isElementRepeated) { + this._reportRepeatingElement(); + } + + if (this.log.length) { + if (writeToElement) { + writeToElement.innerHTML = '
        1. ' + this.log.join('
        2. ') + '
        '; + } + else { + var output = ' - ' + + this.log.join('\n - ') + .replace(/(<([^>]+)>)/ig, '') + .replace(/</g, '<') + .replace(/>/g, '>'); + + console.log(output); + } + } +}; + +exports.HTMLLint = Lint; + +},{}],"html-minifier/src/htmlparser":[function(require,module,exports){ +/*! + * HTML Parser By John Resig (ejohn.org) + * Modified by Juriy "kangax" Zaytsev + * Original code by Erik Arvidsson, Mozilla Public License + * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js + */ + +/* + * // Use like so: + * HTMLParser(htmlString, { + * start: function(tag, attrs, unary) {}, + * end: function(tag) {}, + * chars: function(text) {}, + * comment: function(text) {} + * }); + * + * // or to get an XML string: + * HTMLtoXML(htmlString); + * + * // or to get an XML DOM Document + * HTMLtoDOM(htmlString); + * + * // or to inject into an existing document/DOM node + * HTMLtoDOM(htmlString, document); + * HTMLtoDOM(htmlString, document.body); + * + */ + + /* global ActiveXObject, DOMDocument */ + +'use strict'; + +var createMapFromString = require('./utils').createMapFromString; + +function makeMap(values) { + return createMapFromString(values, true); +} + +// Regular Expressions for parsing tags and attributes +var singleAttrIdentifier = /([^\s"'<>\/=]+)/, + singleAttrAssign = /=/, + singleAttrAssigns = [ singleAttrAssign ], + singleAttrValues = [ + // attr value double quotes + /"([^"]*)"+/.source, + // attr value, single quotes + /'([^']*)'+/.source, + // attr value, no quotes + /([^\s"'=<>`]+)/.source + ], + // https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName + qnameCapture = (function() { + var ncname = require('ncname').source.slice(1, -1); + return '((?:' + ncname + '\\:)?' + ncname + ')'; + })(), + startTagOpen = new RegExp('^<' + qnameCapture), + startTagClose = /^\s*(\/?)>/, + endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'), + doctype = /^]+>/i; + +var IS_REGEX_CAPTURING_BROKEN = false; +'x'.replace(/x(.)?/g, function(m, g) { + IS_REGEX_CAPTURING_BROKEN = g === ''; +}); + +// Empty Elements +var empty = makeMap('area,base,basefont,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr'); + +// Inline Elements +var inline = makeMap('a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,noscript,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,svg,textarea,tt,u,var'); + +// Elements that you can, intentionally, leave open +// (and which close themselves) +var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'); + +// Attributes that have their values filled in disabled='disabled' +var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); + +// Special Elements (can contain anything) +var special = makeMap('script,style'); + +// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 +// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content +var nonPhrasing = makeMap('address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track'); + +var reCache = {}; + +function attrForHandler(handler) { + var pattern = singleAttrIdentifier.source + + '(?:\\s*(' + joinSingleAttrAssigns(handler) + ')' + + '\\s*(?:' + singleAttrValues.join('|') + '))?'; + if (handler.customAttrSurround) { + var attrClauses = []; + for ( var i = handler.customAttrSurround.length - 1; i >= 0; i-- ) { + attrClauses[i] = '(?:' + + '(' + handler.customAttrSurround[i][0].source + ')\\s*' + + pattern + + '\\s*(' + handler.customAttrSurround[i][1].source + ')' + + ')'; + } + attrClauses.push('(?:' + pattern + ')'); + pattern = '(?:' + attrClauses.join('|') + ')'; + } + return new RegExp('^\\s*' + pattern); +} + +function joinSingleAttrAssigns( handler ) { + return singleAttrAssigns.concat( + handler.customAttrAssign || [] + ).map(function (assign) { + return '(?:' + assign.source + ')'; + }).join('|'); +} + +function HTMLParser( html, handler ) { + var stack = [], lastTag; + var attribute = attrForHandler(handler); + var last, prevTag, nextTag; + while ( html ) { + last = html; + // Make sure we're not in a script or style element + if ( !lastTag || !special(lastTag) ) { + var textEnd = html.indexOf('<'); + if (textEnd === 0) { + // Comment: + if ( /^'); + + if ( commentEnd >= 0 ) { + if ( handler.comment ) { + handler.comment( html.substring( 4, commentEnd ) ); + } + html = html.substring( commentEnd + 3 ); + prevTag = ''; + continue; + } + } + + // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment + if ( /^'); + + if (conditionalEnd >= 0) { + if ( handler.comment ) { + handler.comment( html.substring(2, conditionalEnd + 1 ), true /* non-standard */ ); + } + html = html.substring( conditionalEnd + 2 ); + prevTag = ''; + continue; + } + } + + // Doctype: + var doctypeMatch = html.match( doctype ); + if ( doctypeMatch ) { + if ( handler.doctype ) { + handler.doctype( doctypeMatch[0] ); + } + html = html.substring( doctypeMatch[0].length ); + prevTag = ''; + continue; + } + + // End tag: + var endTagMatch = html.match( endTag ); + if ( endTagMatch ) { + html = html.substring( endTagMatch[0].length ); + endTagMatch[0].replace( endTag, parseEndTag ); + prevTag = '/' + endTagMatch[1].toLowerCase(); + continue; + } + + // Start tag: + var startTagMatch = parseStartTag(html); + if ( startTagMatch ) { + html = startTagMatch.rest; + handleStartTag(startTagMatch); + prevTag = startTagMatch.tagName.toLowerCase(); + continue; + } + } + + var text; + if (textEnd >= 0) { + text = html.substring( 0, textEnd ); + html = html.substring( textEnd ); + } + else { + text = html; + html = ''; } - return attrValue; + + // next tag + var nextTagMatch = parseStartTag(html); + if (nextTagMatch) { + nextTag = nextTagMatch.tagName; + } + else { + nextTagMatch = html.match( endTag ); + if (nextTagMatch) { + nextTag = '/' + nextTagMatch[1]; + } + else { + nextTag = ''; + } + } + + if ( handler.chars ) { + handler.chars(text, prevTag, nextTag); + } + prevTag = ''; + + } + else { + var stackedTag = lastTag.toLowerCase(); + var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)<\/' + stackedTag + '[^>]*>', 'i')); + + html = html.replace(reStackedTag, function(all, text) { + if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') { + text = text + .replace(//g, '$1') + .replace(//g, '$1'); + } + + if ( handler.chars ) { + handler.chars( text ); + } + + return ''; + }); + + parseEndTag( '', stackedTag ); } - else if (attrName === 'class') { - return collapseWhitespaceAll(trimWhitespace(attrValue)); + + if ( html === last ) { + throw new Error('Parse Error: ' + html); } - else if (isUriTypeAttribute(attrName, tag)) { - attrValue = trimWhitespace(attrValue); - if (options.minifyURLs && !isCanonicalURL(tag, attrs)) { - return minifyURLs(attrValue, options.minifyURLs); + } + + if (!handler.partialMarkup) { + // Clean up any remaining tags + parseEndTag(); + } + + function parseStartTag(input) { + var start = input.match(startTagOpen); + if (start) { + var match = { + tagName: start[1], + attrs: [] + }; + input = input.slice(start[0].length); + var end, attr; + while (!(end = input.match(startTagClose)) && (attr = input.match(attribute))) { + input = input.slice(attr[0].length); + match.attrs.push(attr); + } + if (end) { + match.unarySlash = end[1]; + match.rest = input.slice(end[0].length); + return match; } - return attrValue; } - else if (isNumberTypeAttribute(attrName, tag)) { - return trimWhitespace(attrValue); + } + + function handleStartTag(match) { + var tagName = match.tagName; + var unarySlash = match.unarySlash; + + if (handler.html5 && lastTag === 'p' && nonPhrasing(tagName)) { + parseEndTag( '', lastTag ); } - else if (attrName === 'style') { - attrValue = trimWhitespace(attrValue); - if (attrValue) { - attrValue = attrValue.replace(/\s*;\s*$/, ''); - } - if (options.minifyCSS) { - return minifyCSS(attrValue, options.minifyCSS, true); + + if (!handler.html5) { + while (lastTag && inline(lastTag)) { + parseEndTag( '', lastTag ); } - return attrValue; } - else if (isMetaViewport(tag, attrs) && attrName === 'content') { - attrValue = attrValue.replace(/\s+/g, '').replace(/[0-9]+\.[0-9]+/g, function(numString) { - // "0.90000" -> "0.9" - // "1.0" -> "1" - // "1.0001" -> "1.0001" (unchanged) - return (+numString).toString(); - }); + + if ( closeSelf(tagName) && lastTag === tagName ) { + parseEndTag( '', tagName ); } - else if (attrValue && options.customAttrCollapse && options.customAttrCollapse.test(attrName)) { - attrValue = attrValue.replace(/\n+|\r+|\s{2,}/g, ''); + + var unary = empty(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash; + + var attrs = match.attrs.map(function(args) { + var name, value, fallbackValue, customOpen, customClose, customAssign, quote; + var ncp = 7; // number of captured parts, scalar + + // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 + if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { + if (args[3] === '') { args[3] = undefined; } + if (args[4] === '') { args[4] = undefined; } + if (args[5] === '') { args[5] = undefined; } + } + + var j = 1; + if (handler.customAttrSurround) { + for (var i = 0, l = handler.customAttrSurround.length; i < l; i++, j += ncp) { + name = args[j + 1]; + customAssign = args[j + 2]; + if (name) { + fallbackValue = args[j + 3]; + value = fallbackValue || args[j + 4] || args[j + 5]; + quote = fallbackValue ? '"' : value ? '\'' : ''; + customOpen = args[j]; + customClose = args[j + 6]; + break; + } + } + } + + if (!name && (name = args[j])) { + customAssign = args[j + 1]; + fallbackValue = args[j + 2]; + value = fallbackValue || args[j + 3] || args[j + 4]; + quote = fallbackValue ? '"' : value ? '\'' : ''; + } + + if (value === undefined) { + value = fillAttrs(name) ? name : fallbackValue; + } + + return { + name: name, + value: value, + customAssign: customAssign || '=', + customOpen: customOpen || '', + customClose: customClose || '', + quote: quote || '' + }; + }); + + if ( !unary ) { + stack.push( { tag: tagName, attrs: attrs } ); + lastTag = tagName; + unarySlash = ''; } - else if (tag === 'script' && attrName === 'type') { - attrValue = trimWhitespace(attrValue.replace(/\s*;\s*/g, ';')); + + if ( handler.start ) { + handler.start( tagName, attrs, unary, unarySlash ); } - return attrValue; } - function isMetaViewport(tag, attrs) { - if (tag !== 'meta') { - return false; + function parseEndTag( tag, tagName ) { + var pos; + + // If no tag name is provided, clean shop + if ( !tagName ) { + pos = 0; } - for (var i = 0, len = attrs.length; i < len; i++) { - if (attrs[i].name === 'name' && attrs[i].value === 'viewport') { - return true; + else { + // Find the closest opened tag of the same type + var needle = tagName.toLowerCase(); + for ( pos = stack.length - 1; pos >= 0; pos-- ) { + if ( stack[ pos ].tag.toLowerCase() === needle ) { + break; + } } } - } - // Wrap CSS declarations for CleanCSS > 3.x - // See https://github.com/jakubpawlowicz/clean-css/issues/418 - function wrapCSS(text) { - return '*{' + text + '}'; + if ( pos >= 0 ) { + // Close all the open elements, up the stack + for ( var i = stack.length - 1; i >= pos; i-- ) { + if ( handler.end ) { + handler.end( stack[ i ].tag, stack[ i ].attrs, i > pos || !tag ); + } + } + + // Remove the open elements from the stack + stack.length = pos; + lastTag = pos && stack[ pos - 1 ].tag; + } + else if (tagName.toLowerCase() === 'br') { + if (handler.start) { + handler.start(tagName, [], true, ''); + } + } + else if (tagName.toLowerCase() === 'p') { + if (handler.start) { + handler.start(tagName, [], false, '', true); + } + if (handler.end) { + handler.end(tagName, []); + } + } } +} + +exports.HTMLParser = HTMLParser; +exports.HTMLtoXML = function( html ) { + var results = ''; - function unwrapCSS(text) { - var matches = text.match(/^\*\{([\s\S]*)\}$/m); - if (matches && matches[1]) { - return matches[1]; + new HTMLParser(html, { + start: function( tag, attrs, unary ) { + results += '<' + tag; + + for ( var i = 0; i < attrs.length; i++ ) { + results += ' ' + attrs[i].name + '="' + (attrs[i].value || '').replace(/"/g, '"') + '"'; + } + + results += (unary ? '/' : '') + '>'; + }, + end: function( tag ) { + results += ''; + }, + chars: function( text ) { + results += text; + }, + comment: function( text ) { + results += ''; + }, + ignore: function(text) { + results += text; } - else { - return text; + }); + + return results; +}; + +exports.HTMLtoDOM = function( html, doc ) { + // There can be only one of these elements + var one = { + html: true, + head: true, + body: true, + title: true + }; + + // Enforce a structure for the document + var structure = { + link: 'head', + base: 'head' + }; + + if ( !doc ) { + if ( typeof DOMDocument !== 'undefined' ) { + doc = new DOMDocument(); + } + else if ( typeof document !== 'undefined' && document.implementation && document.implementation.createDocument ) { + doc = document.implementation.createDocument('', '', null); } + else if ( typeof ActiveX !== 'undefined' ) { + doc = new ActiveXObject('Msxml.DOMDocument'); + } + + } + else { + doc = doc.ownerDocument || + doc.getOwnerDocument && doc.getOwnerDocument() || + doc; } - function cleanConditionalComment(comment, options) { - return options.processConditionalComments ? comment.replace(/^(\[if\s[^\]]+\]>)([\s\S]*?)( */" or "// ]]>" - .replace(/(?:\/\*\s*\]\]>\s*\*\/|\/\/\s*\]\]>)\s*$/, ''); + // Find all the unique elements + if ( doc.getElementsByTagName ) { + for ( var i in one ) { + one[ i ] = doc.getElementsByTagName( i )[0]; + } } - function processScript(text, options, currentAttrs) { - for (var i = 0, len = currentAttrs.length; i < len; i++) { - if (currentAttrs[i].name.toLowerCase() === 'type' && - options.processScripts.indexOf(currentAttrs[i].value) > -1) { - return minify(text, options); + // If we're working with a document, inject contents into + // the body element + var curParentNode = one.body; + + new HTMLParser( html, { + start: function( tagName, attrs, unary ) { + // If it's a pre-built element, then we can ignore + // its construction + if ( one[ tagName ] ) { + curParentNode = one[ tagName ]; + return; + } + + var elem = doc.createElement( tagName ); + + for ( var attr in attrs ) { + elem.setAttribute( attrs[ attr ].name, attrs[ attr ].value ); + } + + if ( structure[ tagName ] && typeof one[ structure[ tagName ] ] !== 'boolean' ) { + one[ structure[ tagName ] ].appendChild( elem ); } + else if ( curParentNode && curParentNode.appendChild ) { + curParentNode.appendChild( elem ); + } + + if ( !unary ) { + elems.push( elem ); + curParentNode = elem; + } + }, + end: function( /* tag */ ) { + elems.length -= 1; + + // Init the new parentNode + curParentNode = elems[ elems.length - 1 ]; + }, + chars: function( text ) { + curParentNode.appendChild( doc.createTextNode( text ) ); + }, + comment: function( /* text */ ) { + // create comment node + }, + ignore: function( /* text */ ) { + // What to do here? } - return text; + }); + + return doc; +}; + +},{"./utils":147,"ncname":74}],"html-minifier":[function(require,module,exports){ +'use strict'; + +var CleanCSS = require('clean-css'); +var HTMLParser = require('./htmlparser').HTMLParser; +var RelateUrl = require('relateurl'); +var UglifyJS = require('uglify-js'); +var utils = require('./utils'); + +var log; +if (typeof window !== 'undefined' && typeof console !== 'undefined' && typeof console.log === 'function') { + log = function(message) { + // "preserving" `this` + console.log(message); + }; +} +else { + log = function() {}; +} + +var trimWhitespace = function(str) { + if (typeof str !== 'string') { + return str; + } + return str.replace(/^\s+/, '').replace(/\s+$/, ''); +}; +if (String.prototype.trim) { + trimWhitespace = function(str) { + if (typeof str !== 'string') { + return str; + } + return str.trim(); + }; +} + +function compressWhitespace(spaces) { + return spaces === '\t' ? spaces : ' '; +} + +function collapseWhitespaceAll(str) { + return str ? str.replace(/[\t\n\r ]+/g, compressWhitespace) : str; +} + +function collapseWhitespace(str, options, trimLeft, trimRight, collapseAll) { + var lineBreakBefore = '', lineBreakAfter = ''; + + if (options.preserveLineBreaks) { + str = str.replace(/^[\t ]*[\n\r][\t\n\r ]*/, function() { + lineBreakBefore = '\n'; + return ''; + }).replace(/[\t\n\r ]*[\n\r][\t ]*$/, function() { + lineBreakAfter = '\n'; + return ''; + }); + } + + if (trimLeft) { + str = str.replace(/^\s+/, !lineBreakBefore && options.conservativeCollapse ? compressWhitespace : ''); + } + + if (trimRight) { + str = str.replace(/\s+$/, !lineBreakAfter && options.conservativeCollapse ? compressWhitespace : ''); + } + + if (collapseAll) { + // strip non space whitespace then compress spaces to one + str = collapseWhitespaceAll(str); } - var reStartDelimiter = { - // account for js + html comments (e.g.: //\s*$/, - style: /\s*-->\s*$/ - }; - function removeComments(text, tag) { - return text.replace(reStartDelimiter[tag], '').replace(reEndDelimiter[tag], ''); - } - - // Tag omission rules from https://html.spec.whatwg.org/multipage/syntax.html#optional-tags - // with the following deviations: - // - retain if followed by