build/JSXTransformer.js in react-source-0.4.2 vs build/JSXTransformer.js in react-source-0.5.0

- old
+ new

@@ -1,56 +1,262 @@ /** - * JSXTransformer v0.4.2 + * JSXTransformer v0.5.0 */ -(function(e){if("function"==typeof bootstrap)bootstrap("jsxtransformer",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeJSXTransformer=e}else"undefined"!=typeof window?window.JSXTransformer=e():global.JSXTransformer=e()})(function(){var define,ses,bootstrap,module,exports; -return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){ -var Base62 = (function (my) { - my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] +!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.JSXTransformer=e():"undefined"!=typeof global?global.JSXTransformer=e():"undefined"!=typeof self&&(self.JSXTransformer=e())}(function(){var define,module,exports; +return (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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ - my.encode = function(i){ - if (i === 0) {return '0'} - var s = '' - while (i > 0) { - s = this.chars[i % 62] + s - i = Math.floor(i/62) + +// +// The shims in this file are not fully implemented shims for the ES5 +// features, but do work for the particular usecases there is in +// the other modules. +// + +var toString = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +// Array.isArray is supported in IE9 +function isArray(xs) { + return toString.call(xs) === '[object Array]'; +} +exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; + +// Array.prototype.indexOf is supported in IE9 +exports.indexOf = function indexOf(xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0; i < xs.length; i++) { + if (x === xs[i]) return i; + } + return -1; +}; + +// Array.prototype.filter is supported in IE9 +exports.filter = function filter(xs, fn) { + if (xs.filter) return xs.filter(fn); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (fn(xs[i], i, xs)) res.push(xs[i]); + } + return res; +}; + +// Array.prototype.forEach is supported in IE9 +exports.forEach = function forEach(xs, fn, self) { + if (xs.forEach) return xs.forEach(fn, self); + for (var i = 0; i < xs.length; i++) { + fn.call(self, xs[i], i, xs); + } +}; + +// Array.prototype.map is supported in IE9 +exports.map = function map(xs, fn) { + if (xs.map) return xs.map(fn); + var out = new Array(xs.length); + for (var i = 0; i < xs.length; i++) { + out[i] = fn(xs[i], i, xs); + } + return out; +}; + +// Array.prototype.reduce is supported in IE9 +exports.reduce = function reduce(array, callback, opt_initialValue) { + if (array.reduce) return array.reduce(callback, opt_initialValue); + var value, isValueSet = false; + + if (2 < arguments.length) { + value = opt_initialValue; + isValueSet = true; + } + for (var i = 0, l = array.length; l > i; ++i) { + if (array.hasOwnProperty(i)) { + if (isValueSet) { + value = callback(value, array[i], i, array); + } + else { + value = array[i]; + isValueSet = true; + } } - return s + } + + return value; +}; + +// String.prototype.substr - negative index don't work in IE8 +if ('ab'.substr(-1) !== 'b') { + exports.substr = function (str, start, length) { + // did we get a negative start, calculate how much it is from the beginning of the string + if (start < 0) start = str.length + start; + + // call the original function + return str.substr(start, length); }; - my.decode = function(a,b,c,d){ - for ( - b = c = ( - a === (/\W|_|^$/.test(a += "") || a) - ) - 1; - d = a.charCodeAt(c++); - ) - b = b * 62 + d - [, 48, 29, 87][d >> 5]; - return b +} else { + exports.substr = function (str, start, length) { + return str.substr(start, length); }; +} - return my; -}({})); +// String.prototype.trim is supported in IE9 +exports.trim = function (str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ''); +}; -module.exports = Base62 -},{}],2:[function(require,module,exports){ -var process=require("__browserify_process");function filter (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - if (fn(xs[i], i, xs)) res.push(xs[i]); +// Function.prototype.bind is supported in IE9 +exports.bind = function () { + var args = Array.prototype.slice.call(arguments); + var fn = args.shift(); + if (fn.bind) return fn.bind.apply(fn, args); + var self = args.shift(); + return function () { + fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); + }; +}; + +// Object.create is supported in IE9 +function create(prototype, properties) { + var object; + if (prototype === null) { + object = { '__proto__' : null }; + } + else { + if (typeof prototype !== 'object') { + throw new TypeError( + 'typeof prototype[' + (typeof prototype) + '] != \'object\'' + ); } - return res; + var Type = function () {}; + Type.prototype = prototype; + object = new Type(); + object.__proto__ = prototype; + } + if (typeof properties !== 'undefined' && Object.defineProperties) { + Object.defineProperties(object, properties); + } + return object; } +exports.create = typeof Object.create === 'function' ? Object.create : create; +// Object.keys and Object.getOwnPropertyNames is supported in IE9 however +// they do show a description and number property on Error objects +function notObject(object) { + return ((typeof object != "object" && typeof object != "function") || object === null); +} + +function keysShim(object) { + if (notObject(object)) { + throw new TypeError("Object.keys called on a non-object"); + } + + var result = []; + for (var name in object) { + if (hasOwnProperty.call(object, name)) { + result.push(name); + } + } + return result; +} + +// getOwnPropertyNames is almost the same as Object.keys one key feature +// is that it returns hidden properties, since that can't be implemented, +// this feature gets reduced so it just shows the length property on arrays +function propertyShim(object) { + if (notObject(object)) { + throw new TypeError("Object.getOwnPropertyNames called on a non-object"); + } + + var result = keysShim(object); + if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { + result.push('length'); + } + return result; +} + +var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; +var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? + Object.getOwnPropertyNames : propertyShim; + +if (new Error().hasOwnProperty('description')) { + var ERROR_PROPERTY_FILTER = function (obj, array) { + if (toString.call(obj) === '[object Error]') { + array = exports.filter(array, function (name) { + return name !== 'description' && name !== 'number' && name !== 'message'; + }); + } + return array; + }; + + exports.keys = function (object) { + return ERROR_PROPERTY_FILTER(object, keys(object)); + }; + exports.getOwnPropertyNames = function (object) { + return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); + }; +} else { + exports.keys = keys; + exports.getOwnPropertyNames = getOwnPropertyNames; +} + +// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements +function valueObject(value, key) { + return { value: value[key] }; +} + +if (typeof Object.getOwnPropertyDescriptor === 'function') { + try { + Object.getOwnPropertyDescriptor({'a': 1}, 'a'); + exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + } catch (e) { + // IE8 dom element issue - use a try catch and default to valueObject + exports.getOwnPropertyDescriptor = function (value, key) { + try { + return Object.getOwnPropertyDescriptor(value, key); + } catch (e) { + return valueObject(value, key); + } + }; + } +} else { + exports.getOwnPropertyDescriptor = valueObject; +} + +},{}],2:[function(require,module,exports){ +var process=require("__browserify_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. + +var util = require('util'); +var shims = require('_shims'); + // 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; i >= 0; i--) { + for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; - if (last == '.') { + if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { @@ -67,107 +273,89 @@ } return parts; } -// Regex to split a filename into [*, dir, basename, ext] -// posix version -var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; +// 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; + var resolvedPath = '', + resolvedAbsolute = false; -for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) - ? arguments[i] - : process.cwd(); + 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' || !path) { - continue; + // Skip empty and invalid entries + if (!util.isString(path)) { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; } - 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) -// 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) { + // Normalize the path + resolvedPath = normalizeArray(shims.filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { -var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.slice(-1) === '/'; + var isAbsolute = exports.isAbsolute(path), + trailingSlash = shims.substr(path, -1) === '/'; -// Normalize the path -path = normalizeArray(filter(path.split('/'), function(p) { + // Normalize the path + path = normalizeArray(shims.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) { - return p && typeof p === 'string'; + return exports.normalize(shims.filter(paths, function(p, index) { + if (!util.isString(p)) { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; }).join('/')); }; -exports.dirname = function(path) { - var dir = splitPathRe.exec(path)[1] || ''; - var isWindows = false; - if (!dir) { - // No dirname - return '.'; - } else if (dir.length === 1 || - (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { - // It is just a slash or a drive letter with a slash - return dir; - } else { - // It is a full dirname, strip trailing slash - return dir.substring(0, dir.length - 1); - } -}; - - -exports.basename = function(path, ext) { - var f = splitPathRe.exec(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 splitPathRe.exec(path)[3] || ''; -}; - +// 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) { @@ -206,12 +394,2967 @@ return outputParts.join('/'); }; exports.sep = '/'; +exports.delimiter = ':'; -},{"__browserify_process":3}],3:[function(require,module,exports){ +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]; +}; + +},{"__browserify_process":5,"_shims":1,"util":3}],3:[function(require,module,exports){ +var Buffer=require("__browserify_Buffer").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. + +var shims = require('_shims'); + +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; +}; + +/** + * 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 = {}; + + shims.forEach(array, 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); + 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 = shims.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = shims.getOwnPropertyNames(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(''); + } + } + + shims.forEach(keys, 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 = shims.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 (shims.indexOf(ctx.seen, 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 = shims.reduce(output, 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 shims.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; +} +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]'; +} +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; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = 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 = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = shims.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +}; + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = shims.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); +} + +},{"__browserify_Buffer":4,"_shims":1}],4:[function(require,module,exports){ +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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ +exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isBE ? 0 : (nBytes - 1), + d = isBE ? 1 : -1, + 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.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) { + var e, m, c, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isBE ? (nBytes - 1) : 0, + d = isBE ? -1 : 1, + 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; +}; + +},{}],"q9TxCC":[function(require,module,exports){ +var assert; +exports.Buffer = Buffer; +exports.SlowBuffer = Buffer; +Buffer.poolSize = 8192; +exports.INSPECT_MAX_BYTES = 50; + +function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ''); +} + +function Buffer(subject, encoding, offset) { + if(!assert) assert= require('assert'); + if (!(this instanceof Buffer)) { + return new Buffer(subject, encoding, offset); + } + this.parent = this; + this.offset = 0; + + // Work-around: node's base64 implementation + // allows for non-padded strings while base64-js + // does not.. + if (encoding == "base64" && typeof subject == "string") { + subject = stringtrim(subject); + while (subject.length % 4 != 0) { + subject = subject + "="; + } + } + + var type; + + // Are we slicing? + if (typeof offset === 'number') { + this.length = coerce(encoding); + // slicing works, with limitations (no parent tracking/update) + // check https://github.com/toots/buffer-browserify/issues/19 + for (var i = 0; i < this.length; i++) { + this[i] = subject.get(i+offset); + } + } else { + // Find the length + switch (type = typeof subject) { + case 'number': + this.length = coerce(subject); + break; + + case 'string': + this.length = Buffer.byteLength(subject, encoding); + break; + + case 'object': // Assume object is an array + this.length = coerce(subject.length); + break; + + default: + throw new Error('First argument needs to be a number, ' + + 'array or string.'); + } + + // Treat array-ish objects as a byte array. + if (isArrayIsh(subject)) { + for (var i = 0; i < this.length; i++) { + if (subject instanceof Buffer) { + this[i] = subject.readUInt8(i); + } + else { + this[i] = subject[i]; + } + } + } else if (type == 'string') { + // We are a string + this.length = this.write(subject, 0, encoding); + } else if (type === 'number') { + for (var i = 0; i < this.length; i++) { + this[i] = 0; + } + } + } +} + +Buffer.prototype.get = function get(i) { + if (i < 0 || i >= this.length) throw new Error('oob'); + return this[i]; +}; + +Buffer.prototype.set = function set(i, v) { + if (i < 0 || i >= this.length) throw new Error('oob'); + return this[i] = v; +}; + +Buffer.byteLength = function (str, encoding) { + switch (encoding || "utf8") { + case 'hex': + return str.length / 2; + + case 'utf8': + case 'utf-8': + return utf8ToBytes(str).length; + + case 'ascii': + case 'binary': + return str.length; + + case 'base64': + return base64ToBytes(str).length; + + default: + throw new Error('Unknown encoding'); + } +}; + +Buffer.prototype.utf8Write = function (string, offset, length) { + var bytes, pos; + return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length); +}; + +Buffer.prototype.asciiWrite = function (string, offset, length) { + var bytes, pos; + return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length); +}; + +Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite; + +Buffer.prototype.base64Write = function (string, offset, length) { + var bytes, pos; + return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); +}; + +Buffer.prototype.base64Slice = function (start, end) { + var bytes = Array.prototype.slice.apply(this, arguments) + return require("base64-js").fromByteArray(bytes); +}; + +Buffer.prototype.utf8Slice = function () { + var bytes = Array.prototype.slice.apply(this, arguments); + var res = ""; + var tmp = ""; + var i = 0; + while (i < bytes.length) { + if (bytes[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]); + tmp = ""; + } else + tmp += "%" + bytes[i].toString(16); + + i++; + } + + return res + decodeUtf8Char(tmp); +} + +Buffer.prototype.asciiSlice = function () { + var bytes = Array.prototype.slice.apply(this, arguments); + var ret = ""; + for (var i = 0; i < bytes.length; i++) + ret += String.fromCharCode(bytes[i]); + return ret; +} + +Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; + +Buffer.prototype.inspect = function() { + var out = [], + len = this.length; + for (var i = 0; i < len; i++) { + out[i] = toHex(this[i]); + if (i == exports.INSPECT_MAX_BYTES) { + out[i + 1] = '...'; + break; + } + } + return '<Buffer ' + out.join(' ') + '>'; +}; + + +Buffer.prototype.hexSlice = function(start, end) { + var len = this.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(this[i]); + } + return out; +}; + + +Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + start = +start || 0; + if (typeof end == 'undefined') end = this.length; + + // Fastpath empty strings + if (+end == start) { + return ''; + } + + switch (encoding) { + case 'hex': + return this.hexSlice(start, end); + + case 'utf8': + case 'utf-8': + return this.utf8Slice(start, end); + + case 'ascii': + return this.asciiSlice(start, end); + + case 'binary': + return this.binarySlice(start, end); + + case 'base64': + return this.base64Slice(start, end); + + case 'ucs2': + case 'ucs-2': + return this.ucs2Slice(start, end); + + default: + throw new Error('Unknown encoding'); + } +}; + + +Buffer.prototype.hexWrite = function(string, offset, length) { + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2) { + throw new Error('Invalid hex string'); + } + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; i++) { + var byte = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(byte)) throw new Error('Invalid hex string'); + this[offset + i] = byte; + } + Buffer._charsWritten = i * 2; + return i; +}; + + +Buffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + switch (encoding) { + case 'hex': + return this.hexWrite(string, offset, length); + + case 'utf8': + case 'utf-8': + return this.utf8Write(string, offset, length); + + case 'ascii': + return this.asciiWrite(string, offset, length); + + case 'binary': + return this.binaryWrite(string, offset, length); + + case 'base64': + return this.base64Write(string, offset, length); + + case 'ucs2': + case 'ucs-2': + return this.ucs2Write(string, offset, length); + + default: + throw new Error('Unknown encoding'); + } +}; + +// slice(start, end) +function clamp(index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue; + index = ~~index; // Coerce to integer. + if (index >= len) return len; + if (index >= 0) return index; + index += len; + if (index >= 0) return index; + return 0; +} + +Buffer.prototype.slice = function(start, end) { + var len = this.length; + start = clamp(start, len, 0); + end = clamp(end, len, len); + return new Buffer(this, end - start, +start); +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function(target, target_start, start, end) { + var source = this; + start || (start = 0); + if (end === undefined || isNaN(end)) { + end = this.length; + } + target_start || (target_start = 0); + + if (end < start) throw new Error('sourceEnd < sourceStart'); + + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length == 0 || source.length == 0) return 0; + + if (target_start < 0 || target_start >= target.length) { + throw new Error('targetStart out of bounds'); + } + + if (start < 0 || start >= source.length) { + throw new Error('sourceStart out of bounds'); + } + + if (end < 0 || end > source.length) { + throw new Error('sourceEnd out of bounds'); + } + + // Are we oob? + if (end > this.length) { + end = this.length; + } + + if (target.length - target_start < end - start) { + end = target.length - target_start + start; + } + + var temp = []; + for (var i=start; i<end; i++) { + assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!"); + temp.push(this[i]); + } + + for (var i=target_start; i<target_start+temp.length; i++) { + target[i] = temp[i-target_start]; + } +}; + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill(value, start, end) { + value || (value = 0); + start || (start = 0); + end || (end = this.length); + + if (typeof value === 'string') { + value = value.charCodeAt(0); + } + if (!(typeof value === 'number') || isNaN(value)) { + throw new Error('value is not a number'); + } + + if (end < start) throw new Error('end < start'); + + // Fill 0 bytes; we're done + if (end === start) return 0; + if (this.length == 0) return 0; + + if (start < 0 || start >= this.length) { + throw new Error('start out of bounds'); + } + + if (end < 0 || end > this.length) { + throw new Error('end out of bounds'); + } + + for (var i = start; i < end; i++) { + this[i] = value; + } +} + +// Static methods +Buffer.isBuffer = function isBuffer(b) { + return b instanceof Buffer || b instanceof Buffer; +}; + +Buffer.concat = function (list, totalLength) { + if (!isArray(list)) { + throw new Error("Usage: Buffer.concat(list, [totalLength])\n \ + list should be an Array."); + } + + if (list.length === 0) { + return new Buffer(0); + } else if (list.length === 1) { + return list[0]; + } + + if (typeof totalLength !== 'number') { + totalLength = 0; + for (var i = 0; i < list.length; i++) { + var buf = list[i]; + totalLength += buf.length; + } + } + + var buffer = new Buffer(totalLength); + var pos = 0; + for (var i = 0; i < list.length; i++) { + var buf = list[i]; + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer; +}; + +Buffer.isEncoding = function(encoding) { + switch ((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; + } +}; + +// helpers + +function coerce(length) { + // Coerce length to a number (possibly NaN), round up + // in case it's fractional (e.g. 123.456) then do a + // double negate to coerce a NaN to 0. Easy, right? + length = ~~Math.ceil(+length); + return length < 0 ? 0 : length; +} + +function isArray(subject) { + return (Array.isArray || + function(subject){ + return {}.toString.apply(subject) == '[object Array]' + }) + (subject) +} + +function isArrayIsh(subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number'; +} + +function toHex(n) { + if (n < 16) return '0' + n.toString(16); + return n.toString(16); +} + +function utf8ToBytes(str) { + var byteArray = []; + for (var i = 0; i < str.length; i++) + if (str.charCodeAt(i) <= 0x7F) + byteArray.push(str.charCodeAt(i)); + else { + var h = encodeURIComponent(str.charAt(i)).substr(1).split('%'); + for (var j = 0; j < h.length; j++) + byteArray.push(parseInt(h[j], 16)); + } + + return byteArray; +} + +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 base64ToBytes(str) { + return require("base64-js").toByteArray(str); +} + +function blitBuffer(src, dst, offset, length) { + var pos, i = 0; + while (i < length) { + if ((i+offset >= dst.length) || (i >= src.length)) + break; + + dst[i + offset] = src[i]; + i++; + } + return i; +} + +function decodeUtf8Char(str) { + try { + return decodeURIComponent(str); + } catch (err) { + return String.fromCharCode(0xFFFD); // UTF 8 invalid char + } +} + +// read/write bit-twiddling + +Buffer.prototype.readUInt8 = function(offset, noAssert) { + var buffer = this; + + if (!noAssert) { + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset < buffer.length, + 'Trying to read beyond buffer length'); + } + + if (offset >= buffer.length) return; + + return buffer[offset]; +}; + +function readUInt16(buffer, offset, isBigEndian, noAssert) { + var val = 0; + + + if (!noAssert) { + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 1 < buffer.length, + 'Trying to read beyond buffer length'); + } + + if (offset >= buffer.length) return 0; + + if (isBigEndian) { + val = buffer[offset] << 8; + if (offset + 1 < buffer.length) { + val |= buffer[offset + 1]; + } + } else { + val = buffer[offset]; + if (offset + 1 < buffer.length) { + val |= buffer[offset + 1] << 8; + } + } + + return val; +} + +Buffer.prototype.readUInt16LE = function(offset, noAssert) { + return readUInt16(this, offset, false, noAssert); +}; + +Buffer.prototype.readUInt16BE = function(offset, noAssert) { + return readUInt16(this, offset, true, noAssert); +}; + +function readUInt32(buffer, offset, isBigEndian, noAssert) { + var val = 0; + + if (!noAssert) { + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 3 < buffer.length, + 'Trying to read beyond buffer length'); + } + + if (offset >= buffer.length) return 0; + + if (isBigEndian) { + if (offset + 1 < buffer.length) + val = buffer[offset + 1] << 16; + if (offset + 2 < buffer.length) + val |= buffer[offset + 2] << 8; + if (offset + 3 < buffer.length) + val |= buffer[offset + 3]; + val = val + (buffer[offset] << 24 >>> 0); + } else { + if (offset + 2 < buffer.length) + val = buffer[offset + 2] << 16; + if (offset + 1 < buffer.length) + val |= buffer[offset + 1] << 8; + val |= buffer[offset]; + if (offset + 3 < buffer.length) + val = val + (buffer[offset + 3] << 24 >>> 0); + } + + return val; +} + +Buffer.prototype.readUInt32LE = function(offset, noAssert) { + return readUInt32(this, offset, false, noAssert); +}; + +Buffer.prototype.readUInt32BE = function(offset, noAssert) { + return readUInt32(this, offset, true, noAssert); +}; + + +/* + * Signed integer types, yay team! A reminder on how two's complement actually + * works. The first bit is the signed bit, i.e. tells us whether or not the + * number should be positive or negative. If the two's complement value is + * positive, then we're done, as it's equivalent to the unsigned representation. + * + * Now if the number is positive, you're pretty much done, you can just leverage + * the unsigned translations and return those. Unfortunately, negative numbers + * aren't quite that straightforward. + * + * At first glance, one might be inclined to use the traditional formula to + * translate binary numbers between the positive and negative values in two's + * complement. (Though it doesn't quite work for the most negative value) + * Mainly: + * - invert all the bits + * - add one to the result + * + * Of course, this doesn't quite work in Javascript. Take for example the value + * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of + * course, Javascript will do the following: + * + * > ~0xff80 + * -65409 + * + * Whoh there, Javascript, that's not quite right. But wait, according to + * Javascript that's perfectly correct. When Javascript ends up seeing the + * constant 0xff80, it has no notion that it is actually a signed number. It + * assumes that we've input the unsigned value 0xff80. Thus, when it does the + * binary negation, it casts it into a signed value, (positive 0xff80). Then + * when you perform binary negation on that, it turns it into a negative number. + * + * Instead, we're going to have to use the following general formula, that works + * in a rather Javascript friendly way. I'm glad we don't support this kind of + * weird numbering scheme in the kernel. + * + * (BIT-MAX - (unsigned)val + 1) * -1 + * + * The astute observer, may think that this doesn't make sense for 8-bit numbers + * (really it isn't necessary for them). However, when you get 16-bit numbers, + * you do. Let's go back to our prior example and see how this will look: + * + * (0xffff - 0xff80 + 1) * -1 + * (0x007f + 1) * -1 + * (0x0080) * -1 + */ +Buffer.prototype.readInt8 = function(offset, noAssert) { + var buffer = this; + var neg; + + if (!noAssert) { + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset < buffer.length, + 'Trying to read beyond buffer length'); + } + + if (offset >= buffer.length) return; + + neg = buffer[offset] & 0x80; + if (!neg) { + return (buffer[offset]); + } + + return ((0xff - buffer[offset] + 1) * -1); +}; + +function readInt16(buffer, offset, isBigEndian, noAssert) { + var neg, val; + + if (!noAssert) { + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 1 < buffer.length, + 'Trying to read beyond buffer length'); + } + + val = readUInt16(buffer, offset, isBigEndian, noAssert); + neg = val & 0x8000; + if (!neg) { + return val; + } + + return (0xffff - val + 1) * -1; +} + +Buffer.prototype.readInt16LE = function(offset, noAssert) { + return readInt16(this, offset, false, noAssert); +}; + +Buffer.prototype.readInt16BE = function(offset, noAssert) { + return readInt16(this, offset, true, noAssert); +}; + +function readInt32(buffer, offset, isBigEndian, noAssert) { + var neg, val; + + if (!noAssert) { + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 3 < buffer.length, + 'Trying to read beyond buffer length'); + } + + val = readUInt32(buffer, offset, isBigEndian, noAssert); + neg = val & 0x80000000; + if (!neg) { + return (val); + } + + return (0xffffffff - val + 1) * -1; +} + +Buffer.prototype.readInt32LE = function(offset, noAssert) { + return readInt32(this, offset, false, noAssert); +}; + +Buffer.prototype.readInt32BE = function(offset, noAssert) { + return readInt32(this, offset, true, noAssert); +}; + +function readFloat(buffer, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset + 3 < buffer.length, + 'Trying to read beyond buffer length'); + } + + return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, + 23, 4); +} + +Buffer.prototype.readFloatLE = function(offset, noAssert) { + return readFloat(this, offset, false, noAssert); +}; + +Buffer.prototype.readFloatBE = function(offset, noAssert) { + return readFloat(this, offset, true, noAssert); +}; + +function readDouble(buffer, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset + 7 < buffer.length, + 'Trying to read beyond buffer length'); + } + + return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, + 52, 8); +} + +Buffer.prototype.readDoubleLE = function(offset, noAssert) { + return readDouble(this, offset, false, noAssert); +}; + +Buffer.prototype.readDoubleBE = function(offset, noAssert) { + return readDouble(this, offset, true, noAssert); +}; + + +/* + * We have to make sure that the value is a valid integer. This means that it is + * non-negative. It has no fractional component and that it does not exceed the + * maximum allowed value. + * + * value The number to check for validity + * + * max The maximum value + */ +function verifuint(value, max) { + assert.ok(typeof (value) == 'number', + 'cannot write a non-number as a number'); + + assert.ok(value >= 0, + 'specified a negative value for writing an unsigned value'); + + assert.ok(value <= max, 'value is larger than maximum value for type'); + + assert.ok(Math.floor(value) === value, 'value has a fractional component'); +} + +Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { + var buffer = this; + + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset < buffer.length, + 'trying to write beyond buffer length'); + + verifuint(value, 0xff); + } + + if (offset < buffer.length) { + buffer[offset] = value; + } +}; + +function writeUInt16(buffer, value, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 1 < buffer.length, + 'trying to write beyond buffer length'); + + verifuint(value, 0xffff); + } + + for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) { + buffer[offset + i] = + (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>> + (isBigEndian ? 1 - i : i) * 8; + } + +} + +Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) { + writeUInt16(this, value, offset, false, noAssert); +}; + +Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) { + writeUInt16(this, value, offset, true, noAssert); +}; + +function writeUInt32(buffer, value, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 3 < buffer.length, + 'trying to write beyond buffer length'); + + verifuint(value, 0xffffffff); + } + + for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { + buffer[offset + i] = + (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { + writeUInt32(this, value, offset, false, noAssert); +}; + +Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { + writeUInt32(this, value, offset, true, noAssert); +}; + + +/* + * We now move onto our friends in the signed number category. Unlike unsigned + * numbers, we're going to have to worry a bit more about how we put values into + * arrays. Since we are only worrying about signed 32-bit values, we're in + * slightly better shape. Unfortunately, we really can't do our favorite binary + * & in this system. It really seems to do the wrong thing. For example: + * + * > -32 & 0xff + * 224 + * + * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of + * this aren't treated as a signed number. Ultimately a bad thing. + * + * What we're going to want to do is basically create the unsigned equivalent of + * our representation and pass that off to the wuint* functions. To do that + * we're going to do the following: + * + * - if the value is positive + * we can pass it directly off to the equivalent wuint + * - if the value is negative + * we do the following computation: + * mb + val + 1, where + * mb is the maximum unsigned value in that byte size + * val is the Javascript negative integer + * + * + * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If + * you do out the computations: + * + * 0xffff - 128 + 1 + * 0xffff - 127 + * 0xff80 + * + * You can then encode this value as the signed version. This is really rather + * hacky, but it should work and get the job done which is our goal here. + */ + +/* + * A series of checks to make sure we actually have a signed 32-bit number + */ +function verifsint(value, max, min) { + assert.ok(typeof (value) == 'number', + 'cannot write a non-number as a number'); + + assert.ok(value <= max, 'value larger than maximum allowed value'); + + assert.ok(value >= min, 'value smaller than minimum allowed value'); + + assert.ok(Math.floor(value) === value, 'value has a fractional component'); +} + +function verifIEEE754(value, max, min) { + assert.ok(typeof (value) == 'number', + 'cannot write a non-number as a number'); + + assert.ok(value <= max, 'value larger than maximum allowed value'); + + assert.ok(value >= min, 'value smaller than minimum allowed value'); +} + +Buffer.prototype.writeInt8 = function(value, offset, noAssert) { + var buffer = this; + + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset < buffer.length, + 'Trying to write beyond buffer length'); + + verifsint(value, 0x7f, -0x80); + } + + if (value >= 0) { + buffer.writeUInt8(value, offset, noAssert); + } else { + buffer.writeUInt8(0xff + value + 1, offset, noAssert); + } +}; + +function writeInt16(buffer, value, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 1 < buffer.length, + 'Trying to write beyond buffer length'); + + verifsint(value, 0x7fff, -0x8000); + } + + if (value >= 0) { + writeUInt16(buffer, value, offset, isBigEndian, noAssert); + } else { + writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); + } +} + +Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { + writeInt16(this, value, offset, false, noAssert); +}; + +Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { + writeInt16(this, value, offset, true, noAssert); +}; + +function writeInt32(buffer, value, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 3 < buffer.length, + 'Trying to write beyond buffer length'); + + verifsint(value, 0x7fffffff, -0x80000000); + } + + if (value >= 0) { + writeUInt32(buffer, value, offset, isBigEndian, noAssert); + } else { + writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); + } +} + +Buffer.prototype.writeInt32LE = function(value, offset, noAssert) { + writeInt32(this, value, offset, false, noAssert); +}; + +Buffer.prototype.writeInt32BE = function(value, offset, noAssert) { + writeInt32(this, value, offset, true, noAssert); +}; + +function writeFloat(buffer, value, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 3 < buffer.length, + 'Trying to write beyond buffer length'); + + verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); + } + + require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, + 23, 4); +} + +Buffer.prototype.writeFloatLE = function(value, offset, noAssert) { + writeFloat(this, value, offset, false, noAssert); +}; + +Buffer.prototype.writeFloatBE = function(value, offset, noAssert) { + writeFloat(this, value, offset, true, noAssert); +}; + +function writeDouble(buffer, value, offset, isBigEndian, noAssert) { + if (!noAssert) { + assert.ok(value !== undefined && value !== null, + 'missing value'); + + assert.ok(typeof (isBigEndian) === 'boolean', + 'missing or invalid endian'); + + assert.ok(offset !== undefined && offset !== null, + 'missing offset'); + + assert.ok(offset + 7 < buffer.length, + 'Trying to write beyond buffer length'); + + verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); + } + + require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, + 52, 8); +} + +Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { + writeDouble(this, value, offset, false, noAssert); +}; + +Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { + writeDouble(this, value, offset, true, noAssert); +}; + +},{"./buffer_ieee754":1,"assert":6,"base64-js":4}],"buffer-browserify":[function(require,module,exports){ +module.exports=require('q9TxCC'); +},{}],4:[function(require,module,exports){ +(function (exports) { + 'use strict'; + + var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + function b64ToByteArray(b64) { + var i, j, l, tmp, placeHolders, arr; + + if (b64.length % 4 > 0) { + throw 'Invalid string. Length must be a multiple of 4'; + } + + // 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.indexOf('='); + placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]); + arr.push((tmp & 0xFF0000) >> 16); + arr.push((tmp & 0xFF00) >> 8); + arr.push(tmp & 0xFF); + } + + if (placeHolders === 2) { + tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4); + arr.push(tmp & 0xFF); + } else if (placeHolders === 1) { + tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2); + arr.push((tmp >> 8) & 0xFF); + arr.push(tmp & 0xFF); + } + + return arr; + } + + function uint8ToBase64(uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length; + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; + }; + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output += tripletToBase64(temp); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1]; + output += lookup[temp >> 2]; + output += lookup[(temp << 4) & 0x3F]; + output += '=='; + break; + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); + output += lookup[temp >> 10]; + output += lookup[(temp >> 4) & 0x3F]; + output += lookup[(temp << 2) & 0x3F]; + output += '='; + break; + } + + return output; + } + + module.exports.toByteArray = b64ToByteArray; + module.exports.fromByteArray = uint8ToBase64; +}()); + +},{}],5:[function(require,module,exports){ + + +// +// The shims in this file are not fully implemented shims for the ES5 +// features, but do work for the particular usecases there is in +// the other modules. +// + +var toString = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +// Array.isArray is supported in IE9 +function isArray(xs) { + return toString.call(xs) === '[object Array]'; +} +exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; + +// Array.prototype.indexOf is supported in IE9 +exports.indexOf = function indexOf(xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0; i < xs.length; i++) { + if (x === xs[i]) return i; + } + return -1; +}; + +// Array.prototype.filter is supported in IE9 +exports.filter = function filter(xs, fn) { + if (xs.filter) return xs.filter(fn); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (fn(xs[i], i, xs)) res.push(xs[i]); + } + return res; +}; + +// Array.prototype.forEach is supported in IE9 +exports.forEach = function forEach(xs, fn, self) { + if (xs.forEach) return xs.forEach(fn, self); + for (var i = 0; i < xs.length; i++) { + fn.call(self, xs[i], i, xs); + } +}; + +// Array.prototype.map is supported in IE9 +exports.map = function map(xs, fn) { + if (xs.map) return xs.map(fn); + var out = new Array(xs.length); + for (var i = 0; i < xs.length; i++) { + out[i] = fn(xs[i], i, xs); + } + return out; +}; + +// Array.prototype.reduce is supported in IE9 +exports.reduce = function reduce(array, callback, opt_initialValue) { + if (array.reduce) return array.reduce(callback, opt_initialValue); + var value, isValueSet = false; + + if (2 < arguments.length) { + value = opt_initialValue; + isValueSet = true; + } + for (var i = 0, l = array.length; l > i; ++i) { + if (array.hasOwnProperty(i)) { + if (isValueSet) { + value = callback(value, array[i], i, array); + } + else { + value = array[i]; + isValueSet = true; + } + } + } + + return value; +}; + +// String.prototype.substr - negative index don't work in IE8 +if ('ab'.substr(-1) !== 'b') { + exports.substr = function (str, start, length) { + // did we get a negative start, calculate how much it is from the beginning of the string + if (start < 0) start = str.length + start; + + // call the original function + return str.substr(start, length); + }; +} else { + exports.substr = function (str, start, length) { + return str.substr(start, length); + }; +} + +// String.prototype.trim is supported in IE9 +exports.trim = function (str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ''); +}; + +// Function.prototype.bind is supported in IE9 +exports.bind = function () { + var args = Array.prototype.slice.call(arguments); + var fn = args.shift(); + if (fn.bind) return fn.bind.apply(fn, args); + var self = args.shift(); + return function () { + fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); + }; +}; + +// Object.create is supported in IE9 +function create(prototype, properties) { + var object; + if (prototype === null) { + object = { '__proto__' : null }; + } + else { + if (typeof prototype !== 'object') { + throw new TypeError( + 'typeof prototype[' + (typeof prototype) + '] != \'object\'' + ); + } + var Type = function () {}; + Type.prototype = prototype; + object = new Type(); + object.__proto__ = prototype; + } + if (typeof properties !== 'undefined' && Object.defineProperties) { + Object.defineProperties(object, properties); + } + return object; +} +exports.create = typeof Object.create === 'function' ? Object.create : create; + +// Object.keys and Object.getOwnPropertyNames is supported in IE9 however +// they do show a description and number property on Error objects +function notObject(object) { + return ((typeof object != "object" && typeof object != "function") || object === null); +} + +function keysShim(object) { + if (notObject(object)) { + throw new TypeError("Object.keys called on a non-object"); + } + + var result = []; + for (var name in object) { + if (hasOwnProperty.call(object, name)) { + result.push(name); + } + } + return result; +} + +// getOwnPropertyNames is almost the same as Object.keys one key feature +// is that it returns hidden properties, since that can't be implemented, +// this feature gets reduced so it just shows the length property on arrays +function propertyShim(object) { + if (notObject(object)) { + throw new TypeError("Object.getOwnPropertyNames called on a non-object"); + } + + var result = keysShim(object); + if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { + result.push('length'); + } + return result; +} + +var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; +var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? + Object.getOwnPropertyNames : propertyShim; + +if (new Error().hasOwnProperty('description')) { + var ERROR_PROPERTY_FILTER = function (obj, array) { + if (toString.call(obj) === '[object Error]') { + array = exports.filter(array, function (name) { + return name !== 'description' && name !== 'number' && name !== 'message'; + }); + } + return array; + }; + + exports.keys = function (object) { + return ERROR_PROPERTY_FILTER(object, keys(object)); + }; + exports.getOwnPropertyNames = function (object) { + return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); + }; +} else { + exports.keys = keys; + exports.getOwnPropertyNames = getOwnPropertyNames; +} + +// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements +function valueObject(value, key) { + return { value: value[key] }; +} + +if (typeof Object.getOwnPropertyDescriptor === 'function') { + try { + Object.getOwnPropertyDescriptor({'a': 1}, 'a'); + exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + } catch (e) { + // IE8 dom element issue - use a try catch and default to valueObject + exports.getOwnPropertyDescriptor = function (value, key) { + try { + return Object.getOwnPropertyDescriptor(value, key); + } catch (e) { + return valueObject(value, key); + } + }; + } +} else { + exports.getOwnPropertyDescriptor = valueObject; +} + +},{}],6:[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. + +// UTILITY +var util = require('util'); +var shims = require('_shims'); +var pSlice = Array.prototype.slice; + +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + this.message = options.message || getMessage(this); +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + return true; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + try { + var ka = shims.keys(a), + kb = shims.keys(b), + key, i; + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; +},{"_shims":5,"util":7}],7:[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 shims = require('_shims'); + +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; +}; + +/** + * 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 = {}; + + shims.forEach(array, 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); + 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 = shims.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = shims.getOwnPropertyNames(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(''); + } + } + + shims.forEach(keys, 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 = shims.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 (shims.indexOf(ctx.seen, 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 = shims.reduce(output, 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 shims.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; +} +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]'; +} +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; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = 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 = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = shims.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +}; + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = shims.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); +} + +},{"_shims":5}]},{},[]) +;;module.exports=require("buffer-browserify") + +},{}],5:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { @@ -261,12 +3404,13 @@ process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; -},{}],4:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ /* + Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl> Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com> @@ -408,19 +3552,18 @@ ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', + ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', - ExportSpecifierSet: 'ExportSpecifierSet', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', - Glob: 'Glob', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportSpecifier: 'ImportSpecifier', LabeledStatement: 'LabeledStatement', @@ -430,11 +3573,10 @@ MethodDefinition: 'MethodDefinition', ModuleDeclaration: 'ModuleDeclaration', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', - Path: 'Path', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', @@ -444,10 +3586,12 @@ TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', + TypeAnnotatedIdentifier: 'TypeAnnotatedIdentifier', + TypeAnnotation: 'TypeAnnotation', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', @@ -503,10 +3647,11 @@ StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list', + DefaultRestParameter: 'Rest parameter can not have a default value', ElementAfterSpreadElement: 'Spread must be the final element of an element list', ObjectPatternAsRestParameter: 'Invalid rest parameter', ObjectPatternAsSpread: 'Invalid spread argument', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', @@ -516,11 +3661,14 @@ AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', + NewlineAfterModule: 'Illegal newline after module', NoFromAfterImport: 'Missing from after import', + InvalidModuleSpecifier: 'Invalid module specifier', + NestedModule: 'Module declaration can not be nested', NoYieldInGenerator: 'Missing yield in generator', NoUnintializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', @@ -1475,10 +4623,11 @@ } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } + cooked += '\n'; } else { cooked += ch; } } @@ -1944,29 +5093,33 @@ right: right, body: body, }; }, - createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression) { + createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, + returnTypeAnnotation) { return { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, + returnType: returnTypeAnnotation, body: body, rest: rest, generator: generator, expression: expression }; }, - createFunctionExpression: function (id, params, defaults, body, rest, generator, expression) { + createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, + returnTypeAnnotation) { return { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, + returnType: returnTypeAnnotation, body: body, rest: rest, generator: generator, expression: expression }; @@ -1977,10 +5130,32 @@ type: Syntax.Identifier, name: name }; }, + createTypeAnnotatedIdentifier: function (annotation, identifier) { + return { + type: Syntax.TypeAnnotatedIdentifier, + annotation: annotation, + identifier: identifier + }; + }, + + createTypeAnnotation: function (annotatedType, templateTypes, + paramTypes, returnType, unionType, + nullable) { + return { + type: Syntax.TypeAnnotation, + annotatedType: annotatedType, + templateTypes: templateTypes, + paramTypes: paramTypes, + returnType: returnType, + unionType: unionType, + nullable: nullable + }; + }, + createXJSAttribute: function (name, value) { return { type: Syntax.XJSAttribute, name: name, value: value @@ -2290,59 +5465,48 @@ superClass: superClass, body: body }; }, - createPath: function (body) { + createExportSpecifier: function (id, name) { return { - type: Syntax.Path, - body: body - }; - }, - - createGlob: function () { - return { - type: Syntax.Glob - }; - }, - - createExportSpecifier: function (id, from) { - return { type: Syntax.ExportSpecifier, id: id, - from: from + name: name }; }, - createExportSpecifierSet: function (specifiers) { + createExportBatchSpecifier: function () { return { - type: Syntax.ExportSpecifierSet, - specifiers: specifiers + type: Syntax.ExportBatchSpecifier }; }, - createExportDeclaration: function (declaration, specifiers) { + createExportDeclaration: function (def, declaration, specifiers, source) { return { type: Syntax.ExportDeclaration, declaration: declaration, - specifiers: specifiers + default: def, + specifiers: specifiers, + source: source }; }, - createImportSpecifier: function (id, from) { + createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, - from: from + name: name }; }, - createImportDeclaration: function (specifiers, from) { + createImportDeclaration: function (specifiers, kind, source) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, - from: from + kind: kind, + source: source }; }, createYieldExpression: function (argument, delegate) { return { @@ -2350,15 +5514,15 @@ argument: argument, delegate: delegate }; }, - createModuleDeclaration: function (id, from, body) { + createModuleDeclaration: function (id, source, body) { return { type: Syntax.ModuleDeclaration, id: id, - from: from, + source: source, body: body }; } @@ -2626,28 +5790,30 @@ } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { - var previousStrict, previousYieldAllowed, params, body; + var previousStrict, previousYieldAllowed, params, defaults, body; previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; params = options.params || []; + defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } if (state.yieldAllowed && !state.yieldFound) { - throwError({}, Messages.NoYieldInGenerator); + throwErrorTolerant({}, Messages.NoYieldInGenerator); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; - return delegate.createFunctionExpression(null, params, [], body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement); + return delegate.createFunctionExpression(null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, + options.returnTypeAnnotation); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; @@ -2662,12 +5828,14 @@ } method = parsePropertyFunction({ params: tmp.params, + defaults: tmp.defaults, rest: tmp.rest, - generator: options.generator + generator: options.generator, + returnTypeAnnotation: tmp.returnTypeAnnotation }); strict = previousStrict; return method; @@ -3319,30 +6487,38 @@ } } } function reinterpretAsCoverFormalsList(expressions) { - var i, len, param, params, options, rest; + var i, len, param, params, defaults, defaultCount, options, rest; params = []; + defaults = []; + defaultCount = 0; rest = null; options = { paramSet: {} }; for (i = 0, len = expressions.length; i < len; i += 1) { param = expressions[i]; if (param.type === Syntax.Identifier) { params.push(param); + defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); + defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, "It is guaranteed that SpreadElement is last element by parseExpression"); reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; + } else if (param.type === Syntax.AssignmentExpression) { + params.push(param.left); + defaults.push(param.right); + ++defaultCount; } else { return null; } } @@ -3351,11 +6527,15 @@ } if (options.stricted) { throwErrorTolerant(options.stricted, options.message); } - return { params: params, rest: rest }; + if (defaultCount === 0) { + defaults = []; + } + + return { params: params, defaults: defaults, rest: rest }; } function parseArrowFunctionExpression(options) { var previousStrict, previousYieldAllowed, body; @@ -3367,11 +6547,11 @@ state.yieldAllowed = false; body = parseConciseBody(); strict = previousStrict; state.yieldAllowed = previousYieldAllowed; - return delegate.createArrowFunctionExpression(options.params, [], body, options.rest, body.type !== Syntax.BlockStatement); + return delegate.createArrowFunctionExpression(options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement); } function parseAssignmentExpression() { var expr, token, params, oldParenthesizedCount; @@ -3398,11 +6578,11 @@ if (match('=>') && expr.type === Syntax.Identifier) { if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.StrictParamName); } - return parseArrowFunctionExpression({ params: [ expr ], rest: null }); + return parseArrowFunctionExpression({ params: [ expr ], defaults: [], rest: null }); } } if (matchAssign()) { // 11.13.1 @@ -3518,21 +6698,119 @@ } return delegate.createIdentifier(token.value); } + function parseTypeAnnotation() { + var isNullable = false, paramTypes = null, returnType = null, + templateTypes = null, type, unionType = null; + + if (match('?')) { + lex(); + isNullable = true; + } + + type = parseVariableIdentifier(); + + if (match('<')) { + lex(); + templateTypes = []; + while (lookahead.type === Token.Identifier || match('?')) { + templateTypes.push(parseTypeAnnotation()); + if (!match('>')) { + expect(','); + } + } + expect('>'); + } + + if (match('(')) { + lex(); + paramTypes = []; + while (lookahead.type === Token.Identifier || match('?')) { + paramTypes.push(parseTypeAnnotation()); + if (!match(')')) { + expect(','); + } + } + expect(')'); + + if (match(':')) { + lex(); + returnType = parseTypeAnnotation(); + } + } + + if (match('|')) { + lex(); + unionType = parseTypeAnnotation(); + } + + return delegate.createTypeAnnotation( + type, + templateTypes, + paramTypes, + returnType, + unionType, + isNullable + ); + } + + function parseAnnotatableIdentifier() { + var annotation, annotationLookahead, annotationPresent, identifier, + matchesNullableToken; + + matchesNullableToken = match('?'); + + if (lookahead.type !== Token.Identifier && !matchesNullableToken) { + throwUnexpected(lookahead); + } + + if (!matchesNullableToken) { + annotationLookahead = lookahead2(); + } + + annotationPresent = + matchesNullableToken + + // function (number numVal) {} + || annotationLookahead.type === Token.Identifier + + // function (fn(number)|array<number|string> param) {} + || (annotationLookahead.type === Token.Punctuator + && (annotationLookahead.value === '(' + || annotationLookahead.value === '<' + || annotationLookahead.value === '|')); + + if (!annotationPresent) { + return parseVariableIdentifier(); + } + + annotation = parseTypeAnnotation(); + identifier = parseVariableIdentifier(); + + return delegate.createTypeAnnotatedIdentifier( + annotation, + identifier + ); + } + function parseVariableDeclaration(kind) { var id, init = null; if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); } else { - id = parseVariableIdentifier(); + if (state.allowDefault) { + id = matchKeyword('default') ? parseNonComputedProperty() : parseVariableIdentifier(); + } else { + id = parseVariableIdentifier(); + } // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } @@ -3593,186 +6871,183 @@ return delegate.createVariableDeclaration(declarations, kind); } // http://wiki.ecmascript.org/doku.php?id=harmony:modules - function parsePath() { - var body = []; - - while (true) { - body.push(parseVariableIdentifier()); - if (!match('.')) { - break; - } - lex(); - } - - return delegate.createPath(body); - } - - function parseGlob() { - expect('*'); - return delegate.createGlob(); - } - function parseModuleDeclaration() { - var id, token, from = null; + var id, src, body; - lex(); + lex(); // 'module' - id = parseVariableIdentifier(); - - if (match('{')) { - return delegate.createModuleDeclaration(id, from, parseModuleBlock()); + if (peekLineTerminator()) { + throwError({}, Messages.NewlineAfterModule); } - expect('='); + switch (lookahead.type) { - token = lookahead; - if (token.type === Token.StringLiteral) { - from = parsePrimaryExpression(); - } else { - from = parsePath(); + case Token.StringLiteral: + id = parsePrimaryExpression(); + body = parseModuleBlock(); + src = null; + break; + + case Token.Identifier: + id = parseVariableIdentifier(); + body = null; + if (!matchContextualKeyword('from')) { + throwUnexpected(lex()); + } + lex(); + src = parsePrimaryExpression(); + if (src.type !== Syntax.Literal) { + throwError({}, Messages.InvalidModuleSpecifier); + } + break; } consumeSemicolon(); + return delegate.createModuleDeclaration(id, src, body); + } - return delegate.createModuleDeclaration(id, from, null); + function parseExportBatchSpecifier() { + expect('*'); + return delegate.createExportBatchSpecifier(); } - function parseExportSpecifierSetProperty() { - var id, from = null; + function parseExportSpecifier() { + var id, name = null; id = parseVariableIdentifier(); - - if (match(':')) { + if (matchContextualKeyword('as')) { lex(); - from = parsePath(); + name = parseNonComputedProperty(); } - return delegate.createExportSpecifier(id, from); + return delegate.createExportSpecifier(id, name); } - function parseExportSpecifier() { - var specifiers, id, from; + function parseExportDeclaration() { + var previousAllowDefault, decl, def, src, specifiers; - if (match('{')) { - lex(); - specifiers = []; + expectKeyword('export'); - do { - specifiers.push(parseExportSpecifierSetProperty()); - } while (match(',') && lex()); - - expect('}'); - - return delegate.createExportSpecifierSet(specifiers); - } - - from = null; - - if (match('*')) { - id = parseGlob(); - if (matchContextualKeyword('from')) { + if (matchKeyword('default')) { + lex(); + if (match('=')) { lex(); - from = parsePath(); + def = parseAssignmentExpression(); + } else if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { + case 'let': + case 'const': + case 'var': + case 'class': + def = parseSourceElement(); + break; + case 'function': + def = parseFunctionExpression(); + break; + default: + throwUnexpected(lex()); + } + } else { + def = parseAssignmentExpression(); } - } else { - id = parseVariableIdentifier(); + consumeSemicolon(); + return delegate.createExportDeclaration(true, def, null, null); } - return delegate.createExportSpecifier(id, from); - } - function parseExportDeclaration() { - var token, specifiers; - - expectKeyword('export'); - - token = lookahead; - - if (token.type === Token.Keyword || (token.type === Token.Identifier && token.value === 'module')) { - switch (token.value) { - case 'function': - return delegate.createExportDeclaration(parseFunctionDeclaration(), null); - case 'module': - return delegate.createExportDeclaration(parseModuleDeclaration(), null); + if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { case 'let': case 'const': - return delegate.createExportDeclaration(parseConstLetDeclaration(token.value), null); case 'var': - return delegate.createExportDeclaration(parseStatement(), null); case 'class': - return delegate.createExportDeclaration(parseClassDeclaration(), null); + case 'function': + previousAllowDefault = state.allowDefault; + state.allowDefault = true; + decl = delegate.createExportDeclaration(false, parseSourceElement(), null, null); + state.allowDefault = previousAllowDefault; + return decl; } throwUnexpected(lex()); } - specifiers = [ parseExportSpecifier() ]; - if (match(',')) { - while (index < length) { - if (!match(',')) { - break; - } - lex(); + specifiers = []; + src = null; + + if (match('*')) { + specifiers.push(parseExportBatchSpecifier()); + } else { + expect('{'); + do { specifiers.push(parseExportSpecifier()); + } while (match(',') && lex()); + expect('}'); + } + + if (matchContextualKeyword('from')) { + lex(); + src = parsePrimaryExpression(); + if (src.type !== Syntax.Literal) { + throwError({}, Messages.InvalidModuleSpecifier); } } consumeSemicolon(); - return delegate.createExportDeclaration(null, specifiers); + return delegate.createExportDeclaration(false, null, specifiers, src); } function parseImportDeclaration() { - var specifiers, from; + var specifiers, kind, src; expectKeyword('import'); + specifiers = []; - if (match('*')) { - specifiers = [parseGlob()]; + if (isIdentifierName(lookahead)) { + kind = 'default'; + specifiers.push(parseImportSpecifier()); + + if (!matchContextualKeyword('from')) { + throwError({}, Messages.NoFromAfterImport); + } + lex(); } else if (match('{')) { + kind = 'named'; lex(); - specifiers = []; - do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); - expect('}'); - } else { - specifiers = [parseVariableIdentifier()]; - } - if (!matchContextualKeyword('from')) { - throwError({}, Messages.NoFromAfterImport); + if (!matchContextualKeyword('from')) { + throwError({}, Messages.NoFromAfterImport); + } + lex(); } - lex(); - - if (lookahead.type === Token.StringLiteral) { - from = parsePrimaryExpression(); - } else { - from = parsePath(); + src = parsePrimaryExpression(); + if (src.type !== Syntax.Literal) { + throwError({}, Messages.InvalidModuleSpecifier); } consumeSemicolon(); - return delegate.createImportDeclaration(specifiers, from); + return delegate.createImportDeclaration(specifiers, kind, src); } function parseImportSpecifier() { - var id, from; + var id, name = null; - id = parseVariableIdentifier(); - from = null; - - if (match(':')) { + id = parseNonComputedProperty(); + if (matchContextualKeyword('as')) { lex(); - from = parsePath(); + name = parseVariableIdentifier(); } - return delegate.createImportSpecifier(id, from); + return delegate.createImportSpecifier(id, name); } // 12.3 Empty Statement function parseEmptyStatement() { @@ -4147,17 +7422,17 @@ expect(')'); expect('{'); + cases = []; + if (match('}')) { lex(); - return delegate.createSwitchStatement(discriminant); + return delegate.createSwitchStatement(discriminant, cases); } - cases = []; - oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { @@ -4438,11 +7713,11 @@ } options.paramSet[key] = true; } function parseParam(options) { - var token, rest, param; + var token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; @@ -4456,12 +7731,25 @@ throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); } else { - param = parseVariableIdentifier(); + // We don't currently support typed rest params because doing so is + // a bit awkward. We may come back to this, but for now we'll punt + // on it. + param = rest + ? parseVariableIdentifier() + : parseAnnotatableIdentifier(); validateParam(options, token, token.value); + if (match('=')) { + if (rest) { + throwErrorTolerant(lookahead, Messages.DefaultRestParameter); + } + lex(); + def = parseAssignmentExpression(); + ++options.defaultCount; + } } if (rest) { if (!match(')')) { throwError({}, Messages.ParameterAfterRestParameter); @@ -4469,18 +7757,21 @@ options.rest = param; return false; } options.params.push(param); + options.defaults.push(def); return !match(')'); } function parseParams(firstRestricted) { var options; options = { params: [], + defaultCount: 0, + defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); @@ -4495,10 +7786,19 @@ } } expect(')'); + if (options.defaultCount === 0) { + options.defaults = []; + } + + if (match(':')) { + lex(); + options.returnTypeAnnotation = parseTypeAnnotation(); + } + return options; } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator, expression; @@ -4511,11 +7811,15 @@ generator = true; } token = lookahead; - id = parseVariableIdentifier(); + if (state.allowDefault) { + id = matchKeyword('default') ? parseNonComputedProperty() : parseVariableIdentifier(); + } else { + id = parseVariableIdentifier(); + } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { @@ -4547,16 +7851,17 @@ } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } if (state.yieldAllowed && !state.yieldFound) { - throwError({}, Messages.NoYieldInGenerator); + throwErrorTolerant({}, Messages.NoYieldInGenerator); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; - return delegate.createFunctionDeclaration(id, tmp.params, [], body, tmp.rest, generator, expression); + return delegate.createFunctionDeclaration(id, tmp.params, tmp.defaults, body, tmp.rest, generator, expression, + tmp.returnTypeAnnotation); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator, expression; @@ -4606,16 +7911,17 @@ } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } if (state.yieldAllowed && !state.yieldFound) { - throwError({}, Messages.NoYieldInGenerator); + throwErrorTolerant({}, Messages.NoYieldInGenerator); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; - return delegate.createFunctionExpression(id, tmp.params, [], body, tmp.rest, generator, expression); + return delegate.createFunctionExpression(id, tmp.params, tmp.defaults, body, tmp.rest, generator, expression, + tmp.returnTypeAnnotation); } function parseYieldExpression() { var delegateFlag, expr, previousYieldAllowed; @@ -4797,16 +8103,19 @@ return delegate.createClassExpression(id, superClass, parseClassBody()); } function parseClassDeclaration() { - var token, id, previousYieldAllowed, superClass = null; + var id, previousYieldAllowed, superClass = null; expectKeyword('class'); - token = lookahead; - id = parseVariableIdentifier(); + if (state.allowDefault) { + id = matchKeyword('default') ? parseNonComputedProperty() : parseVariableIdentifier(); + } else { + id = parseVariableIdentifier(); + } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; @@ -4817,46 +8126,57 @@ return delegate.createClassDeclaration(id, superClass, parseClassBody()); } // 15 Program + function matchModuleDeclaration() { + var id; + if (matchContextualKeyword('module')) { + id = lookahead2(); + return id.type === Token.StringLiteral || id.type === Token.Identifier; + } + return false; + } + function parseSourceElement() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); + case 'export': + return parseExportDeclaration(); + case 'import': + return parseImportDeclaration(); default: return parseStatement(); } } + if (matchModuleDeclaration()) { + throwError({}, Messages.NestedModule); + } + if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { - var lineNumber, token; - if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } - if (lookahead.value === 'module' && lookahead.type === Token.Identifier) { - lineNumber = lookahead.lineNumber; - token = lookahead2(); - if (token.type === Token.Identifier && token.lineNumber === lineNumber) { - return parseModuleDeclaration(); - } + if (matchModuleDeclaration()) { + return parseModuleDeclaration(); } return parseSourceElement(); } @@ -4897,11 +8217,11 @@ } return sourceElements; } function parseModuleElement() { - return parseProgramElement(); + return parseSourceElement(); } function parseModuleElements() { var list = [], statement; @@ -5506,11 +8826,11 @@ function parseXJSIdentifier() { var token; if (lookahead.type !== Token.XJSIdentifier) { - throwError({}, Messages.InvalidXJSTagName); + throwUnexpected(lookahead); } token = lex(); return delegate.createXJSIdentifier(token.value, token.namespace); } @@ -5753,32 +9073,34 @@ } extra.tokens = tokens; } - function createLocationMarker() { - var marker = {}; - - marker.range = [index, index]; - marker.loc = { + function LocationMarker() { + this.range = [index, index]; + this.loc = { start: { line: lineNumber, column: index - lineStart }, end: { line: lineNumber, column: index - lineStart } }; + } - marker.end = function () { + LocationMarker.prototype = { + constructor: LocationMarker, + + end: function () { this.range[1] = index; this.loc.end.line = lineNumber; this.loc.end.column = index - lineStart; - }; + }, - marker.applyGroup = function (node) { + applyGroup: function (node) { if (extra.range) { node.groupRange = [this.range[0], this.range[1]]; } if (extra.loc) { node.groupLoc = { @@ -5791,13 +9113,13 @@ column: this.loc.end.column } }; node = delegate.postProcess(node); } - }; + }, - marker.apply = function (node) { + apply: function (node) { var nodeType = typeof node; assert(nodeType === "object", "Applying location marker to an unexpected node type: " + nodeType); @@ -5815,13 +9137,15 @@ column: this.loc.end.column } }; node = delegate.postProcess(node); } - }; + } + }; - return marker; + function createLocationMarker() { + return new LocationMarker(); } function trackGroupExpression() { var marker, expr; @@ -6028,28 +9352,26 @@ extra.parseFunctionSourceElements = parseFunctionSourceElements; extra.parseCatchClause = parseCatchClause; extra.parseComputedMember = parseComputedMember; extra.parseConditionalExpression = parseConditionalExpression; extra.parseConstLetDeclaration = parseConstLetDeclaration; + extra.parseExportBatchSpecifier = parseExportBatchSpecifier; extra.parseExportDeclaration = parseExportDeclaration; extra.parseExportSpecifier = parseExportSpecifier; - extra.parseExportSpecifierSetProperty = parseExportSpecifierSetProperty; extra.parseExpression = parseExpression; extra.parseForVariableDeclaration = parseForVariableDeclaration; extra.parseFunctionDeclaration = parseFunctionDeclaration; extra.parseFunctionExpression = parseFunctionExpression; extra.parseParams = parseParams; - extra.parseGlob = parseGlob; extra.parseImportDeclaration = parseImportDeclaration; extra.parseImportSpecifier = parseImportSpecifier; extra.parseModuleDeclaration = parseModuleDeclaration; extra.parseModuleBlock = parseModuleBlock; extra.parseNewExpression = parseNewExpression; extra.parseNonComputedProperty = parseNonComputedProperty; extra.parseObjectProperty = parseObjectProperty; extra.parseObjectPropertyKey = parseObjectPropertyKey; - extra.parsePath = parsePath; extra.parsePostfixExpression = parsePostfixExpression; extra.parsePrimaryExpression = parsePrimaryExpression; extra.parseProgram = parseProgram; extra.parsePropertyFunction = parsePropertyFunction; extra.parseSpreadOrAssignmentExpression = parseSpreadOrAssignmentExpression; @@ -6058,10 +9380,12 @@ extra.parseStatement = parseStatement; extra.parseSwitchCase = parseSwitchCase; extra.parseUnaryExpression = parseUnaryExpression; extra.parseVariableDeclaration = parseVariableDeclaration; extra.parseVariableIdentifier = parseVariableIdentifier; + extra.parseAnnotatableIdentifier = parseAnnotatableIdentifier; + extra.parseTypeAnnotation = parseTypeAnnotation; extra.parseMethodDefinition = parseMethodDefinition; extra.parseClassDeclaration = parseClassDeclaration; extra.parseClassExpression = parseClassExpression; extra.parseClassBody = parseClassBody; extra.parseXJSIdentifier = parseXJSIdentifier; @@ -6080,29 +9404,27 @@ parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements); parseCatchClause = wrapTracking(extra.parseCatchClause); parseComputedMember = wrapTracking(extra.parseComputedMember); parseConditionalExpression = wrapTracking(extra.parseConditionalExpression); parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration); + parseExportBatchSpecifier = wrapTracking(parseExportBatchSpecifier); parseExportDeclaration = wrapTracking(parseExportDeclaration); parseExportSpecifier = wrapTracking(parseExportSpecifier); - parseExportSpecifierSetProperty = wrapTracking(parseExportSpecifierSetProperty); parseExpression = wrapTracking(extra.parseExpression); parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration); parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration); parseFunctionExpression = wrapTracking(extra.parseFunctionExpression); parseParams = wrapTracking(extra.parseParams); - parseGlob = wrapTracking(extra.parseGlob); parseImportDeclaration = wrapTracking(extra.parseImportDeclaration); parseImportSpecifier = wrapTracking(extra.parseImportSpecifier); parseModuleDeclaration = wrapTracking(extra.parseModuleDeclaration); parseModuleBlock = wrapTracking(extra.parseModuleBlock); parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression); parseNewExpression = wrapTracking(extra.parseNewExpression); parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty); parseObjectProperty = wrapTracking(extra.parseObjectProperty); parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey); - parsePath = wrapTracking(extra.parsePath); parsePostfixExpression = wrapTracking(extra.parsePostfixExpression); parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression); parseProgram = wrapTracking(extra.parseProgram); parsePropertyFunction = wrapTracking(extra.parsePropertyFunction); parseTemplateElement = wrapTracking(extra.parseTemplateElement); @@ -6111,10 +9433,12 @@ parseStatement = wrapTracking(extra.parseStatement); parseSwitchCase = wrapTracking(extra.parseSwitchCase); parseUnaryExpression = wrapTracking(extra.parseUnaryExpression); parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration); parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier); + parseAnnotatableIdentifier = wrapTracking(extra.parseAnnotatableIdentifier); + parseTypeAnnotation = wrapTracking(extra.parseTypeAnnotation); parseMethodDefinition = wrapTracking(extra.parseMethodDefinition); parseClassDeclaration = wrapTracking(extra.parseClassDeclaration); parseClassExpression = wrapTracking(extra.parseClassExpression); parseClassBody = wrapTracking(extra.parseClassBody); parseXJSIdentifier = wrapTracking(extra.parseXJSIdentifier); @@ -6149,18 +9473,17 @@ parseFunctionSourceElements = extra.parseFunctionSourceElements; parseCatchClause = extra.parseCatchClause; parseComputedMember = extra.parseComputedMember; parseConditionalExpression = extra.parseConditionalExpression; parseConstLetDeclaration = extra.parseConstLetDeclaration; + parseExportBatchSpecifier = extra.parseExportBatchSpecifier; parseExportDeclaration = extra.parseExportDeclaration; parseExportSpecifier = extra.parseExportSpecifier; - parseExportSpecifierSetProperty = extra.parseExportSpecifierSetProperty; parseExpression = extra.parseExpression; parseForVariableDeclaration = extra.parseForVariableDeclaration; parseFunctionDeclaration = extra.parseFunctionDeclaration; parseFunctionExpression = extra.parseFunctionExpression; - parseGlob = extra.parseGlob; parseImportDeclaration = extra.parseImportDeclaration; parseImportSpecifier = extra.parseImportSpecifier; parseGroupExpression = extra.parseGroupExpression; parseLeftHandSideExpression = extra.parseLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall; @@ -6168,11 +9491,10 @@ parseModuleBlock = extra.parseModuleBlock; parseNewExpression = extra.parseNewExpression; parseNonComputedProperty = extra.parseNonComputedProperty; parseObjectProperty = extra.parseObjectProperty; parseObjectPropertyKey = extra.parseObjectPropertyKey; - parsePath = extra.parsePath; parsePostfixExpression = extra.parsePostfixExpression; parsePrimaryExpression = extra.parsePrimaryExpression; parseProgram = extra.parseProgram; parsePropertyFunction = extra.parsePropertyFunction; parseTemplateElement = extra.parseTemplateElement; @@ -6181,10 +9503,12 @@ parseStatement = extra.parseStatement; parseSwitchCase = extra.parseSwitchCase; parseUnaryExpression = extra.parseUnaryExpression; parseVariableDeclaration = extra.parseVariableDeclaration; parseVariableIdentifier = extra.parseVariableIdentifier; + parseAnnotatableIdentifier = extra.parseAnnotatableIdentifier; + parseTypeAnnotation = extra.parseTypeAnnotation; parseMethodDefinition = extra.parseMethodDefinition; parseClassDeclaration = extra.parseClassDeclaration; parseClassExpression = extra.parseClassExpression; parseClassBody = extra.parseClassBody; parseXJSIdentifier = extra.parseXJSIdentifier; @@ -6240,10 +9564,11 @@ lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { + allowDefault: true, allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false @@ -6340,10 +9665,11 @@ lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { + allowDefault: false, allowIn: true, labelSet: {}, parenthesizedCount: 0, inFunctionBody: false, inIteration: false, @@ -6444,34 +9770,60 @@ }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ -},{}],5:[function(require,module,exports){ +},{}],7:[function(require,module,exports){ +var Base62 = (function (my) { + my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] + + my.encode = function(i){ + if (i === 0) {return '0'} + var s = '' + while (i > 0) { + s = this.chars[i % 62] + s + i = Math.floor(i/62) + } + return s + }; + my.decode = function(a,b,c,d){ + for ( + b = c = ( + a === (/\W|_|^$/.test(a += "") || a) + ) - 1; + d = a.charCodeAt(c++); + ) + b = b * 62 + d - [, 48, 29, 87][d >> 5]; + return b + }; + + return my; +}({})); + +module.exports = Base62 +},{}],8:[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":10,"./source-map/source-map-generator":11,"./source-map/source-node":12}],6:[function(require,module,exports){ +},{"./source-map/source-map-consumer":13,"./source-map/source-map-generator":14,"./source-map/source-node":15}],9:[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); + var define = require('amdefine')(module); } 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. @@ -6482,52 +9834,64 @@ } /** * Static method for creating ArraySet instances from an existing array. */ - ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + ArraySet.fromArray = function ArraySet_fromArray(aArray) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); + set.add(aArray[i]); } return set; }; /** + * Because behavior goes wacky when you set `__proto__` on `this._set`, 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 + */ + ArraySet.prototype._toSetString = function ArraySet__toSetString (aStr) { + return "$" + aStr; + }; + + /** * 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); + ArraySet.prototype.add = function ArraySet_add(aStr) { + if (this.has(aStr)) { + // Already a member; nothing to do. + return; } - if (!isDuplicate) { - this._set[util.toSetString(aStr)] = idx; - } + var idx = this._array.length; + this._array.push(aStr); + this._set[this._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)); + this._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)]; + return this._set[this._toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** @@ -6553,11 +9917,11 @@ exports.ArraySet = ArraySet; }); -},{"./util":13,"amdefine":14}],7:[function(require,module,exports){ +},{"amdefine":17}],10:[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 @@ -6591,11 +9955,11 @@ * 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); + var define = require('amdefine')(module); } define(function (require, exports, module) { var base64 = require('./base64'); @@ -6699,19 +10063,19 @@ }; }; }); -},{"./base64":8,"amdefine":14}],8:[function(require,module,exports){ +},{"./base64":11,"amdefine":17}],11:[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); + var define = require('amdefine')(module); } define(function (require, exports, module) { var charToIntMap = {}; var intToCharMap = {}; @@ -6743,19 +10107,19 @@ throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); -},{"amdefine":14}],9:[function(require,module,exports){ +},{"amdefine":17}],12:[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); + var define = require('amdefine')(module); } define(function (require, exports, module) { /** * Recursive implementation of binary search. @@ -6776,11 +10140,11 @@ // // 3. We did not find the exact element, and there is no next-closest // element which is less than the one we are searching for, so we // return null. var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); + var cmp = aCompare(aNeedle, aHaystack[mid]); if (cmp === 0) { // Found the element we are looking for. return aHaystack[mid]; } else if (cmp > 0) { @@ -6826,19 +10190,19 @@ : null; }; }); -},{"amdefine":14}],10:[function(require,module,exports){ +},{"amdefine":17}],13:[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); + var define = require('amdefine')(module); } define(function (require, exports, module) { var util = require('./util'); var binarySearch = require('./binary-search'); @@ -6856,11 +10220,10 @@ * * - 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: The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * @@ -6881,139 +10244,71 @@ 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 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); + var file = util.getArg(sourceMap, 'file'); - // 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) { + if (version !== this._version) { throw new Error('Unsupported version: ' + version); } - // 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._names = ArraySet.fromArray(names); + this._sources = ArraySet.fromArray(sources); + this._sourceRoot = sourceRoot; this.file = file; + + // `this._generatedMappings` and `this._originalMappings` hold the parsed + // mapping coordinates from the source map's "mappings" attribute. Each + // object in the array 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`. + // + // `this._generatedMappings` is ordered by the generated positions. + // + // `this._originalMappings` is ordered by the original positions. + this._generatedMappings = []; + this._originalMappings = []; + this._parseMappings(mappings, sourceRoot); } /** - * Create a SourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns SourceMapConsumer - */ - SourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(SourceMapConsumer.prototype); - - smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - 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; - - smc.__generatedMappings = aSourceMap._mappings.slice() - .sort(util.compareByGeneratedPositions); - smc.__originalMappings = aSourceMap._mappings.slice() - .sort(util.compareByOriginalPositions); - - return smc; - }; - - /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(SourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { - return this.sourceRoot ? util.join(this.sourceRoot, s) : s; + return this._sourceRoot ? util.join(this._sourceRoot, s) : s; }, this); } }); - // `__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.__generatedMappings = []; - this.__originalMappings = []; - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } - }); - - SourceMapConsumer.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this.__generatedMappings = []; - this.__originalMappings = []; - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } - }); - /** * 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). + * query (an ordered list in this._generatedMappings). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; @@ -7046,11 +10341,16 @@ str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original source. temp = base64VLQ.decode(str); - mapping.source = this._sources.at(previousSource + temp.value); + if (aSourceRoot) { + mapping.source = util.join(aSourceRoot, this._sources.at(previousSource + temp.value)); + } + else { + mapping.source = this._sources.at(previousSource + temp.value); + } previousSource += temp.value; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source, but no line and column'); } @@ -7079,21 +10379,49 @@ previousName += temp.value; str = temp.rest; } } - this.__generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - this.__originalMappings.push(mapping); - } + this._generatedMappings.push(mapping); + this._originalMappings.push(mapping); } } - this.__originalMappings.sort(util.compareByOriginalPositions); + this._originalMappings.sort(this._compareOriginalPositions); }; /** + * Comparator between two mappings where the original positions are compared. + */ + SourceMapConsumer.prototype._compareOriginalPositions = + function SourceMapConsumer_compareOriginalPositions(mappingA, mappingB) { + if (mappingA.source > mappingB.source) { + return 1; + } + else if (mappingA.source < mappingB.source) { + return -1; + } + else { + var cmp = mappingA.originalLine - mappingB.originalLine; + return cmp === 0 + ? mappingA.originalColumn - mappingB.originalColumn + : cmp; + } + }; + + /** + * Comparator between two mappings where the generated positions are compared. + */ + SourceMapConsumer.prototype._compareGeneratedPositions = + function SourceMapConsumer_compareGeneratedPositions(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + return cmp === 0 + ? mappingA.generatedColumn - mappingB.generatedColumn + : cmp; + }; + + /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, @@ -7139,19 +10467,15 @@ var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", - util.compareByGeneratedPositions); + this._compareGeneratedPositions) if (mapping) { - var source = util.getArg(mapping, 'source', null); - if (source && this.sourceRoot) { - source = util.join(this.sourceRoot, source); - } return { - source: source, + source: util.getArg(mapping, 'source', null), line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } @@ -7163,51 +10487,10 @@ name: 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. - */ - SourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot - && (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)]; - } - } - - 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. @@ -7225,19 +10508,15 @@ source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; - if (this.sourceRoot) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", - util.compareByOriginalPositions); + this._compareOriginalPositions) if (mapping) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null) @@ -7256,11 +10535,12 @@ /** * 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. + * The function that is called with each mapping. This function should + * not mutate the 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 @@ -7284,40 +10564,26 @@ break; default: throw new Error("Unknown order of iteration."); } - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source; - if (source && sourceRoot) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name - }; - }).forEach(aCallback, context); + mappings.forEach(aCallback, context); }; exports.SourceMapConsumer = SourceMapConsumer; }); -},{"./array-set":6,"./base64-vlq":7,"./binary-search":9,"./util":13,"amdefine":14}],11:[function(require,module,exports){ +},{"./array-set":9,"./base64-vlq":10,"./binary-search":12,"./util":16,"amdefine":17}],14:[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); + var define = require('amdefine')(module); } define(function (require, exports, module) { var base64VLQ = require('./base64-vlq'); var util = require('./util'); @@ -7335,63 +10601,15 @@ this._file = util.getArg(aArgs, 'file'); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = []; - 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) { - newMapping.source = mapping.source; - if (sourceRoot) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content) { - 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. @@ -7415,124 +10633,18 @@ if (name && !this._names.has(name)) { this._names.add(name); } this._mappings.push({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, + generated: generated, + original: original, 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) { - 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 { - // 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. - */ - SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (!aSourceFile) { - aSourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "aSourceFile" relative if an absolute Url is passed. - if (sourceRoot) { - aSourceFile = util.relative(sourceRoot, aSourceFile); - } - // 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 "aSourceFile" - this._mappings.forEach(function (mapping) { - if (mapping.source === aSourceFile && mapping.originalLine) { - // 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 - if (sourceRoot) { - mapping.source = util.relative(sourceRoot, original.source); - } else { - mapping.source = original.source; - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name !== null && mapping.name !== null) { - // Only use the identifier name if it's an identifier - // in both SourceMaps - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name && !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) { - if (sourceRoot) { - 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 @@ -7557,16 +10669,11 @@ && aSource) { // Cases 2 and 3. return; } else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - orginal: aOriginal, - name: aName - })); + throw new Error('Invalid mapping.'); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs @@ -7581,53 +10688,55 @@ var previousName = 0; var previousSource = 0; var result = ''; var mapping; - // The mappings must be guaranteed to be in sorted order before we start + // The mappings must be guarenteed to be in sorted order before we start // serializing them or else the generated line numbers (which are defined // via the ';' separators) will be all messed up. Note: it might be more // performant to maintain the sorting as we insert them, rather than as we // serialize them, but the big O is the same either way. - this._mappings.sort(util.compareByGeneratedPositions); + this._mappings.sort(function (mappingA, mappingB) { + var cmp = mappingA.generated.line - mappingB.generated.line; + return cmp === 0 + ? mappingA.generated.column - mappingB.generated.column + : cmp; + }); for (var i = 0, len = this._mappings.length; i < len; i++) { mapping = this._mappings[i]; - if (mapping.generatedLine !== previousGeneratedLine) { + if (mapping.generated.line !== previousGeneratedLine) { previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { + while (mapping.generated.line !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { - if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { - continue; - } result += ','; } } - result += base64VLQ.encode(mapping.generatedColumn + result += base64VLQ.encode(mapping.generated.column - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; + previousGeneratedColumn = mapping.generated.column; - if (mapping.source) { + if (mapping.source && mapping.original) { 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 + result += base64VLQ.encode(mapping.original.line - 1 - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; + previousOriginalLine = mapping.original.line - 1; - result += base64VLQ.encode(mapping.originalColumn + result += base64VLQ.encode(mapping.original.column - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; + previousOriginalColumn = mapping.original.column; if (mapping.name) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); @@ -7636,27 +10745,10 @@ } return result; }; - SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot) { - 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() { @@ -7668,14 +10760,10 @@ mappings: this._serializeMappings() }; if (this._sourceRoot) { 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. @@ -7687,24 +10775,23 @@ exports.SourceMapGenerator = SourceMapGenerator; }); -},{"./array-set":6,"./base64-vlq":7,"./util":13,"amdefine":14}],12:[function(require,module,exports){ +},{"./array-set":9,"./base64-vlq":10,"./util":16,"amdefine":17}],15:[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); + var define = require('amdefine')(module); } define(function (require, exports, module) { var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; - var util = require('./util'); /** * 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. @@ -7712,126 +10799,20 @@ * @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) { + function SourceNode(aLine, aColumn, aSource, aChunks) { this.children = []; - this.sourceContents = {}; - this.line = aLine === undefined ? null : aLine; - this.column = aColumn === undefined ? null : aColumn; - this.source = aSource === undefined ? null : aSource; - this.name = aName === undefined ? null : aName; + this.line = aLine; + this.column = aColumn; + this.source = aSource; 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 - */ - SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // The generated code - // Processed fragments are removed from this array. - var remainingLines = aGeneratedCode.split('\n'); - - // 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 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(remainingLines.shift() + "\n"); - 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; - } - } else { - // 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 full lines with "lastMapping" - do { - code += remainingLines.shift() + "\n"; - lastGeneratedLine++; - lastGeneratedColumn = 0; - } while (lastGeneratedLine < mapping.generatedLine); - // When we reached the correct line, we add code until we - // reach the correct column too. - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[0]; - code += nextLine.substr(0, mapping.generatedColumn); - remainingLines[0] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - // Create the SourceNode. - addMappingWithCode(lastMapping, code); - } 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); - } - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - // Associate the remaining code in the current line with "lastMapping" - // and add the remaining lines without any mapping - addMappingWithCode(lastMapping, remainingLines.join("\n")); - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content) { - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - mapping.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. */ @@ -7883,25 +10864,20 @@ * 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]; + this.children.forEach(function (chunk) { if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); + aFn(chunk, { source: this.source, line: this.line, column: this.column }); } } - } + }, this); }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. @@ -7909,11 +10885,11 @@ * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; - var len = this.children.length; + var len = this.children.length if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); @@ -7944,42 +10920,10 @@ } 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] instanceof SourceNode) { - 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 = ""; @@ -7998,81 +10942,53 @@ 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) { + if (original.source != null + && original.line != null + && original.column != null) { map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, generated: { line: generated.line, column: generated.column } }); - lastOriginalSource = null; - sourceMappingActive = false; } - chunk.split('').forEach(function (ch) { - if (ch === '\n') { + chunk.split('').forEach(function (char) { + if (char === '\n') { generated.line++; generated.column = 0; } else { generated.column++; } }); }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); -},{"./source-map-generator":11,"./util":13,"amdefine":14}],13:[function(require,module,exports){ +},{"./source-map-generator":14,"amdefine":17}],16:[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); + var define = require('amdefine')(module); } define(function (require, exports, module) { /** * This is a helper function for getting values from parameter/options @@ -8093,186 +11009,21 @@ 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[3], - host: match[4], - port: match[6], - path: match[7] - }; - } - exports.urlParse = urlParse; - - function urlGenerate(aParsedUrl) { - var url = aParsedUrl.scheme + "://"; - 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; - function join(aRoot, aPath) { - var url; - - if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { - return aPath; - } - - if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { - url.path = aPath; - return urlGenerate(url); - } - - return aRoot.replace(/\/$/, '') + '/' + aPath; + return aPath.charAt(0) === '/' + ? aPath + : aRoot.replace(/\/*$/, '') + '/' + aPath; } exports.join = join; - /** - * 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; - - function relative(aRoot, aPath) { - aRoot = aRoot.replace(/\/$/, ''); - - var url = urlParse(aRoot); - if (aPath.charAt(0) == "/" && url && url.path == "/") { - return aPath.slice(1); - } - - return aPath.indexOf(aRoot + '/') === 0 - ? aPath.substr(aRoot.length + 1) - : aPath; - } - exports.relative = relative; - - function strcmp(aStr1, aStr2) { - var s1 = aStr1 || ""; - var s2 = aStr2 || ""; - return (s1 > s2) - (s1 < s2); - } - - /** - * 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; - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp || onlyCompareOriginal) { - return cmp; - } - - cmp = strcmp(mappingA.name, mappingB.name); - if (cmp) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp) { - return cmp; - } - - return mappingA.generatedColumn - mappingB.generatedColumn; - }; - exports.compareByOriginalPositions = compareByOriginalPositions; - - /** - * Comparator between two mappings 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 compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { - var cmp; - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - }; - exports.compareByGeneratedPositions = compareByGeneratedPositions; - }); -},{"amdefine":14}],14:[function(require,module,exports){ -var process=require("__browserify_process"),__filename="/../node_modules/source-map/node_modules/amdefine/amdefine.js";/** vim: et:ts=4:sw=4:sts=4 +},{"amdefine":17}],17:[function(require,module,exports){ +var process=require("__browserify_process"),__filename="/../node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js";/** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/amdefine for details */ @@ -8568,11 +11319,11 @@ return define; } module.exports = amdefine; -},{"__browserify_process":3,"path":2}],15:[function(require,module,exports){ +},{"__browserify_process":5,"path":2}],18:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -8584,109 +11335,12 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -/* jshint browser: true */ -/* jslint evil: true */ -'use strict'; -var runScripts; -var headEl; - -var transform = require('./fbtransform/lib/transform').transform; -var visitors = require('./fbtransform/visitors').transformVisitors; -var transform = transform.bind(null, visitors.react); -var docblock = require('./fbtransform/lib/docblock'); - - -exports.transform = transform; - -exports.exec = function(code) { - return eval(transform(code)); -}; - -if (typeof window === "undefined" || window === null) { - return; -} -headEl = document.getElementsByTagName('head')[0]; - -var run = exports.run = function(code) { - var jsx = docblock.parseAsObject(docblock.extract(code)).jsx; - - var functionBody = jsx ? transform(code).code : code; - var scriptEl = document.createElement('script'); - - scriptEl.innerHTML = functionBody; - headEl.appendChild(scriptEl); -}; - -var load = exports.load = function(url, callback) { - var xhr; - xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') - : new XMLHttpRequest(); - // Disable async since we need to execute scripts in the order they are in the - // DOM to mirror normal script loading. - xhr.open('GET', url, false); - if ('overrideMimeType' in xhr) { - xhr.overrideMimeType('text/plain'); - } - xhr.onreadystatechange = function() { - if (xhr.readyState === 4) { - if (xhr.status === 0 || xhr.status === 200) { - run(xhr.responseText); - } else { - throw new Error("Could not load " + url); - } - if (callback) { - return callback(); - } - } - }; - return xhr.send(null); -}; - -runScripts = function() { - var scripts = document.getElementsByTagName('script'); - scripts = Array.prototype.slice.call(scripts); - var jsxScripts = scripts.filter(function(script) { - return script.type === 'text/jsx'; - }); - - jsxScripts.forEach(function(script) { - if (script.src) { - load(script.src); - } else { - run(script.innerHTML); - } - }); -}; - -if (window.addEventListener) { - window.addEventListener('DOMContentLoaded', runScripts, false); -} else { - window.attachEvent('onload', runScripts); -} - -},{"./fbtransform/lib/docblock":16,"./fbtransform/lib/transform":17,"./fbtransform/visitors":23}],16:[function(require,module,exports){ -/** - * Copyright 2013 Facebook, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -var docblockRe = /^\s*(\/\*\*(.|\n)*?\*\/)/; +var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/; var ltrimRe = /^\s*/; /** * @param {String} contents * @return {String} */ @@ -8700,13 +11354,13 @@ var commentStartRe = /^\/\*\*?/; var commentEndRe = /\*\/$/; var wsRe = /[\t ]+/g; -var stringStartRe = /(\n|^) *\*/g; -var multilineRe = /(?:^|\n) *(@[^\n]*?) *\n *([^@\n\s][^@\n]+?) *\n/g; -var propertyRe = /(?:^|\n) *@(\S+) *([^\n]*)/g; +var stringStartRe = /(\r?\n|^) *\*/g; +var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g; +var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; /** * @param {String} contents * @return {Array} */ @@ -8753,11 +11407,11 @@ exports.extract = extract; exports.parse = parse; exports.parseAsObject = parseAsObject; -},{}],17:[function(require,module,exports){ +},{}],19:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -8769,138 +11423,244 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -/*global exports:true*/ + + /*jslint node: true*/ "use strict"; /** * Syntax transfomer for javascript. Takes the source in, spits the source - * out. Tries to maintain readability and preserve whitespace and line numbers - * where posssible. + * out. * - * Support - * - ES6 class transformation + private property munging, see ./classes.js - * - React XHP style syntax transformations, see ./react.js - * - Bolt XHP style syntax transformations, see ./bolt.js - * - * The general flow is the following: - * - Parse the source with our customized esprima-parser - * https://github.com/voloko/esprima. We have to customize the parser to - * support non-standard XHP-style syntax. We parse the source range: true - * option that forces esprima to return positions in the source within - * resulting parse tree. - * - * - Traverse resulting syntax tree, trying to apply a set of visitors to each - * node. Each visitor should provide a .test() function that tests if the - * visitor can process a given node. - * - * - Visitor is responsible for code generation for a given syntax node. - * Generated code is stored in state.g.buffer that is passed to every - * visitor. It's up to the visitor to process the code the way it sees fit. - * All of the current visitors however use both the node and the original - * source to generate transformed code. They use nodes to generate new - * code and they copy the original source, preserving whitespace and comments, - * for the parts they don't care about. + * Parses input source with esprima, applies the given list of visitors to the + * AST tree, and returns the resulting output. */ -var esprima = require('esprima'); +var esprima = require('esprima-fb'); var createState = require('./utils').createState; var catchup = require('./utils').catchup; +var updateState = require('./utils').updateState; +var analyzeAndTraverse = require('./utils').analyzeAndTraverse; +var Syntax = esprima.Syntax; + /** - * @param {object} object + * @param {object} node + * @param {object} parentNode + * @return {boolean} + */ +function _nodeIsClosureScopeBoundary(node, parentNode) { + if (node.type === Syntax.Program) { + return true; + } + + var parentIsFunction = + parentNode.type === Syntax.FunctionDeclaration + || parentNode.type === Syntax.FunctionExpression; + + return node.type === Syntax.BlockStatement && parentIsFunction; +} + +function _nodeIsBlockScopeBoundary(node, parentNode) { + if (node.type === Syntax.Program) { + return false; + } + + return node.type === Syntax.BlockStatement + && parentNode.type === Syntax.CatchClause; +} + +/** + * @param {object} node * @param {function} visitor * @param {array} path * @param {object} state */ -function traverse(object, path, state) { - var key, child; +function traverse(node, path, state) { + // Create a scope stack entry if this is the first node we've encountered in + // its local scope + var parentNode = path[0]; + if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) { + if (_nodeIsClosureScopeBoundary(node, parentNode)) { + var scopeIsStrict = + state.scopeIsStrict + || node.body.length > 0 + && node.body[0].type === Syntax.ExpressionStatement + && node.body[0].expression.type === Syntax.Literal + && node.body[0].expression.value === 'use strict'; - if (walker(traverse, object, path, state) === false) { - return; - } - path.unshift(object); - for (key in object) { - // skip obviously wrong attributes - if (key === 'range' || key === 'loc') { - continue; + if (node.type === Syntax.Program) { + state = updateState(state, { + scopeIsStrict: scopeIsStrict + }); + } else { + state = updateState(state, { + localScope: { + parentNode: parentNode, + parentScope: state.localScope, + identifiers: {} + }, + scopeIsStrict: scopeIsStrict + }); + + // All functions have an implicit 'arguments' object in scope + state.localScope.identifiers['arguments'] = true; + + // Include function arg identifiers in the scope boundaries of the + // function + if (parentNode.params.length > 0) { + var param; + for (var i = 0; i < parentNode.params.length; i++) { + param = parentNode.params[i]; + if (param.type === Syntax.Identifier) { + state.localScope.identifiers[param.name] = true; + } + } + } + + // Named FunctionExpressions scope their name within the body block of + // themselves only + if (parentNode.type === Syntax.FunctionExpression && parentNode.id) { + state.localScope.identifiers[parentNode.id.name] = true; + } + } + + // Traverse and find all local identifiers in this closure first to + // account for function/variable declaration hoisting + collectClosureIdentsAndTraverse(node, path, state); } - if (object.hasOwnProperty(key)) { - child = object[key]; - if (typeof child === 'object' && child !== null) { - child.range && catchup(child.range[0], state); - traverse(child, path, state); - child.range && catchup(child.range[1], state); + + if (_nodeIsBlockScopeBoundary(node, parentNode)) { + state = updateState(state, { + localScope: { + parentNode: parentNode, + parentScope: state.localScope, + identifiers: {} + } + }); + + if (parentNode.type === Syntax.CatchClause) { + state.localScope.identifiers[parentNode.param.name] = true; } + collectBlockIdentsAndTraverse(node, path, state); } } - path.shift(); + + // Only catchup() before and after traversing a child node + function traverser(node, path, state) { + node.range && catchup(node.range[0], state); + traverse(node, path, state); + node.range && catchup(node.range[1], state); + } + + analyzeAndTraverse(walker, traverser, node, path, state); } -function walker(traverse, object, path, state) { +function collectClosureIdentsAndTraverse(node, path, state) { + analyzeAndTraverse( + visitLocalClosureIdentifiers, + collectClosureIdentsAndTraverse, + node, + path, + state + ); +} + +function collectBlockIdentsAndTraverse(node, path, state) { + analyzeAndTraverse( + visitLocalBlockIdentifiers, + collectBlockIdentsAndTraverse, + node, + path, + state + ); +} + +function visitLocalClosureIdentifiers(node, path, state) { + var identifiers = state.localScope.identifiers; + switch (node.type) { + case Syntax.FunctionExpression: + // Function expressions don't get their names (if there is one) added to + // the closure scope they're defined in + return false; + case Syntax.ClassDeclaration: + case Syntax.ClassExpression: + case Syntax.FunctionDeclaration: + if (node.id) { + identifiers[node.id.name] = true; + } + return false; + case Syntax.VariableDeclarator: + if (path[0].kind === 'var') { + identifiers[node.id.name] = true; + } + break; + } +} + +function visitLocalBlockIdentifiers(node, path, state) { + // TODO: Support 'let' here...maybe...one day...or something... + if (node.type === Syntax.CatchClause) { + return false; + } +} + +function walker(node, path, state) { var visitors = state.g.visitors; for (var i = 0; i < visitors.length; i++) { - if (visitors[i].test(object, path, state)) { - return visitors[i](traverse, object, path, state); + if (visitors[i].test(node, path, state)) { + return visitors[i](traverse, node, path, state); } } } -function runPass(source, visitors, options) { +/** + * Applies all available transformations to the source + * @param {array} visitors + * @param {string} source + * @param {?object} options + * @return {object} + */ +function transform(visitors, source, options) { + options = options || {}; + var ast; try { - ast = esprima.parse(source, { comment: true, loc: true, range: true }); + ast = esprima.parse(source, { + comment: true, + loc: true, + range: true + }); } catch (e) { e.message = 'Parse Error: ' + e.message; throw e; } - var state = createState(source, options); - state.g.originalProgramAST = ast; + var state = createState(source, ast, options); state.g.visitors = visitors; if (options.sourceMap) { var SourceMapGenerator = require('source-map').SourceMapGenerator; - state.g.sourceMap = new SourceMapGenerator({ file: 'transformed.js' }); + state.g.sourceMap = new SourceMapGenerator({file: 'transformed.js'}); } + traverse(ast, [], state); catchup(source.length, state); - return state; -} -/** - * Applies all available transformations to the source - * @param {array} visitors - * @param {string} source - * @param {?object} options - * @return {object} - */ -function transform(visitors, source, options) { - options = options || {}; - - var state = runPass(source, visitors, options); - var sourceMap = state.g.sourceMap; - - if (sourceMap) { - return { - sourceMap: sourceMap, - sourceMapFilename: options.filename || 'source.js', - code: state.g.buffer - }; - } else { - return { - code: state.g.buffer - }; + var ret = {code: state.g.buffer}; + if (options.sourceMap) { + ret.sourceMap = state.g.sourceMap; + ret.sourceMapFilename = options.filename || 'source.js'; } + return ret; } - exports.transform = transform; -},{"./utils":18,"esprima":4,"source-map":5}],18:[function(require,module,exports){ +},{"./utils":20,"esprima-fb":6,"source-map":8}],20:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -8912,36 +11672,64 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -/*global exports:true*/ + +/*jslint node: true*/ + /** - * State represents the given parser state. It has a local and global parts. - * Global contains parser position, source, etc. Local contains scope based - * properties, like current class name. State should contain all the info - * required for transformation. It's the only mandatory object that is being - * passed to every function in transform chain. + * A `state` object represents the state of the parser. It has "local" and + * "global" parts. Global contains parser position, source, etc. Local contains + * scope based properties like current class name. State should contain all the + * info required for transformation. It's the only mandatory object that is + * being passed to every function in transform chain. * - * @param {String} source - * @param {Object} transformOptions - * @return {Object} + * @param {string} source + * @param {object} transformOptions + * @return {object} */ -function createState(source, transformOptions) { +function createState(source, rootNode, transformOptions) { return { /** - * Name of the super class variable + * A tree representing the current local scope (and its lexical scope chain) + * Useful for tracking identifiers from parent scopes, etc. + * @type {Object} + */ + localScope: { + parentNode: rootNode, + parentScope: null, + identifiers: {} + }, + /** + * The name (and, if applicable, expression) of the super class + * @type {Object} + */ + superClass: null, + /** + * The namespace to use when munging identifiers * @type {String} */ - superVar: '', + mungeNamespace: '', /** - * Name of the enclosing class scope + * Ref to the node for the FunctionExpression of the enclosing + * MethodDefinition + * @type {Object} + */ + methodFuncNode: null, + /** + * Name of the enclosing class * @type {String} */ - scopeName: '', + className: null, /** + * Whether we're currently within a `strict` scope + * @type {Bool} + */ + scopeIsStrict: null, + /** * Global state (not affected by updateState) * @type {Object} */ g: { /** @@ -9035,29 +11823,30 @@ } /** * Updates a copy of a given state with "update" and returns an updated state. * - * @param {Object} state - * @param {Object} update - * @return {Object} + * @param {object} state + * @param {object} update + * @return {object} */ function updateState(state, update) { - return { - g: state.g, - superVar: update.superVar || state.superVar, - scopeName: update.scopeName || state.scopeName - }; + var ret = Object.create(state); + Object.keys(update).forEach(function(updatedKey) { + ret[updatedKey] = update[updatedKey]; + }); + return ret; } /** * Given a state fill the resulting buffer from the original source up to * the end - * @param {Number} end - * @param {Object} state - * @param {Function?} contentTransformer Optional callback to transform newly - * added content. + * + * @param {number} end + * @param {object} state + * @param {?function} contentTransformer Optional callback to transform newly + * added content. */ function catchup(end, state, contentTransformer) { if (end < state.g.position) { // cannot move backwards return; @@ -9106,30 +11895,52 @@ contentTransformer ? contentTransformer(transformed) : transformed; state.g.position = end; } /** - * Applies `catchup` but passing in a function that removes any non-whitespace - * characters. + * Removes all non-whitespace characters */ -var re = /(\S)/g; +var reNonWhite = /(\S)/g; function stripNonWhite(value) { - return value.replace(re, function() { + return value.replace(reNonWhite, function() { return ''; }); } + /** - * Catches up as `catchup` but turns each non-white character into a space. + * Catches up as `catchup` but removes all non-whitespace characters. */ function catchupWhiteSpace(end, state) { catchup(end, state, stripNonWhite); } /** + * Removes all non-newline characters + */ +var reNonNewline = /[^\n]/g; +function stripNonNewline(value) { + return value.replace(reNonNewline, function() { + return ''; + }); +} + +/** + * Catches up as `catchup` but removes all non-newline characters. + * + * Equivalent to appending as many newlines as there are in the original source + * between the current position and `end`. + */ +function catchupNewlines(end, state) { + catchup(end, state, stripNonNewline); +} + + +/** * Same as catchup but does not touch the buffer - * @param {Number} end - * @param {Object} state + * + * @param {number} end + * @param {object} state */ function move(end, state) { // move the internal cursors if (state.g.sourceMap) { if (end < state.g.position) { @@ -9149,38 +11960,39 @@ state.g.position = end; } /** * Appends a string of text to the buffer - * @param {String} string - * @param {Object} state + * + * @param {string} str + * @param {object} state */ -function append(string, state) { - if (state.g.sourceMap && string) { +function append(str, state) { + if (state.g.sourceMap && str) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); - var transformedLines = string.split('\n'); + var transformedLines = str.split('\n'); if (transformedLines.length > 1) { state.g.bufferLine += transformedLines.length - 1; state.g.bufferColumn = 0; } state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } - state.g.buffer += string; + state.g.buffer += str; } /** * Update indent using state.indentBy property. Indent is measured in * double spaces. Updates a single line only. * - * @param {String} str - * @param {Object} state - * @return {String} + * @param {string} str + * @param {object} state + * @return {string} */ function updateIndent(str, state) { for (var i = 0; i < -state.g.indentBy; i++) { str = str.replace(/(^|\n)( {2}|\t)/g, '$1'); } @@ -9194,13 +12006,13 @@ * " foo.bar()" * ^ * start * indent will be 2 * - * @param {Number} start - * @param {Object} state - * @return {Number} + * @param {number} start + * @param {object} state + * @return {number} */ function indentBefore(start, state) { var end = start; start = start - 1; @@ -9220,21 +12032,116 @@ docblock.parseAsObject(docblock.extract(state.g.source)); } return state.g.docblock; } +function identWithinLexicalScope(identName, state, stopBeforeNode) { + var currScope = state.localScope; + while (currScope) { + if (currScope.identifiers[identName] !== undefined) { + return true; + } + + if (stopBeforeNode && currScope.parentNode === stopBeforeNode) { + break; + } + + currScope = currScope.parentScope; + } + return false; +} + +function identInLocalScope(identName, state) { + return state.localScope.identifiers[identName] !== undefined; +} + +function declareIdentInLocalScope(identName, state) { + state.localScope.identifiers[identName] = true; +} + +/** + * Apply the given analyzer function to the current node. If the analyzer + * doesn't return false, traverse each child of the current node using the given + * traverser function. + * + * @param {function} analyzer + * @param {function} traverser + * @param {object} node + * @param {function} visitor + * @param {array} path + * @param {object} state + */ +function analyzeAndTraverse(analyzer, traverser, node, path, state) { + var key, child; + + if (node.type) { + if (analyzer(node, path, state) === false) { + return; + } + path.unshift(node); + } + + for (key in node) { + // skip obviously wrong attributes + if (key === 'range' || key === 'loc') { + continue; + } + if (node.hasOwnProperty(key)) { + child = node[key]; + if (typeof child === 'object' && child !== null) { + traverser(child, path, state); + } + } + } + node.type && path.shift(); +} + +/** + * Checks whether a node or any of its sub-nodes contains + * a syntactic construct of the passed type. + * @param {object} node - AST node to test. + * @param {string} type - node type to lookup. + */ +function containsChildOfType(node, type) { + var foundMatchingChild = false; + function nodeTypeAnalyzer(node) { + if (node.type === type) { + foundMatchingChild = true; + return false; + } + } + function nodeTypeTraverser(child, path, state) { + if (!foundMatchingChild) { + foundMatchingChild = containsChildOfType(child, type); + } + } + analyzeAndTraverse( + nodeTypeAnalyzer, + nodeTypeTraverser, + node, + [] + ); + return foundMatchingChild; +} + +exports.append = append; exports.catchup = catchup; exports.catchupWhiteSpace = catchupWhiteSpace; -exports.append = append; +exports.catchupNewlines = catchupNewlines; +exports.containsChildOfType = containsChildOfType; +exports.createState = createState; +exports.declareIdentInLocalScope = declareIdentInLocalScope; +exports.getDocblock = getDocblock; +exports.identWithinLexicalScope = identWithinLexicalScope; +exports.identInLocalScope = identInLocalScope; +exports.indentBefore = indentBefore; exports.move = move; exports.updateIndent = updateIndent; -exports.indentBefore = indentBefore; exports.updateState = updateState; -exports.createState = createState; -exports.getDocblock = getDocblock; +exports.analyzeAndTraverse = analyzeAndTraverse; -},{"./docblock":16}],19:[function(require,module,exports){ +},{"./docblock":18}],21:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -9246,489 +12153,575 @@ * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -/*global exports:true*/ -"use strict"; +/*jslint node:true*/ + /** - * Desugarizer for ES6 minimal class proposal. See - * http://wiki.ecmascript.org/doku.php?id=harmony:proposals - * - * Does not require any runtime. Preserves whitespace and comments. - * Supports a class declaration with methods, super calls and inheritance. - * Currently does not support for getters and setters, since there's a very - * low probability we're going to use them anytime soon. - * - * Additional features: - * - Any member with private name (the name with prefix _, such _name) inside - * the class's scope will be munged. This would will to eliminate the case - * of sub-class accidentally overriding the super-class's provate properties - * also discouage people from accessing private members that they should not - * access. However, quoted property names don't get munged. - * - * class SkinnedMesh extends require('THREE').Mesh { - * - * update(camera) { - * camera.code = 'iphone' - * super.update(camera); - * } - * - * / - * * @constructor - * / - * constructor(geometry, materials) { - * super(geometry, materials); - * - * super.update(1); - * - * this.identityMatrix = new THREE.Matrix4(); - * this.bones = []; - * this.boneMatrices = []; - * this._name = 'foo'; - * } - * - * / - * * some other code - * / - * readMore() { - * - * } - * - * _doSomething() { - * - * } - * } - * - * should be converted to - * - * var SkinnedMesh = (function() { - * var __super = require('parent').Mesh; - * - * / - * * @constructor - * / - * function SkinnedMesh(geometry, materials) { - * __super.call(this, geometry, materials); - * - * __super.prototype.update.call(this, 1); - * - * this.identityMatrix = new THREE.Matrix4(); - * this.bones = []; - * this.boneMatrices = []; - * this.$SkinnedMesh_name = 'foo'; - * } - * SkinnedMesh.prototype = Object.create(__super.prototype); - * SkinnedMesh.prototype.constructor = SkinnedMesh; - * - * / - * * @param camera - * / - * SkinnedMesh.prototype.update = function(camera) { - * camera.code = 'iphone' - * __super.prototype.update.call(this, camera); - * }; - * - * SkinnedMesh.prototype.readMore = function() { - * - * }; - * - * SkinnedMesh.prototype.$SkinnedMesh_doSomething = function() { - * - * }; - * - * return SkinnedMesh; - * })(); - * + * @typechecks */ -var Syntax = require('esprima').Syntax; +'use strict'; + var base62 = require('base62'); +var Syntax = require('esprima-fb').Syntax; +var utils = require('../src/utils'); -var catchup = require('../lib/utils').catchup; -var append = require('../lib/utils').append; -var move = require('../lib/utils').move; -var indentBefore = require('../lib/utils').indentBefore; -var updateIndent = require('../lib/utils').updateIndent; -var updateState = require('../lib/utils').updateState; +var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf'; -function findConstructorIndex(object) { - var classElements = object.body && object.body.body || []; - for (var i = 0; i < classElements.length; i++) { - if (classElements[i].type === Syntax.MethodDefinition && - classElements[i].key.name === 'constructor') { - return i; - } - } - return -1; +var _anonClassUUIDCounter = 0; +var _mungedSymbolMaps = {}; + +/** + * Used to generate a unique class for use with code-gens for anonymous class + * expressions. + * + * @param {object} state + * @return {string} + */ +function _generateAnonymousClassName(state) { + var mungeNamespace = state.mungeNamespace || ''; + return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++); } -var _mungedSymbolMaps = {}; -function getMungedName(scopeName, name, minify) { - if (minify) { - if (!_mungedSymbolMaps[scopeName]) { - _mungedSymbolMaps[scopeName] = { +/** + * Given an identifier name, munge it using the current state's mungeNamespace. + * + * @param {string} identName + * @param {object} state + * @return {string} + */ +function _getMungedName(identName, state) { + var mungeNamespace = state.mungeNamespace; + var shouldMinify = state.g.opts.minify; + + if (shouldMinify) { + if (!_mungedSymbolMaps[mungeNamespace]) { + _mungedSymbolMaps[mungeNamespace] = { symbolMap: {}, - identifierUUIDCounter: 0 + identUUIDCounter: 0 }; } - var symbolMap = _mungedSymbolMaps[scopeName].symbolMap; - if (!symbolMap[name]) { - symbolMap[name] = - base62.encode(_mungedSymbolMaps[scopeName].identifierUUIDCounter); - _mungedSymbolMaps[scopeName].identifierUUIDCounter++; + var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap; + if (!symbolMap[identName]) { + symbolMap[identName] = + base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++); } - name = symbolMap[name]; + identName = symbolMap[identName]; } - return '$' + scopeName + name; + return '$' + mungeNamespace + identName; } -function shouldMungeName(scopeName, name, state) { - // only run when @preventMunge is not present in the docblock - if (state.g.preventMunge === undefined) { - var docblock = require('../lib/docblock'); - state.g.preventMunge = docblock.parseAsObject( - docblock.extract(state.g.source)).preventMunge !== undefined; +/** + * Extracts super class information from a class node. + * + * Information includes name of the super class and/or the expression string + * (if extending from an expression) + * + * @param {object} node + * @param {object} state + * @return {object} + */ +function _getSuperClassInfo(node, state) { + var ret = { + name: null, + expression: null + }; + if (node.superClass) { + if (node.superClass.type === Syntax.Identifier) { + ret.name = node.superClass.name; + } else { + // Extension from an expression + ret.name = _generateAnonymousClassName(state); + ret.expression = state.g.source.substring( + node.superClass.range[0], + node.superClass.range[1] + ); + } } - // Starts with only a single underscore (i.e. don't count double-underscores) - return !state.g.preventMunge && scopeName ? /^_(?!_)/.test(name) : false; + return ret; } - -function getProtoOfPrototypeVariableName(superVar) { - return superVar + 'ProtoOfPrototype'; +/** + * Used with .filter() to find the constructor method in a list of + * MethodDefinition nodes. + * + * @param {object} classElement + * @return {boolean} + */ +function _isConstructorMethod(classElement) { + return classElement.type === Syntax.MethodDefinition && + classElement.key.type === Syntax.Identifier && + classElement.key.name === 'constructor'; } -function getSuperKeyName(superVar) { - return superVar + 'Key'; +/** + * @param {object} node + * @param {object} state + * @return {boolean} + */ +function _shouldMungeIdentifier(node, state) { + return ( + !!state.methodFuncNode && + !utils.getDocblock(state).hasOwnProperty('preventMunge') && + /^_(?!_)/.test(node.name) + ); } -function getSuperProtoOfPrototypeVariable(superVariableName, indent) { - var string = (indent + - 'var $proto = $superName && $superName.prototype ? ' + - '$superName.prototype : $superName;\n' - ).replace(/\$proto/g, getProtoOfPrototypeVariableName(superVariableName)) - .replace(/\$superName/g, superVariableName); - return string; +/** + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state + */ +function visitClassMethod(traverse, node, path, state) { + utils.catchup(node.range[0], state); + path.unshift(node); + traverse(node.value, path, state); + path.shift(); + return false; } +visitClassMethod.test = function(node, path, state) { + return node.type === Syntax.MethodDefinition; +}; +/** + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state + */ +function visitClassFunctionExpression(traverse, node, path, state) { + var methodNode = path[0]; -function getInheritanceSetup(superClassToken, className, indent, superName) { - var string = ''; - if (superClassToken) { - string += getStaticMethodsOnConstructorSetup(className, indent, superName); - string += getPrototypeOnConstructorSetup(className, indent, superName); - string += getConstructorPropertySetup(className, indent); + state = utils.updateState(state, { + methodFuncNode: node + }); + + if (methodNode.key.name === 'constructor') { + utils.append('function ' + state.className, state); + } else { + var methodName = methodNode.key.name; + if (_shouldMungeIdentifier(methodNode.key, state)) { + methodName = _getMungedName(methodName, state); + } + + var prototypeOrStatic = methodNode.static ? '' : 'prototype.'; + utils.append( + state.className + '.' + prototypeOrStatic + methodName + '=function', + state + ); } - return string; -} + utils.move(methodNode.key.range[1], state); -function getStaticMethodsOnConstructorSetup(className, indent, superName) { - var string = ( indent + - 'for (var $keyName in $superName) {\n' + indent + - ' if ($superName.hasOwnProperty($keyName)) {\n' + indent + - ' $className[$keyName] = $superName[$keyName];\n' + indent + - ' }\n' + indent + - '}\n') - .replace(/\$className/g, className) - .replace(/\$keyName/g, getSuperKeyName(superName)) - .replace(/\$superName/g, superName); - return string; -} + var params = node.params; + var paramName; + if (params.length > 0) { + for (var i = 0; i < params.length; i++) { + utils.catchup(node.params[i].range[0], state); + paramName = params[i].name; + if (_shouldMungeIdentifier(params[i], state)) { + paramName = _getMungedName(params[i].name, state); + } + utils.append(paramName, state); + utils.move(params[i].range[1], state); + } + } else { + utils.append('(', state); + } + utils.append(')', state); + utils.catchupWhiteSpace(node.body.range[0], state); + utils.append('{', state); + if (!state.scopeIsStrict) { + utils.append('"use strict";', state); + } + utils.move(node.body.range[0] + '{'.length, state); -function getPrototypeOnConstructorSetup(className, indent, superName) { - var string = ( indent + - '$className.prototype = Object.create($protoPrototype);\n') - .replace(/\$protoPrototype/g, getProtoOfPrototypeVariableName(superName)) - .replace(/\$className/g, className); - return string; + path.unshift(node); + traverse(node.body, path, state); + path.shift(); + utils.catchup(node.body.range[1], state); + + if (methodNode.key.name !== 'constructor') { + utils.append(';', state); + } + return false; } +visitClassFunctionExpression.test = function(node, path, state) { + return node.type === Syntax.FunctionExpression + && path[0].type === Syntax.MethodDefinition; +}; -function getConstructorPropertySetup(className, indent) { - var string = ( indent + - '$className.prototype.constructor = $className;\n') - .replace(/\$className/g, className); +/** + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state + */ +function _renderClassBody(traverse, node, path, state) { + var className = state.className; + var superClass = state.superClass; - return string; -} + // Set up prototype of constructor on same line as `extends` for line-number + // preservation. This relies on function-hoisting if a constructor function is + // defined in the class body. + if (superClass.name) { + // If the super class is an expression, we need to memoize the output of the + // expression into the generated class name variable and use that to refer + // to the super class going forward. Example: + // + // class Foo extends mixin(Bar, Baz) {} + // --transforms to-- + // function Foo() {} var ____Class0Blah = mixin(Bar, Baz); + if (superClass.expression !== null) { + utils.append( + 'var ' + superClass.name + '=' + superClass.expression + ';', + state + ); + } -function getSuperConstructorSetup(superClassToken, indent, superName) { - if (!superClassToken) return ''; - var string = ( '\n' + indent + - ' if ($superName && $superName.prototype) {\n' + indent + - ' $superName.apply(this, arguments);\n' + indent + - ' }\n' + indent) - .replace(/\$superName/g, superName); - return string; -} + var keyName = superClass.name + '____Key'; + var keyNameDeclarator = ''; + if (!utils.identWithinLexicalScope(keyName, state)) { + keyNameDeclarator = 'var '; + utils.declareIdentInLocalScope(keyName, state); + } + utils.append( + 'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' + + 'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' + + className + '[' + keyName + ']=' + + superClass.name + '[' + keyName + '];' + + '}' + + '}', + state + ); -function getMemberFunctionCall(superVar, propertyName, superArgs) { - var string = ( - '$superPrototype.$propertyName.call($superArguments)') - .replace(/\$superPrototype/g, getProtoOfPrototypeVariableName(superVar)) - .replace(/\$propertyName/g, propertyName) - .replace(/\$superArguments/g, superArgs); - return string; -} + var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name; + if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) { + utils.append( + 'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' + + 'null:' + superClass.name + '.prototype;', + state + ); + utils.declareIdentInLocalScope(superProtoIdentStr, state); + } -function getCallParams(classElement, state) { - var params = classElement.value.params; - if (!params.length) { - return ''; + utils.append( + className + '.prototype=Object.create(' + superProtoIdentStr + ');', + state + ); + utils.append( + className + '.prototype.constructor=' + className + ';', + state + ); + utils.append( + className + '.__superConstructor__=' + superClass.name + ';', + state + ); } - return state.g.source.substring( - params[0].range[0], - params[params.length - 1].range[1]); -} -function getSuperArguments(callExpression, state) { - var args = callExpression.arguments; - if (!args.length) { - return 'this'; + // If there's no constructor method specified in the class body, create an + // empty constructor function at the top (same line as the class keyword) + if (!node.body.body.filter(_isConstructorMethod).pop()) { + utils.append('function ' + className + '(){', state); + if (!state.scopeIsStrict) { + utils.append('"use strict";', state); + } + if (superClass.name) { + utils.append( + 'if(' + superClass.name + '!==null){' + + superClass.name + '.apply(this,arguments);}', + state + ); + } + utils.append('}', state); } - return 'this, ' + state.g.source.substring( - args[0].range[0], - args[args.length - 1].range[1]); + + utils.move(node.body.range[0] + '{'.length, state); + traverse(node.body, path, state); + utils.catchupWhiteSpace(node.range[1], state); } -// The seed is used to generate the name for an anonymous class, -// and this seed should be unique per browser's session. -// The value of the seed looks like this: 1229588505.2969012. -var classIDSeed = Date.now() % (60 * 60 * 1000) + Math.random(); - /** - * Generates a name for an anonymous class. The generated value looks like - * this: "Classkc6pcn_mniza1yvi" - * @param {String} scopeName - * @return {string} the scope name for Anonymous Class + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state */ -function generateAnonymousClassName(scopeName) { - classIDSeed++; - return 'Class' + - (classIDSeed).toString(36).replace('.', '_') + - (scopeName || ''); +function visitClassDeclaration(traverse, node, path, state) { + var className = node.id.name; + var superClass = _getSuperClassInfo(node, state); + + state = utils.updateState(state, { + mungeNamespace: className, + className: className, + superClass: superClass + }); + + _renderClassBody(traverse, node, path, state); + + return false; } +visitClassDeclaration.test = function(node, path, state) { + return node.type === Syntax.ClassDeclaration; +}; -function renderMethods(traverse, object, name, path, state) { - var classElements = object.body && object.body.body || []; +/** + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state + */ +function visitClassExpression(traverse, node, path, state) { + var className = node.id && node.id.name || _generateAnonymousClassName(state); + var superClass = _getSuperClassInfo(node, state); - move(object.body.range[0] + 1, state); - for (var i = 0; i < classElements.length; i++) { - if (classElements[i].key.name !== 'constructor') { - catchup(classElements[i].range[0], state); + utils.append('(function(){', state); - var memberName = classElements[i].key.name; - if (shouldMungeName(state.scopeName, memberName, state)) { - memberName = getMungedName( - state.scopeName, - memberName, - state.g.opts.minify - ); - } + state = utils.updateState(state, { + mungeNamespace: className, + className: className, + superClass: superClass + }); - var prototypeOrStatic; - if (classElements[i]['static']) { - prototypeOrStatic = ''; - } else { - prototypeOrStatic = 'prototype.'; - } + _renderClassBody(traverse, node, path, state); - append(name + '.' + prototypeOrStatic + memberName + ' = ', state); - renderMethod(traverse, classElements[i], null, path, state); - append(';', state); - } - move(classElements[i].range[1], state); - } - if (classElements.length) { - append('\n', state); - } - move(object.range[1], state); + utils.append('return ' + className + ';})()', state); + return false; } +visitClassExpression.test = function(node, path, state) { + return node.type === Syntax.ClassExpression; +}; -function renderMethod(traverse, method, name, path, state) { - append(name ? 'function ' + name + '(' : 'function(', state); - append(getCallParams(method, state) + ') {', state); - move(method.value.body.range[0] + 1, state); - traverse(method.value.body, path, state); - catchup(method.value.body.range[1] - 1, state); - append('}', state); +/** + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state + */ +function visitPrivateIdentifier(traverse, node, path, state) { + utils.append(_getMungedName(node.name, state), state); + utils.move(node.range[1], state); } +visitPrivateIdentifier.test = function(node, path, state) { + if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) { + // Always munge non-computed properties of MemberExpressions + // (a la preventing access of properties of unowned objects) + if (path[0].type === Syntax.MemberExpression && path[0].object !== node + && path[0].computed === false) { + return true; + } -function renderSuperClass(traverse, superClass, path, state) { - append('var ' + state.superVar + ' = ', state); - move(superClass.range[0], state); - traverse(superClass, path, state); - catchup(superClass.range[1], state); - append(';\n', state); -} + // Always munge identifiers that were declared within the method function + // scope + if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) { + return true; + } -function renderConstructor(traverse, object, name, indent, path, state) { - var classElements = object.body && object.body.body || []; - var constructorIndex = findConstructorIndex(object); - var constructor = constructorIndex === -1 ? - null : - classElements[constructorIndex]; - if (constructor) { - move(constructorIndex === 0 ? - object.body.range[0] + 1 : - classElements[constructorIndex - 1].range[1], state); - catchup(constructor.range[0], state); - renderMethod(traverse, constructor, name, path, state); - append('\n', state); - } else { - if (object.superClass) { - append('\n' + indent, state); + // Always munge private keys on object literals defined within a method's + // scope. + if (path[0].type === Syntax.Property + && path[1].type === Syntax.ObjectExpression) { + return true; } - append('function ', state); - if (object.id) { - move(object.id.range[0], state); + + // Always munge function parameters + if (path[0].type === Syntax.FunctionExpression + || path[0].type === Syntax.FunctionDeclaration) { + for (var i = 0; i < path[0].params.length; i++) { + if (path[0].params[i] === node) { + return true; + } + } } - append(name, state); - if (object.id) { - move(object.id.range[1], state); - } - append('(){ ', state); - if (object.body) { - move(object.body.range[0], state); - } - append(getSuperConstructorSetup( - object.superClass, - indent, - state.superVar), state); - append('}\n', state); } -} + return false; +}; -var superId = 0; -function renderClassBody(traverse, object, path, state) { - var name = object.id ? object.id.name : 'constructor'; - var superClass = object.superClass; - var indent = updateIndent( - indentBefore(object.range[0], state) + ' ', - state); +/** + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state + */ +function visitSuperCallExpression(traverse, node, path, state) { + var superClassName = state.superClass.name; - state = updateState( - state, - { - scopeName: object.id ? object.id.name : - generateAnonymousClassName(state.scopeName), - superVar: superClass ? '__super' + superId++ : '' - }); + if (node.callee.type === Syntax.Identifier) { + utils.append(superClassName + '.call(', state); + utils.move(node.callee.range[1], state); + } else if (node.callee.type === Syntax.MemberExpression) { + utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); + utils.move(node.callee.object.range[1], state); - // super class - if (superClass) { - append(indent, state); - renderSuperClass(traverse, superClass, path, state); - append(getSuperProtoOfPrototypeVariable(state.superVar, indent), state); + if (node.callee.computed) { + // ["a" + "b"] + utils.catchup(node.callee.property.range[1] + ']'.length, state); + } else { + // .ab + utils.append('.' + node.callee.property.name, state); + } + + utils.append('.call(', state); + utils.move(node.callee.range[1], state); } - renderConstructor(traverse, object, name, indent, path, state); - append(getInheritanceSetup(superClass, name, indent, state.superVar), state); - renderMethods(traverse, object, name, path, state); + utils.append('this', state); + if (node.arguments.length > 0) { + utils.append(',', state); + utils.catchupWhiteSpace(node.arguments[0].range[0], state); + traverse(node.arguments, path, state); + } + + utils.catchupWhiteSpace(node.range[1], state); + utils.append(')', state); + return false; } +visitSuperCallExpression.test = function(node, path, state) { + if (state.superClass && node.type === Syntax.CallExpression) { + var callee = node.callee; + if (callee.type === Syntax.Identifier && callee.name === 'super' + || callee.type == Syntax.MemberExpression + && callee.object.name === 'super') { + return true; + } + } + return false; +}; - /** - * @public + * @param {function} traverse + * @param {object} node + * @param {array} path + * @param {object} state */ -function visitClassExpression(traverse, object, path, state) { - var indent = updateIndent( - indentBefore(object.range[0], state) + ' ', - state); - var name = object.id ? object.id.name : 'constructor'; +function visitSuperMemberExpression(traverse, node, path, state) { + var superClassName = state.superClass.name; - append('(function() {\n', state); - renderClassBody(traverse, object, path, state); - append(indent + 'return ' + name + ';\n', state); - append(indent.substring(0, indent.length - 2) + '})()', state); - return false + utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state); + utils.move(node.object.range[1], state); } - -visitClassExpression.test = function(object, path, state) { - return object.type === Syntax.ClassExpression; +visitSuperMemberExpression.test = function(node, path, state) { + return state.superClass + && node.type === Syntax.MemberExpression + && node.object.type === Syntax.Identifier + && node.object.name === 'super'; }; +exports.visitorList = [ + visitClassDeclaration, + visitClassExpression, + visitClassFunctionExpression, + visitClassMethod, + visitPrivateIdentifier, + visitSuperCallExpression, + visitSuperMemberExpression +]; + +},{"../src/utils":20,"base62":7,"esprima-fb":6}],22:[function(require,module,exports){ /** - * @public + * Copyright 2013 Facebook, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -function visitClassDeclaration(traverse, object, path, state) { - state.g.indentBy--; - renderClassBody(traverse, object, path, state); - state.g.indentBy++; - return false; -} +/* jshint browser: true */ +/* jslint evil: true */ -visitClassDeclaration.test = function(object, path, state) { - return object.type === Syntax.ClassDeclaration; -}; +'use strict'; +var runScripts; +var headEl; +var transform = require('jstransform').transform; +var visitors = require('./fbtransform/visitors').transformVisitors; +var transform = transform.bind(null, visitors.react); +var docblock = require('jstransform/src/docblock'); -/** - * @public - */ -function visitSuperCall(traverse, object, path, state) { - if (path[0].type === Syntax.CallExpression) { - append(state.superVar + - '.call(' + getSuperArguments(path[0], state) + ')', state); - move(path[0].range[1], state); - } else if (path[0].type === Syntax.MemberExpression) { - append(getMemberFunctionCall( - state.superVar, - path[0].property.name, - getSuperArguments(path[1], state)), state); - move(path[1].range[1], state); - } - return false; + +exports.transform = transform; + +exports.exec = function(code) { + return eval(transform(code).code); +}; + +if (typeof window === "undefined" || window === null) { + return; } +headEl = document.getElementsByTagName('head')[0]; -visitSuperCall.test = function(object, path, state) { - return state.superVar && object.type === Syntax.Identifier && - object.name === 'super'; +var run = exports.run = function(code) { + var jsx = docblock.parseAsObject(docblock.extract(code)).jsx; + + var functionBody = jsx ? transform(code).code : code; + var scriptEl = document.createElement('script'); + + scriptEl.innerHTML = functionBody; + headEl.appendChild(scriptEl); }; -/** - * @public - */ -function visitPrivateProperty(traverse, object, path, state) { - var type = path[0] ? path[0].type : null; - if (type !== Syntax.Property) { - if (type === Syntax.MemberExpression) { - type = path[0].object ? path[0].object.type : null; - if (type === Syntax.Identifier && - path[0].object.range[0] === object.range[0]) { - // Identifier is a variable that appears "private". - return; +var load = exports.load = function(url, callback) { + var xhr; + xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') + : new XMLHttpRequest(); + + // Disable async since we need to execute scripts in the order they are in the + // DOM to mirror normal script loading. + xhr.open('GET', url, false); + if ('overrideMimeType' in xhr) { + xhr.overrideMimeType('text/plain'); + } + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + if (xhr.status === 0 || xhr.status === 200) { + run(xhr.responseText); + } else { + throw new Error("Could not load " + url); } - } else { - // Other syntax that are neither Property nor MemberExpression. - return; + if (callback) { + return callback(); + } } - } + }; + return xhr.send(null); +}; - var oldName = object.name; - var newName = getMungedName( - state.scopeName, - oldName, - state.g.opts.minify - ); - append(newName, state); - move(object.range[1], state); -} +runScripts = function() { + var scripts = document.getElementsByTagName('script'); + scripts = Array.prototype.slice.call(scripts); + var jsxScripts = scripts.filter(function(script) { + return script.type === 'text/jsx'; + }); -visitPrivateProperty.test = function(object, path, state) { - return object.type === Syntax.Identifier && - shouldMungeName(state.scopeName, object.name, state); + console.warn("You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx"); + + jsxScripts.forEach(function(script) { + if (script.src) { + load(script.src); + } else { + run(script.innerHTML); + } + }); }; +if (window.addEventListener) { + window.addEventListener('DOMContentLoaded', runScripts, false); +} else { + window.attachEvent('onload', runScripts); +} -exports.visitClassDeclaration = visitClassDeclaration; -exports.visitClassExpression = visitClassExpression; -exports.visitSuperCall = visitSuperCall; -exports.visitPrivateProperty = visitPrivateProperty; - -},{"../lib/docblock":16,"../lib/utils":18,"base62":1,"esprima":4}],20:[function(require,module,exports){ +},{"./fbtransform/visitors":26,"jstransform":19,"jstransform/src/docblock":18}],23:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -9743,16 +12736,17 @@ * limitations under the License. */ /*global exports:true*/ "use strict"; -var Syntax = require('esprima').Syntax; +var Syntax = require('esprima-fb').Syntax; -var catchup = require('../lib/utils').catchup; -var append = require('../lib/utils').append; -var move = require('../lib/utils').move; -var getDocblock = require('../lib/utils').getDocblock; +var catchup = require('jstransform/src/utils').catchup; +var catchupWhiteSpace = require('jstransform/src/utils').catchupWhiteSpace; +var append = require('jstransform/src/utils').append; +var move = require('jstransform/src/utils').move; +var getDocblock = require('jstransform/src/utils').getDocblock; var FALLBACK_TAGS = require('./xjs').knownTags; var renderXJSExpressionContainer = require('./xjs').renderXJSExpressionContainer; var renderXJSLiteral = require('./xjs').renderXJSLiteral; @@ -9770,15 +12764,10 @@ * Exceptions to the simple rules above: * if a property is named "class" it will be changed to "className" in the * javascript since "class" is not a valid object key in javascript. */ -var JSX_ATTRIBUTE_RENAMES = { - 'class': 'className', - cxName: 'className' -}; - var JSX_ATTRIBUTE_TRANSFORMS = { cxName: function(attr) { if (attr.value.type !== Syntax.Literal) { throw new Error("cx only accepts a string literal"); } else { @@ -9820,11 +12809,11 @@ catchup(attr.range[0], state); if (attr.name.namespace) { throw new Error( 'Namespace attributes are not supported. ReactJSX is not XML.'); } - var name = JSX_ATTRIBUTE_RENAMES[attr.name.name] || attr.name.name; + var name = attr.name.name; var isFirst = index === 0; var isLast = index === object.attributes.length - 1; if (isFirst) { append('{', state); @@ -9837,23 +12826,25 @@ state.g.buffer += 'true'; state.g.position = attr.name.range[1]; if (!isLast) { append(',', state); } - } else if (JSX_ATTRIBUTE_TRANSFORMS[attr.name.name]) { - move(attr.value.range[0], state); - append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); - move(attr.value.range[1], state); - if (!isLast) { - append(',', state); - } - } else if (attr.value.type === Syntax.Literal) { - move(attr.value.range[0], state); - renderXJSLiteral(attr.value, isLast, state); } else { - move(attr.value.range[0], state); - renderXJSExpressionContainer(traverse, attr.value, isLast, path, state); + move(attr.name.range[1], state); + // Use catchupWhiteSpace to skip over the '=' in the attribute + catchupWhiteSpace(attr.value.range[0], state); + if (JSX_ATTRIBUTE_TRANSFORMS[attr.name.name]) { + append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); + move(attr.value.range[1], state); + if (!isLast) { + append(',', state); + } + } else if (attr.value.type === Syntax.Literal) { + renderXJSLiteral(attr.value, isLast, state); + } else { + renderXJSExpressionContainer(traverse, attr.value, isLast, path, state); + } } if (isLast) { append('}', state); } @@ -9914,11 +12905,11 @@ return object.type === Syntax.XJSElement && jsx && jsx.length; }; exports.visitReactTag = visitReactTag; -},{"../lib/utils":18,"./xjs":22,"esprima":4}],21:[function(require,module,exports){ +},{"./xjs":25,"esprima-fb":6,"jstransform/src/utils":20}],24:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -9933,14 +12924,14 @@ * limitations under the License. */ /*global exports:true*/ "use strict"; -var Syntax = require('esprima').Syntax; -var catchup = require('../lib/utils').catchup; -var append = require('../lib/utils').append; -var getDocblock = require('../lib/utils').getDocblock; +var Syntax = require('esprima-fb').Syntax; +var catchup = require('jstransform/src/utils').catchup; +var append = require('jstransform/src/utils').append; +var getDocblock = require('jstransform/src/utils').getDocblock; /** * Transforms the following: * * var MyComponent = React.createClass({ @@ -9979,11 +12970,11 @@ return object.type === Syntax.VariableDeclarator && !!getDocblock(state).jsx; }; exports.visitReactDisplayName = visitReactDisplayName; -},{"../lib/utils":18,"esprima":4}],22:[function(require,module,exports){ +},{"esprima-fb":6,"jstransform/src/utils":20}],25:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -9997,14 +12988,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ "use strict"; -var append = require('../lib/utils').append; -var catchup = require('../lib/utils').catchup; -var move = require('../lib/utils').move; -var Syntax = require('esprima').Syntax; +var append = require('jstransform/src/utils').append; +var catchup = require('jstransform/src/utils').catchup; +var move = require('jstransform/src/utils').move; +var Syntax = require('esprima-fb').Syntax; var knownTags = { a: true, abbr: true, address: true, @@ -10154,10 +13145,11 @@ * "line" */ function renderXJSLiteral(object, isLast, state, start, end) { /** Added blank check filtering and triming*/ var trimmedChildValue = safeTrim(object.value); + var hasFinalNewLine = false; if (trimmedChildValue) { // head whitespace append(object.value.match(/^[\t ]*/)[0], state); if (start) { @@ -10173,11 +13165,11 @@ var lines = initialLines.filter(function(line) { return safeTrim(line).length > 0; }); var hasInitialNewLine = initialLines[0] !== lines[0]; - var hasFinalNewLine = + hasFinalNewLine = initialLines[initialLines.length - 1] !== lines[lines.length - 1]; var numLines = lines.length; lines.forEach(function (line, ii) { var lastLine = ii === numLines - 1; @@ -10185,24 +13177,22 @@ if (trimmedLine === '' && !lastLine) { append(line, state); } else { var preString = ''; var postString = ''; - var leading = ''; + var leading = line.match(/^[ \t]*/)[0]; if (ii === 0) { if (hasInitialNewLine) { preString = ' '; - leading = '\n'; + leading = '\n' + leading; } if (trimmedChildValueWithSpace.substring(0, 1) === ' ') { // If this is the first line, and the original content starts with // whitespace, place a single space at the beginning. preString = ' '; } - } else { - leading = line.match(/^[ \t]*/)[0]; } if (!lastLine || trimmedChildValueWithSpace.substr( trimmedChildValueWithSpace.length - 1, 1) === ' ' || hasFinalNewLine ) { @@ -10238,10 +13228,13 @@ if (!isLast) { append(',', state); } // tail whitespace + if (hasFinalNewLine) { + append('\n', state); + } append(object.value.match(/[ \t]*$/)[0], state); move(object.range[1], state); } function renderXJSExpressionContainer(traverse, object, isLast, path, state) { @@ -10271,35 +13264,27 @@ exports.knownTags = knownTags; exports.renderXJSExpressionContainer = renderXJSExpressionContainer; exports.renderXJSLiteral = renderXJSLiteral; exports.quoteAttrName = quoteAttrName; -},{"../lib/utils":18,"esprima":4}],23:[function(require,module,exports){ +},{"esprima-fb":6,"jstransform/src/utils":20}],26:[function(require,module,exports){ /*global exports:true*/ -var classes = require('./transforms/classes'); +var es6Classes = require('jstransform/visitors/es6-class-visitors').visitorList; var react = require('./transforms/react'); var reactDisplayName = require('./transforms/reactDisplayName'); /** * Map from transformName => orderedListOfVisitors. */ var transformVisitors = { - 'es6-classes': [ - classes.visitClassExpression, - classes.visitClassDeclaration, - classes.visitSuperCall, - classes.visitPrivateProperty + 'es6-classes': es6Classes, + 'react': [ + react.visitReactTag, + reactDisplayName.visitReactDisplayName ] }; -transformVisitors.react = transformVisitors[ - "es6-classes" -].concat([ - react.visitReactTag, - reactDisplayName.visitReactDisplayName -]); - /** * Specifies the order in which each transform should run. */ var transformRunOrder = [ 'es6-classes', @@ -10324,8 +13309,9 @@ } exports.getVisitorsList = getVisitorsList; exports.transformVisitors = transformVisitors; -},{"./transforms/classes":19,"./transforms/react":20,"./transforms/reactDisplayName":21}]},{},[15])(15) +},{"./transforms/react":23,"./transforms/reactDisplayName":24,"jstransform/visitors/es6-class-visitors":21}]},{},[22]) +(22) }); ; \ No newline at end of file