build/JSXTransformer.js in react-source-0.8.0 vs build/JSXTransformer.js in react-source-0.9.0
- old
+ new
@@ -1,227 +1,1331 @@
/**
- * JSXTransformer v0.8.0
+ * JSXTransformer v0.9.0
*/
-!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){
+!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.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){
+// shim for using process in browser
+var process = 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.
-//
+process.nextTick = (function () {
+ var canSetImmediate = typeof window !== 'undefined'
+ && window.setImmediate;
+ var canPost = typeof window !== 'undefined'
+ && window.postMessage && window.addEventListener
+ ;
-var toString = Object.prototype.toString;
-var hasOwnProperty = Object.prototype.hasOwnProperty;
+ if (canSetImmediate) {
+ return function (f) { return window.setImmediate(f) };
+ }
-// Array.isArray is supported in IE9
-function isArray(xs) {
- return toString.call(xs) === '[object Array]';
+ if (canPost) {
+ var queue = [];
+ window.addEventListener('message', function (ev) {
+ var source = ev.source;
+ if ((source === window || source === null) && ev.data === 'process-tick') {
+ ev.stopPropagation();
+ if (queue.length > 0) {
+ var fn = queue.shift();
+ fn();
+ }
+ }
+ }, true);
+
+ return function nextTick(fn) {
+ queue.push(fn);
+ window.postMessage('process-tick', '*');
+ };
+ }
+
+ return function nextTick(fn) {
+ setTimeout(fn, 0);
+ };
+})();
+
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
}
-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;
+// TODO(shtylman)
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
};
-// 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]);
+},{}],2:[function(require,module,exports){
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = Buffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192
+
+/**
+ * If `Buffer._useTypedArrays`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (compatible down to IE6)
+ */
+Buffer._useTypedArrays = (function () {
+ // Detect if browser supports Typed Arrays. Supported browsers are IE 10+,
+ // Firefox 4+, Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+.
+ if (typeof Uint8Array === 'undefined' || typeof ArrayBuffer === 'undefined')
+ return false
+
+ // Does the browser support adding properties to `Uint8Array` instances? If
+ // not, then that's the same as no `Uint8Array` support. We need to be able to
+ // add all the node Buffer API methods.
+ // Relevant Firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
+ try {
+ var arr = new Uint8Array(0)
+ arr.foo = function () { return 42 }
+ return 42 === arr.foo() &&
+ typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
+ } catch (e) {
+ return false
}
- 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);
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (subject, encoding, noZero) {
+ if (!(this instanceof Buffer))
+ return new Buffer(subject, encoding, noZero)
+
+ var type = typeof subject
+
+ // Workaround: node's base64 implementation allows for non-padded strings
+ // while base64-js does not.
+ if (encoding === 'base64' && type === 'string') {
+ subject = stringtrim(subject)
+ while (subject.length % 4 !== 0) {
+ subject = subject + '='
+ }
}
-};
-// 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);
+ // Find the length
+ var length
+ if (type === 'number')
+ length = coerce(subject)
+ else if (type === 'string')
+ length = Buffer.byteLength(subject, encoding)
+ else if (type === 'object')
+ length = coerce(subject.length) // Assume object is an array
+ else
+ throw new Error('First argument needs to be a number, array or string.')
+
+ var buf
+ if (Buffer._useTypedArrays) {
+ // Preferred: Return an augmented `Uint8Array` instance for best performance
+ buf = augment(new Uint8Array(length))
+ } else {
+ // Fallback: Return THIS instance of Buffer (created by `new`)
+ buf = this
+ buf.length = length
+ buf._isBuffer = true
}
- 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;
+ var i
+ if (Buffer._useTypedArrays && typeof Uint8Array === 'function' &&
+ subject instanceof Uint8Array) {
+ // Speed optimization -- use set if we're copying from a Uint8Array
+ buf._set(subject)
+ } else if (isArrayish(subject)) {
+ // Treat array-ish objects as a byte array
+ for (i = 0; i < length; i++) {
+ if (Buffer.isBuffer(subject))
+ buf[i] = subject.readUInt8(i)
+ else
+ buf[i] = subject[i]
+ }
+ } else if (type === 'string') {
+ buf.write(subject, 0, encoding)
+ } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
+ for (i = 0; i < length; i++) {
+ buf[i] = 0
+ }
+ }
- if (2 < arguments.length) {
- value = opt_initialValue;
- isValueSet = true;
+ return buf
+}
+
+// STATIC METHODS
+// ==============
+
+Buffer.isEncoding = function (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'binary':
+ case 'base64':
+ case 'raw':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true
+ default:
+ return false
}
- 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;
- }
+}
+
+Buffer.isBuffer = function (b) {
+ return !!(b !== null && b !== undefined && b._isBuffer)
+}
+
+Buffer.byteLength = function (str, encoding) {
+ var ret
+ str = str + ''
+ switch (encoding || 'utf8') {
+ case 'hex':
+ ret = str.length / 2
+ break
+ case 'utf8':
+ case 'utf-8':
+ ret = utf8ToBytes(str).length
+ break
+ case 'ascii':
+ case 'binary':
+ case 'raw':
+ ret = str.length
+ break
+ case 'base64':
+ ret = base64ToBytes(str).length
+ break
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ ret = str.length * 2
+ break
+ default:
+ throw new Error('Unknown encoding')
+ }
+ return ret
+}
+
+Buffer.concat = function (list, totalLength) {
+ assert(isArray(list), '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]
+ }
+
+ var i
+ if (typeof totalLength !== 'number') {
+ totalLength = 0
+ for (i = 0; i < list.length; i++) {
+ totalLength += list[i].length
}
}
- return value;
-};
+ var buf = new Buffer(totalLength)
+ var pos = 0
+ for (i = 0; i < list.length; i++) {
+ var item = list[i]
+ item.copy(buf, pos)
+ pos += item.length
+ }
+ return buf
+}
-// 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;
+// BUFFER INSTANCE METHODS
+// =======================
- // call the original function
- return str.substr(start, length);
- };
-} else {
- exports.substr = function (str, start, length) {
- return str.substr(start, length);
- };
+function _hexWrite (buf, string, offset, length) {
+ offset = Number(offset) || 0
+ var remaining = buf.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
+
+ // must be an even number of digits
+ var strLen = string.length
+ assert(strLen % 2 === 0, '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)
+ assert(!isNaN(byte), 'Invalid hex string')
+ buf[offset + i] = byte
+ }
+ Buffer._charsWritten = i * 2
+ return i
}
-// String.prototype.trim is supported in IE9
-exports.trim = function (str) {
- if (str.trim) return str.trim();
- return str.replace(/^\s+|\s+$/g, '');
-};
+function _utf8Write (buf, string, offset, length) {
+ var charsWritten = Buffer._charsWritten =
+ blitBuffer(utf8ToBytes(string), buf, offset, length)
+ return charsWritten
+}
-// 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)]));
- };
-};
+function _asciiWrite (buf, string, offset, length) {
+ var charsWritten = Buffer._charsWritten =
+ blitBuffer(asciiToBytes(string), buf, offset, length)
+ return charsWritten
+}
-// Object.create is supported in IE9
-function create(prototype, properties) {
- var object;
- if (prototype === null) {
- object = { '__proto__' : null };
+function _binaryWrite (buf, string, offset, length) {
+ return _asciiWrite(buf, string, offset, length)
+}
+
+function _base64Write (buf, string, offset, length) {
+ var charsWritten = Buffer._charsWritten =
+ blitBuffer(base64ToBytes(string), buf, offset, length)
+ return charsWritten
+}
+
+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
}
- else {
- if (typeof prototype !== 'object') {
- throw new TypeError(
- 'typeof prototype[' + (typeof prototype) + '] != \'object\''
- );
+
+ offset = Number(offset) || 0
+ var remaining = this.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
}
- var Type = function () {};
- Type.prototype = prototype;
- object = new Type();
- object.__proto__ = prototype;
}
- if (typeof properties !== 'undefined' && Object.defineProperties) {
- Object.defineProperties(object, properties);
+ encoding = String(encoding || 'utf8').toLowerCase()
+
+ switch (encoding) {
+ case 'hex':
+ return _hexWrite(this, string, offset, length)
+ case 'utf8':
+ case 'utf-8':
+ case 'ucs2': // TODO: No support for ucs2 or utf16le encodings yet
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return _utf8Write(this, string, offset, length)
+ case 'ascii':
+ return _asciiWrite(this, string, offset, length)
+ case 'binary':
+ return _binaryWrite(this, string, offset, length)
+ case 'base64':
+ return _base64Write(this, string, offset, length)
+ default:
+ throw new Error('Unknown encoding')
}
- 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);
+Buffer.prototype.toString = function (encoding, start, end) {
+ var self = this
+
+ encoding = String(encoding || 'utf8').toLowerCase()
+ start = Number(start) || 0
+ end = (end !== undefined)
+ ? Number(end)
+ : end = self.length
+
+ // Fastpath empty strings
+ if (end === start)
+ return ''
+
+ switch (encoding) {
+ case 'hex':
+ return _hexSlice(self, start, end)
+ case 'utf8':
+ case 'utf-8':
+ case 'ucs2': // TODO: No support for ucs2 or utf16le encodings yet
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return _utf8Slice(self, start, end)
+ case 'ascii':
+ return _asciiSlice(self, start, end)
+ case 'binary':
+ return _binarySlice(self, start, end)
+ case 'base64':
+ return _base64Slice(self, start, end)
+ default:
+ throw new Error('Unknown encoding')
+ }
}
-function keysShim(object) {
- if (notObject(object)) {
- throw new TypeError("Object.keys called on a non-object");
+Buffer.prototype.toJSON = function () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
}
+}
- var result = [];
- for (var name in object) {
- if (hasOwnProperty.call(object, name)) {
- result.push(name);
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function (target, target_start, start, end) {
+ var source = this
+
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (!target_start) target_start = 0
+
+ // Copy 0 bytes; we're done
+ if (end === start) return
+ if (target.length === 0 || source.length === 0) return
+
+ // Fatal error conditions
+ assert(end >= start, 'sourceEnd < sourceStart')
+ assert(target_start >= 0 && target_start < target.length,
+ 'targetStart out of bounds')
+ assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
+ assert(end >= 0 && end <= source.length, '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
+
+ // copy!
+ for (var i = 0; i < end - start; i++)
+ target[i + target_start] = this[i + start]
+}
+
+function _base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
+ }
+}
+
+function _utf8Slice (buf, start, end) {
+ var res = ''
+ var tmp = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++) {
+ if (buf[i] <= 0x7F) {
+ res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
+ tmp = ''
+ } else {
+ tmp += '%' + buf[i].toString(16)
}
}
- return result;
+
+ return res + decodeUtf8Char(tmp)
}
-// 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");
+function _asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++)
+ ret += String.fromCharCode(buf[i])
+ return ret
+}
+
+function _binarySlice (buf, start, end) {
+ return _asciiSlice(buf, start, end)
+}
+
+function _hexSlice (buf, start, end) {
+ var len = buf.length
+
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
+
+ var out = ''
+ for (var i = start; i < end; i++) {
+ out += toHex(buf[i])
}
+ return out
+}
- var result = keysShim(object);
- if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) {
- result.push('length');
+// http://nodejs.org/api/buffer.html#buffer_buf_slice_start_end
+Buffer.prototype.slice = function (start, end) {
+ var len = this.length
+ start = clamp(start, len, 0)
+ end = clamp(end, len, len)
+
+ if (Buffer._useTypedArrays) {
+ return augment(this.subarray(start, end))
+ } else {
+ var sliceLen = end - start
+ var newBuf = new Buffer(sliceLen, undefined, true)
+ for (var i = 0; i < sliceLen; i++) {
+ newBuf[i] = this[i + start]
+ }
+ return newBuf
}
- return result;
}
-var keys = typeof Object.keys === 'function' ? Object.keys : keysShim;
-var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ?
- Object.getOwnPropertyNames : propertyShim;
+// `get` will be removed in Node 0.13+
+Buffer.prototype.get = function (offset) {
+ console.log('.get() is deprecated. Access using array indexes instead.')
+ return this.readUInt8(offset)
+}
-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';
- });
+// `set` will be removed in Node 0.13+
+Buffer.prototype.set = function (v, offset) {
+ console.log('.set() is deprecated. Access using array indexes instead.')
+ return this.writeUInt8(v, offset)
+}
+
+Buffer.prototype.readUInt8 = function (offset, noAssert) {
+ if (!noAssert) {
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset < this.length, 'Trying to read beyond buffer length')
+ }
+
+ if (offset >= this.length)
+ return
+
+ return this[offset]
+}
+
+function _readUInt16 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val
+ if (littleEndian) {
+ val = buf[offset]
+ if (offset + 1 < len)
+ val |= buf[offset + 1] << 8
+ } else {
+ val = buf[offset] << 8
+ if (offset + 1 < len)
+ val |= buf[offset + 1]
+ }
+ return val
+}
+
+Buffer.prototype.readUInt16LE = function (offset, noAssert) {
+ return _readUInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt16BE = function (offset, noAssert) {
+ return _readUInt16(this, offset, false, noAssert)
+}
+
+function _readUInt32 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val
+ if (littleEndian) {
+ if (offset + 2 < len)
+ val = buf[offset + 2] << 16
+ if (offset + 1 < len)
+ val |= buf[offset + 1] << 8
+ val |= buf[offset]
+ if (offset + 3 < len)
+ val = val + (buf[offset + 3] << 24 >>> 0)
+ } else {
+ if (offset + 1 < len)
+ val = buf[offset + 1] << 16
+ if (offset + 2 < len)
+ val |= buf[offset + 2] << 8
+ if (offset + 3 < len)
+ val |= buf[offset + 3]
+ val = val + (buf[offset] << 24 >>> 0)
+ }
+ return val
+}
+
+Buffer.prototype.readUInt32LE = function (offset, noAssert) {
+ return _readUInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readUInt32BE = function (offset, noAssert) {
+ return _readUInt32(this, offset, false, noAssert)
+}
+
+Buffer.prototype.readInt8 = function (offset, noAssert) {
+ if (!noAssert) {
+ assert(offset !== undefined && offset !== null,
+ 'missing offset')
+ assert(offset < this.length, 'Trying to read beyond buffer length')
+ }
+
+ if (offset >= this.length)
+ return
+
+ var neg = this[offset] & 0x80
+ if (neg)
+ return (0xff - this[offset] + 1) * -1
+ else
+ return this[offset]
+}
+
+function _readInt16 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val = _readUInt16(buf, offset, littleEndian, true)
+ var neg = val & 0x8000
+ if (neg)
+ return (0xffff - val + 1) * -1
+ else
+ return val
+}
+
+Buffer.prototype.readInt16LE = function (offset, noAssert) {
+ return _readInt16(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt16BE = function (offset, noAssert) {
+ return _readInt16(this, offset, false, noAssert)
+}
+
+function _readInt32 (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ var val = _readUInt32(buf, offset, littleEndian, true)
+ var neg = val & 0x80000000
+ if (neg)
+ return (0xffffffff - val + 1) * -1
+ else
+ return val
+}
+
+Buffer.prototype.readInt32LE = function (offset, noAssert) {
+ return _readInt32(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readInt32BE = function (offset, noAssert) {
+ return _readInt32(this, offset, false, noAssert)
+}
+
+function _readFloat (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ return ieee754.read(buf, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.readFloatLE = function (offset, noAssert) {
+ return _readFloat(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readFloatBE = function (offset, noAssert) {
+ return _readFloat(this, offset, false, noAssert)
+}
+
+function _readDouble (buf, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
+ }
+
+ return ieee754.read(buf, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.readDoubleLE = function (offset, noAssert) {
+ return _readDouble(this, offset, true, noAssert)
+}
+
+Buffer.prototype.readDoubleBE = function (offset, noAssert) {
+ return _readDouble(this, offset, false, noAssert)
+}
+
+Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset < this.length, 'trying to write beyond buffer length')
+ verifuint(value, 0xff)
+ }
+
+ if (offset >= this.length) return
+
+ this[offset] = value
+}
+
+function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
+ verifuint(value, 0xffff)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
+ buf[offset + i] =
+ (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+ (littleEndian ? i : 1 - i) * 8
+ }
+}
+
+Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
+ _writeUInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
+ _writeUInt16(this, value, offset, false, noAssert)
+}
+
+function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
+ verifuint(value, 0xffffffff)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
+ buf[offset + i] =
+ (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+ }
+}
+
+Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
+ _writeUInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
+ _writeUInt32(this, value, offset, false, noAssert)
+}
+
+Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset < this.length, 'Trying to write beyond buffer length')
+ verifsint(value, 0x7f, -0x80)
+ }
+
+ if (offset >= this.length)
+ return
+
+ if (value >= 0)
+ this.writeUInt8(value, offset, noAssert)
+ else
+ this.writeUInt8(0xff + value + 1, offset, noAssert)
+}
+
+function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
+ verifsint(value, 0x7fff, -0x8000)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ if (value >= 0)
+ _writeUInt16(buf, value, offset, littleEndian, noAssert)
+ else
+ _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
+}
+
+Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
+ _writeInt16(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
+ _writeInt16(this, value, offset, false, noAssert)
+}
+
+function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+ verifsint(value, 0x7fffffff, -0x80000000)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ if (value >= 0)
+ _writeUInt32(buf, value, offset, littleEndian, noAssert)
+ else
+ _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
+}
+
+Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
+ _writeInt32(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
+ _writeInt32(this, value, offset, false, noAssert)
+}
+
+function _writeFloat (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
+ verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+}
+
+Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
+ _writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
+ _writeFloat(this, value, offset, false, noAssert)
+}
+
+function _writeDouble (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ assert(value !== undefined && value !== null, 'missing value')
+ assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
+ assert(offset !== undefined && offset !== null, 'missing offset')
+ assert(offset + 7 < buf.length,
+ 'Trying to write beyond buffer length')
+ verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
+
+ var len = buf.length
+ if (offset >= len)
+ return
+
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+}
+
+Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
+ _writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
+ _writeDouble(this, value, offset, false, noAssert)
+}
+
+// fill(value, start=0, end=buffer.length)
+Buffer.prototype.fill = function (value, start, end) {
+ if (!value) value = 0
+ if (!start) start = 0
+ if (!end) end = this.length
+
+ if (typeof value === 'string') {
+ value = value.charCodeAt(0)
+ }
+
+ assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
+ assert(end >= start, 'end < start')
+
+ // Fill 0 bytes; we're done
+ if (end === start) return
+ if (this.length === 0) return
+
+ assert(start >= 0 && start < this.length, 'start out of bounds')
+ assert(end >= 0 && end <= this.length, 'end out of bounds')
+
+ for (var i = start; i < end; i++) {
+ this[i] = value
+ }
+}
+
+Buffer.prototype.inspect = function () {
+ var out = []
+ var 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 array;
- };
+ }
+ return '<Buffer ' + out.join(' ') + '>'
+}
- 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;
+/**
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
+ */
+Buffer.prototype.toArrayBuffer = function () {
+ if (typeof Uint8Array === 'function') {
+ if (Buffer._useTypedArrays) {
+ return (new Buffer(this)).buffer
+ } else {
+ var buf = new Uint8Array(this.length)
+ for (var i = 0, len = buf.length; i < len; i += 1)
+ buf[i] = this[i]
+ return buf.buffer
+ }
+ } else {
+ throw new Error('Buffer.toArrayBuffer not supported in this browser')
+ }
}
-// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements
-function valueObject(value, key) {
- return { value: value[key] };
+// HELPER FUNCTIONS
+// ================
+
+function stringtrim (str) {
+ if (str.trim) return str.trim()
+ return str.replace(/^\s+|\s+$/g, '')
}
-if (typeof Object.getOwnPropertyDescriptor === 'function') {
+var BP = Buffer.prototype
+
+/**
+ * Augment the Uint8Array *instance* (not the class!) with Buffer methods
+ */
+function augment (arr) {
+ arr._isBuffer = true
+
+ // save reference to original Uint8Array get/set methods before overwriting
+ arr._get = arr.get
+ arr._set = arr.set
+
+ // deprecated, will be removed in node 0.13+
+ arr.get = BP.get
+ arr.set = BP.set
+
+ arr.write = BP.write
+ arr.toString = BP.toString
+ arr.toLocaleString = BP.toString
+ arr.toJSON = BP.toJSON
+ arr.copy = BP.copy
+ arr.slice = BP.slice
+ arr.readUInt8 = BP.readUInt8
+ arr.readUInt16LE = BP.readUInt16LE
+ arr.readUInt16BE = BP.readUInt16BE
+ arr.readUInt32LE = BP.readUInt32LE
+ arr.readUInt32BE = BP.readUInt32BE
+ arr.readInt8 = BP.readInt8
+ arr.readInt16LE = BP.readInt16LE
+ arr.readInt16BE = BP.readInt16BE
+ arr.readInt32LE = BP.readInt32LE
+ arr.readInt32BE = BP.readInt32BE
+ arr.readFloatLE = BP.readFloatLE
+ arr.readFloatBE = BP.readFloatBE
+ arr.readDoubleLE = BP.readDoubleLE
+ arr.readDoubleBE = BP.readDoubleBE
+ arr.writeUInt8 = BP.writeUInt8
+ arr.writeUInt16LE = BP.writeUInt16LE
+ arr.writeUInt16BE = BP.writeUInt16BE
+ arr.writeUInt32LE = BP.writeUInt32LE
+ arr.writeUInt32BE = BP.writeUInt32BE
+ arr.writeInt8 = BP.writeInt8
+ arr.writeInt16LE = BP.writeInt16LE
+ arr.writeInt16BE = BP.writeInt16BE
+ arr.writeInt32LE = BP.writeInt32LE
+ arr.writeInt32BE = BP.writeInt32BE
+ arr.writeFloatLE = BP.writeFloatLE
+ arr.writeFloatBE = BP.writeFloatBE
+ arr.writeDoubleLE = BP.writeDoubleLE
+ arr.writeDoubleBE = BP.writeDoubleBE
+ arr.fill = BP.fill
+ arr.inspect = BP.inspect
+ arr.toArrayBuffer = BP.toArrayBuffer
+
+ return arr
+}
+
+// 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
+}
+
+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 Object.prototype.toString.call(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++) {
+ var b = str.charCodeAt(i)
+ if (b <= 0x7F)
+ byteArray.push(str.charCodeAt(i))
+ else {
+ var start = i
+ if (b >= 0xD800 && b <= 0xDFFF) i++
+ var h = encodeURIComponent(str.slice(start, i+1)).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 base64.toByteArray(str)
+}
+
+function blitBuffer (src, dst, offset, length) {
+ var pos
+ for (var i = 0; i < length; i++) {
+ if ((i + offset >= dst.length) || (i >= src.length))
+ break
+ dst[i + offset] = src[i]
+ }
+ return i
+}
+
+function decodeUtf8Char (str) {
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);
- }
- };
+ return decodeURIComponent(str)
+ } catch (err) {
+ return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
-} else {
- exports.getOwnPropertyDescriptor = valueObject;
}
-},{}],2:[function(require,module,exports){
+/*
+ * 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.
+ */
+function verifuint (value, max) {
+ assert(typeof value == 'number', 'cannot write a non-number as a number')
+ assert(value >= 0,
+ 'specified a negative value for writing an unsigned value')
+ assert(value <= max, 'value is larger than maximum value for type')
+ assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifsint(value, max, min) {
+ assert(typeof value == 'number', 'cannot write a non-number as a number')
+ assert(value <= max, 'value larger than maximum allowed value')
+ assert(value >= min, 'value smaller than minimum allowed value')
+ assert(Math.floor(value) === value, 'value has a fractional component')
+}
+
+function verifIEEE754(value, max, min) {
+ assert(typeof value == 'number', 'cannot write a non-number as a number')
+ assert(value <= max, 'value larger than maximum allowed value')
+ assert(value >= min, 'value smaller than minimum allowed value')
+}
+
+function assert (test, message) {
+ if (!test) throw new Error(message || 'Failed assertion')
+}
+
+},{"base64-js":3,"ieee754":4}],3:[function(require,module,exports){
+var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+;(function (exports) {
+ 'use strict';
+
+ var Arr = (typeof Uint8Array !== 'undefined')
+ ? Uint8Array
+ : Array
+
+ var ZERO = '0'.charCodeAt(0)
+ var PLUS = '+'.charCodeAt(0)
+ var SLASH = '/'.charCodeAt(0)
+ var NUMBER = '0'.charCodeAt(0)
+ var LOWER = 'a'.charCodeAt(0)
+ var UPPER = 'A'.charCodeAt(0)
+
+ function decode (elt) {
+ var code = elt.charCodeAt(0)
+ if (code === PLUS)
+ return 62 // '+'
+ if (code === SLASH)
+ return 63 // '/'
+ if (code < NUMBER)
+ return -1 //no match
+ if (code < NUMBER + 10)
+ return code - NUMBER + 26 + 26
+ if (code < UPPER + 26)
+ return code - UPPER
+ if (code < LOWER + 26)
+ return code - LOWER + 26
+ }
+
+ function b64ToByteArray (b64) {
+ var i, j, l, tmp, placeHolders, arr
+
+ if (b64.length % 4 > 0) {
+ throw new Error('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
+ var len = b64.length
+ placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
+
+ // base64 is 4/3 + up to two characters of the original data
+ arr = new Arr(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
+
+ var L = 0
+
+ function push (v) {
+ arr[L++] = v
+ }
+
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
+ tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
+ push((tmp & 0xFF0000) >> 16)
+ push((tmp & 0xFF00) >> 8)
+ push(tmp & 0xFF)
+ }
+
+ if (placeHolders === 2) {
+ tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
+ push(tmp & 0xFF)
+ } else if (placeHolders === 1) {
+ tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
+ push((tmp >> 8) & 0xFF)
+ 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 encode (num) {
+ return lookup.charAt(num)
+ }
+
+ function tripletToBase64 (num) {
+ return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(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 += encode(temp >> 2)
+ output += encode((temp << 4) & 0x3F)
+ output += '=='
+ break
+ case 2:
+ temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
+ output += encode(temp >> 10)
+ output += encode((temp >> 4) & 0x3F)
+ output += encode((temp << 2) & 0x3F)
+ output += '='
+ break
+ }
+
+ return output
+ }
+
+ module.exports.toByteArray = b64ToByteArray
+ module.exports.fromByteArray = uint8ToBase64
+}())
+
+},{}],4:[function(require,module,exports){
+exports.read = function(buffer, offset, isLE, mLen, nBytes) {
+ var e, m,
+ eLen = nBytes * 8 - mLen - 1,
+ eMax = (1 << eLen) - 1,
+ eBias = eMax >> 1,
+ nBits = -7,
+ i = isLE ? (nBytes - 1) : 0,
+ d = isLE ? -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.write = function(buffer, value, offset, isLE, 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 = isLE ? 0 : (nBytes - 1),
+ d = isLE ? 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;
+};
+
+},{}],5:[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
@@ -239,13 +1343,10 @@
// 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) {
@@ -290,11 +1391,11 @@
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
- if (!util.isString(path)) {
+ if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
@@ -304,25 +1405,25 @@
// 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(shims.filter(resolvedPath.split('/'), function(p) {
+ resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
- trailingSlash = shims.substr(path, -1) === '/';
+ trailingSlash = substr(path, -1) === '/';
// Normalize the path
- path = normalizeArray(shims.filter(path.split('/'), function(p) {
+ path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
@@ -340,12 +1441,12 @@
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
- return exports.normalize(shims.filter(paths, function(p, index) {
- if (!util.isString(p)) {
+ return exports.normalize(filter(paths, function(p, index) {
+ if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
@@ -428,610 +1529,29 @@
exports.extname = function(path) {
return splitPath(path)[3];
};
-},{"__browserify_process":4,"_shims":1,"util":3}],3:[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]));
+function filter (xs, f) {
+ if (xs.filter) return xs.filter(f);
+ var res = [];
+ for (var i = 0; i < xs.length; i++) {
+ if (f(xs[i], i, xs)) res.push(xs[i]);
}
- return 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);
+ return res;
}
-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);
+// String.prototype.substr - negative index don't work in IE8
+var substr = 'ab'.substr(-1) === 'b'
+ ? function (str, start, len) { return str.substr(start, len) }
+ : function (str, start, len) {
+ if (start < 0) start = str.length + start;
+ return str.substr(start, len);
}
- 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 && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.binarySlice === 'function'
- ;
-}
-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":1}],4:[function(require,module,exports){
-// shim for using process in browser
-
-var process = module.exports = {};
-
-process.nextTick = (function () {
- var canSetImmediate = typeof window !== 'undefined'
- && window.setImmediate;
- var canPost = typeof window !== 'undefined'
- && window.postMessage && window.addEventListener
- ;
-
- if (canSetImmediate) {
- return function (f) { return window.setImmediate(f) };
- }
-
- if (canPost) {
- var queue = [];
- window.addEventListener('message', function (ev) {
- if (ev.source === window && ev.data === 'process-tick') {
- ev.stopPropagation();
- if (queue.length > 0) {
- var fn = queue.shift();
- fn();
- }
- }
- }, true);
-
- return function nextTick(fn) {
- queue.push(fn);
- window.postMessage('process-tick', '*');
- };
- }
-
- return function nextTick(fn) {
- setTimeout(fn, 0);
- };
-})();
-
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-}
-
-// TODO(shtylman)
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-
-},{}],5:[function(require,module,exports){
+},{"__browserify_process":1}],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>
@@ -1144,19 +1664,19 @@
TokenName[Token.XJSIdentifier] = 'XJSIdentifier';
TokenName[Token.XJSText] = 'XJSText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
- FnExprTokens = ["(", "{", "[", "in", "typeof", "instanceof", "new",
- "return", "case", "delete", "throw", "void",
+ FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
+ 'return', 'case', 'delete', 'throw', 'void',
// assignment operators
- "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=",
- "&=", "|=", "^=", ",",
+ '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
+ '&=', '|=', '^=', ',',
// binary/unary operators
- "+", "-", "*", "/", "%", "++", "--", "<<", ">>", ">>>", "&",
- "|", "^", "!", "~", "&&", "||", "?", ":", "===", "==", ">=",
- "<=", "<", ">", "!=", "!=="];
+ '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
+ '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
+ '<=', '<', '>', '!=', '!=='];
Syntax = {
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
@@ -1236,11 +1756,11 @@
Get: 2,
Set: 4
};
ClassPropertyType = {
- static: 'static',
+ 'static': 'static',
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
@@ -2409,35 +2929,35 @@
prevToken = extra.tokens[extra.tokens.length - 1];
if (!prevToken) {
// Nothing before that: it cannot be a division.
return scanRegExp();
}
- if (prevToken.type === "Punctuator") {
- if (prevToken.value === ")") {
+ if (prevToken.type === 'Punctuator') {
+ if (prevToken.value === ')') {
checkToken = extra.tokens[extra.openParenToken - 1];
if (checkToken &&
- checkToken.type === "Keyword" &&
- (checkToken.value === "if" ||
- checkToken.value === "while" ||
- checkToken.value === "for" ||
- checkToken.value === "with")) {
+ checkToken.type === 'Keyword' &&
+ (checkToken.value === 'if' ||
+ checkToken.value === 'while' ||
+ checkToken.value === 'for' ||
+ checkToken.value === 'with')) {
return scanRegExp();
}
return scanPunctuator();
}
- if (prevToken.value === "}") {
+ if (prevToken.value === '}') {
// Dividing a function by anything makes little sense,
// but we have to check for that.
if (extra.tokens[extra.openCurlyToken - 3] &&
- extra.tokens[extra.openCurlyToken - 3].type === "Keyword") {
+ extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
// Anonymous function.
checkToken = extra.tokens[extra.openCurlyToken - 4];
if (!checkToken) {
return scanPunctuator();
}
} else if (extra.tokens[extra.openCurlyToken - 4] &&
- extra.tokens[extra.openCurlyToken - 4].type === "Keyword") {
+ extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
// Named function.
checkToken = extra.tokens[extra.openCurlyToken - 5];
if (!checkToken) {
return scanRegExp();
}
@@ -2453,34 +2973,36 @@
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
- if (prevToken.type === "Keyword") {
+ if (prevToken.type === 'Keyword') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
- if (state.inXJSChild) {
- return advanceXJSChild();
+ if (!state.inXJSChild) {
+ skipComment();
}
- skipComment();
-
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
range: [index, index]
};
}
+ if (state.inXJSChild) {
+ return advanceXJSChild();
+ }
+
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
@@ -2713,11 +3235,11 @@
createForOfStatement: function (left, right, body) {
return {
type: Syntax.ForOfStatement,
left: left,
right: right,
- body: body,
+ body: body
};
},
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
returnType) {
@@ -2760,17 +3282,17 @@
// else.
typeAnnotation: undefined
};
},
- createTypeAnnotation: function (typeIdentifier, paramTypes, returnType, isNullable) {
+ createTypeAnnotation: function (typeIdentifier, paramTypes, returnType, nullable) {
return {
type: Syntax.TypeAnnotation,
id: typeIdentifier,
paramTypes: paramTypes,
returnType: returnType,
- isNullable: isNullable
+ nullable: nullable
};
},
createTypeAnnotatedIdentifier: function (identifier, annotation) {
return {
@@ -2797,15 +3319,12 @@
},
createXJSElement: function (openingElement, closingElement, children) {
return {
type: Syntax.XJSElement,
- name: openingElement.name,
- selfClosing: openingElement.selfClosing,
openingElement: openingElement,
closingElement: closingElement,
- attributes: openingElement.attributes,
children: children
};
},
createXJSEmptyExpression: function () {
@@ -3062,11 +3581,11 @@
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
- 'static': propertyType === ClassPropertyType.static
+ 'static': propertyType === ClassPropertyType["static"]
};
},
createClassBody: function (body) {
return {
@@ -3221,11 +3740,11 @@
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
- if (token.type === Token.StringLiteral) {
+ if (token.type === Token.StringLiteral || token.type === Token.XJSText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
@@ -3357,11 +3876,11 @@
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
- tmp = parseForStatement({ignore_body: true});
+ tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
@@ -3620,17 +4139,13 @@
expect('(');
++state.parenthesizedCount;
- state.allowArrowFunction = !state.allowArrowFunction;
expr = parseExpression();
- state.allowArrowFunction = false;
- if (expr.type !== Syntax.ArrowFunctionExpression) {
- expect(')');
- }
+ expect(')');
return expr;
}
@@ -4133,46 +4648,61 @@
} 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");
+ 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;
+ validateParam(options, param.left, param.left.name);
} else {
return null;
}
}
- if (options.firstRestricted) {
- throwError(options.firstRestricted, options.message);
+ if (options.message === Messages.StrictParamDupe) {
+ throwError(
+ strict ? options.stricted : options.firstRestricted,
+ options.message
+ );
}
- if (options.stricted) {
- throwErrorTolerant(options.stricted, options.message);
- }
if (defaultCount === 0) {
defaults = [];
}
- return { params: params, defaults: defaults, rest: rest };
+ return {
+ params: params,
+ defaults: defaults,
+ rest: rest,
+ stricted: options.stricted,
+ firstRestricted: options.firstRestricted,
+ message: options.message
+ };
}
function parseArrowFunctionExpression(options) {
var previousStrict, previousYieldAllowed, body;
expect('=>');
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
- strict = true;
state.yieldAllowed = false;
body = parseConciseBody();
+
+ if (strict && options.firstRestricted) {
+ throwError(options.firstRestricted, options.message);
+ }
+ if (strict && options.stricted) {
+ throwErrorTolerant(options.stricted, options.message);
+ }
+
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
return delegate.createArrowFunctionExpression(options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement);
}
@@ -4198,17 +4728,21 @@
}
token = lookahead;
expr = parseConditionalExpression();
- 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 ], defaults: [], rest: null });
+ if (match('=>') &&
+ (state.parenthesizedCount === oldParenthesizedCount ||
+ state.parenthesizedCount === (oldParenthesizedCount + 1))) {
+ if (expr.type === Syntax.Identifier) {
+ params = reinterpretAsCoverFormalsList([ expr ]);
+ } else if (expr.type === Syntax.SequenceExpression) {
+ params = reinterpretAsCoverFormalsList(expr.expressions);
}
+ if (params) {
+ return parseArrowFunctionExpression(params);
+ }
}
if (matchAssign()) {
// 11.13.1
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
@@ -4229,12 +4763,14 @@
}
// 11.14 Comma Operator
function parseExpression() {
- var expr, expressions, sequence, coverFormalsList, spreadFound, token;
+ var expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount;
+ oldParenthesizedCount = state.parenthesizedCount;
+
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
while (index < length) {
@@ -4256,27 +4792,23 @@
}
sequence = delegate.createSequenceExpression(expressions);
}
- if (state.allowArrowFunction && match(')')) {
- token = lookahead2();
- if (token.value === '=>') {
- lex();
-
- state.allowArrowFunction = false;
- expr = expressions;
+ if (match('=>')) {
+ // Do not allow nested parentheses on the LHS of the =>.
+ if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) {
+ expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions;
coverFormalsList = reinterpretAsCoverFormalsList(expr);
if (coverFormalsList) {
return parseArrowFunctionExpression(coverFormalsList);
}
-
- throwUnexpected(token);
}
+ throwUnexpected(lex());
}
- if (spreadFound) {
+ if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
}
@@ -4315,19 +4847,19 @@
// 12.2 Variable Statement
function parseTypeAnnotation(dontExpectColon) {
var typeIdentifier = null, paramTypes = null, returnType = null,
- isNullable = false;
+ nullable = false;
if (!dontExpectColon) {
expect(':');
}
if (match('?')) {
lex();
- isNullable = true;
+ nullable = true;
}
if (lookahead.type === Token.Identifier) {
typeIdentifier = parseVariableIdentifier();
}
@@ -4353,11 +4885,11 @@
return delegate.createTypeAnnotation(
typeIdentifier,
paramTypes,
returnType,
- isNullable
+ nullable
);
}
function parseVariableIdentifier() {
var token = lex();
@@ -4707,11 +5239,11 @@
var init, test, update, left, right, body, operator, oldInIteration;
init = test = update = null;
expectKeyword('for');
// http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
- if (matchContextualKeyword("each")) {
+ if (matchContextualKeyword('each')) {
throwError({}, Messages.EachNotAllowed);
}
expect('(');
@@ -4776,11 +5308,11 @@
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
- if (!(opts !== undefined && opts.ignore_body)) {
+ if (!(opts !== undefined && opts.ignoreBody)) {
body = parseStatement();
}
state.inIteration = oldInIteration;
@@ -5354,11 +5886,11 @@
return options;
}
function parseFunctionDeclaration() {
- var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator, expression;
+ var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator;
expectKeyword('function');
generator = false;
if (match('*')) {
@@ -5392,13 +5924,11 @@
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
- // here we redo some work in order to set 'expression'
- expression = !match('{');
- body = parseConciseBody();
+ body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
@@ -5408,16 +5938,16 @@
throwErrorTolerant({}, Messages.NoYieldInGenerator);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
- return delegate.createFunctionDeclaration(id, tmp.params, tmp.defaults, body, tmp.rest, generator, expression,
+ return delegate.createFunctionDeclaration(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false,
tmp.returnTypeAnnotation);
}
function parseFunctionExpression() {
- var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator, expression;
+ var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator;
expectKeyword('function');
generator = false;
@@ -5452,13 +5982,11 @@
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
- // here we redo some work in order to set 'expression'
- expression = !match('{');
- body = parseConciseBody();
+ body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
@@ -5468,16 +5996,16 @@
throwErrorTolerant({}, Messages.NoYieldInGenerator);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
- return delegate.createFunctionExpression(id, tmp.params, tmp.defaults, body, tmp.rest, generator, expression,
+ return delegate.createFunctionExpression(id, tmp.params, tmp.defaults, body, tmp.rest, generator, false,
tmp.returnTypeAnnotation);
}
function parseYieldExpression() {
- var delegateFlag, expr, previousYieldAllowed;
+ var delegateFlag, expr;
expectKeyword('yield');
if (!state.yieldAllowed) {
throwErrorTolerant({}, Messages.IllegalYield);
@@ -5487,15 +6015,11 @@
if (match('*')) {
lex();
delegateFlag = true;
}
- // It is a Syntax Error if any AssignmentExpression Contains YieldExpression.
- previousYieldAllowed = state.yieldAllowed;
- state.yieldAllowed = false;
expr = parseAssignmentExpression();
- state.yieldAllowed = previousYieldAllowed;
state.yieldFound = true;
return delegate.createYieldExpression(expr, delegateFlag);
}
@@ -5503,11 +6027,11 @@
function parseMethodDefinition(existingPropNames) {
var token, key, param, propType, isValidDuplicateProp = false;
if (lookahead.value === 'static') {
- propType = ClassPropertyType.static;
+ propType = ClassPropertyType["static"];
lex();
} else {
propType = ClassPropertyType.prototype;
}
@@ -5613,11 +6137,11 @@
}
function parseClassBody() {
var classElement, classElements = [], existingProps = {};
- existingProps[ClassPropertyType.static] = {};
+ existingProps[ClassPropertyType["static"]] = {};
existingProps[ClassPropertyType.prototype] = {};
expect('{');
while (index < length) {
@@ -6392,10 +6916,12 @@
value,
'XJS attributes must only be assigned a non-empty ' +
'expression'
);
}
+ } else if (match('<')) {
+ value = parseXJSElement();
} else if (lookahead.type === Token.XJSText) {
value = delegate.createLiteral(lex());
} else {
throwError({}, Messages.InvalidXJSAttributeValue);
}
@@ -6452,34 +6978,39 @@
if (match('{')) {
token = parseXJSExpressionContainer();
} else if (lookahead.type === Token.XJSText) {
token = delegate.createLiteral(lex());
} else {
- state.inXJSChild = false;
token = parseXJSElement();
- state.inXJSChild = true;
}
return token;
}
function parseXJSClosingElement() {
- var name, origInXJSTag;
+ var name, origInXJSChild, origInXJSTag;
+ origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
- state.inXJSTag = true;
state.inXJSChild = false;
+ state.inXJSTag = true;
expect('<');
expect('/');
name = parseXJSIdentifier();
+ // Because advance() (called by lex() called by expect()) expects there
+ // to be a valid token after >, it needs to know whether to look for a
+ // standard JS token or an XJS text node
+ state.inXJSChild = origInXJSChild;
state.inXJSTag = origInXJSTag;
expect('>');
return delegate.createXJSClosingElement(name);
}
function parseXJSOpeningElement() {
- var name, attribute, attributes = [], selfClosing = false, origInXJSTag;
+ var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag;
+ origInXJSChild = state.inXJSChild;
origInXJSTag = state.inXJSTag;
+ state.inXJSChild = false;
state.inXJSTag = true;
expect('<');
name = parseXJSIdentifier();
@@ -6492,36 +7023,42 @@
state.inXJSTag = origInXJSTag;
if (lookahead.value === '/') {
expect('/');
+ // Because advance() (called by lex() called by expect()) expects
+ // there to be a valid token after >, it needs to know whether to
+ // look for a standard JS token or an XJS text node
+ state.inXJSChild = origInXJSChild;
expect('>');
selfClosing = true;
} else {
state.inXJSChild = true;
expect('>');
}
return delegate.createXJSOpeningElement(name, attributes, selfClosing);
}
function parseXJSElement() {
- var openingElement, closingElement, children = [], origInXJSChild;
+ var openingElement, closingElement, children = [], origInXJSChild, origInXJSTag;
+ origInXJSChild = state.inXJSChild;
+ origInXJSTag = state.inXJSTag;
openingElement = parseXJSOpeningElement();
if (!openingElement.selfClosing) {
- origInXJSChild = state.inXJSChild;
while (index < length) {
- state.inXJSChild = false; // </ should not be considered in the child
+ state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
state.inXJSChild = true;
peek(); // reset lookahead token
children.push(parseXJSChild());
}
state.inXJSChild = origInXJSChild;
+ state.inXJSTag = origInXJSTag;
closingElement = parseXJSClosingElement();
if (closingElement.name.namespace !== openingElement.name.namespace || closingElement.name.name !== openingElement.name.name) {
throwError({}, Messages.ExpectedXJSClosingTag, openingElement.name.namespace ? openingElement.name.namespace + ':' + openingElement.name.name : openingElement.name.name);
}
}
@@ -6665,12 +7202,12 @@
}
},
apply: function (node) {
var nodeType = typeof node;
- assert(nodeType === "object",
- "Applying location marker to an unexpected node type: " +
+ assert(nodeType === 'object',
+ 'Applying location marker to an unexpected node type: ' +
nodeType);
if (extra.range) {
node.range = [this.range[0], this.range[1]];
}
@@ -6700,23 +7237,15 @@
skipComment();
marker = createLocationMarker();
expect('(');
++state.parenthesizedCount;
-
- state.allowArrowFunction = !state.allowArrowFunction;
expr = parseExpression();
- state.allowArrowFunction = false;
- if (expr.type === 'ArrowFunctionExpression') {
- marker.end();
- marker.apply(expr);
- } else {
- expect(')');
- marker.end();
- marker.applyGroup(expr);
- }
+ expect(')');
+ marker.end();
+ marker.applyGroup(expr);
return expr;
}
function trackLeftHandSideExpression() {
@@ -6892,10 +7421,11 @@
wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
wrapTrackingPreserveWhitespace =
wrapTrackingFunction(extra.range, extra.loc, true);
+ extra.parseArrayInitialiser = parseArrayInitialiser;
extra.parseAssignmentExpression = parseAssignmentExpression;
extra.parseBinaryExpression = parseBinaryExpression;
extra.parseBlock = parseBlock;
extra.parseFunctionSourceElements = parseFunctionSourceElements;
extra.parseCatchClause = parseCatchClause;
@@ -6914,10 +7444,11 @@
extra.parseImportSpecifier = parseImportSpecifier;
extra.parseModuleDeclaration = parseModuleDeclaration;
extra.parseModuleBlock = parseModuleBlock;
extra.parseNewExpression = parseNewExpression;
extra.parseNonComputedProperty = parseNonComputedProperty;
+ extra.parseObjectInitialiser = parseObjectInitialiser;
extra.parseObjectProperty = parseObjectProperty;
extra.parseObjectPropertyKey = parseObjectPropertyKey;
extra.parsePostfixExpression = parsePostfixExpression;
extra.parsePrimaryExpression = parsePrimaryExpression;
extra.parseProgram = parseProgram;
@@ -6944,10 +7475,11 @@
extra.parseXJSEmptyExpression = parseXJSEmptyExpression;
extra.parseXJSElement = parseXJSElement;
extra.parseXJSClosingElement = parseXJSClosingElement;
extra.parseXJSOpeningElement = parseXJSOpeningElement;
+ parseArrayInitialiser = wrapTracking(extra.parseArrayInitialiser);
parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
parseBinaryExpression = wrapTracking(extra.parseBinaryExpression);
parseBlock = wrapTracking(extra.parseBlock);
parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
parseCatchClause = wrapTracking(extra.parseCatchClause);
@@ -6967,10 +7499,11 @@
parseModuleDeclaration = wrapTracking(extra.parseModuleDeclaration);
parseModuleBlock = wrapTracking(extra.parseModuleBlock);
parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression);
parseNewExpression = wrapTracking(extra.parseNewExpression);
parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
+ parseObjectInitialiser = wrapTracking(extra.parseObjectInitialiser);
parseObjectProperty = wrapTracking(extra.parseObjectProperty);
parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
parseProgram = wrapTracking(extra.parseProgram);
@@ -7013,10 +7546,11 @@
if (typeof extra.skipComment === 'function') {
skipComment = extra.skipComment;
}
if (extra.range || extra.loc) {
+ parseArrayInitialiser = extra.parseArrayInitialiser;
parseAssignmentExpression = extra.parseAssignmentExpression;
parseBinaryExpression = extra.parseBinaryExpression;
parseBlock = extra.parseBlock;
parseFunctionSourceElements = extra.parseFunctionSourceElements;
parseCatchClause = extra.parseCatchClause;
@@ -7037,10 +7571,11 @@
parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall;
parseModuleDeclaration = extra.parseModuleDeclaration;
parseModuleBlock = extra.parseModuleBlock;
parseNewExpression = extra.parseNewExpression;
parseNonComputedProperty = extra.parseNonComputedProperty;
+ parseObjectInitialiser = extra.parseObjectInitialiser;
parseObjectProperty = extra.parseObjectProperty;
parseObjectPropertyKey = extra.parseObjectPropertyKey;
parsePostfixExpression = extra.parsePostfixExpression;
parsePrimaryExpression = extra.parsePrimaryExpression;
parseProgram = extra.parseProgram;
@@ -7220,10 +7755,12 @@
labelSet: {},
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
+ inXJSChild: false,
+ inXJSTag: false,
yieldAllowed: false,
yieldFound: false
};
extra = {};
@@ -7287,11 +7824,11 @@
}
return program;
}
- // Sync with package.json and component.json.
+ // Sync with *.json manifests.
exports.version = '1.1.0-dev-harmony';
exports.tokenize = tokenize;
exports.parse = parse;
@@ -7318,11 +7855,11 @@
}());
}));
/* vim: set sw=4 ts=4 et tw=80 : */
-},{}],6:[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'}
@@ -7346,32 +7883,34 @@
return my;
}({}));
module.exports = Base62
-},{}],7:[function(require,module,exports){
+},{}],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":12,"./source-map/source-map-generator":13,"./source-map/source-node":14}],8:[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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
+ var util = require('./util');
+
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
@@ -7382,64 +7921,52 @@
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
- ArraySet.fromArray = function ArraySet_fromArray(aArray) {
+ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
- set.add(aArray[i]);
+ set.add(aArray[i], aAllowDuplicates);
}
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) {
- if (this.has(aStr)) {
- // Already a member; nothing to do.
- return;
- }
+ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
+ var isDuplicate = this.has(aStr);
var idx = this._array.length;
- this._array.push(aStr);
- this._set[this._toSetString(aStr)] = idx;
+ if (!isDuplicate || aAllowDuplicates) {
+ this._array.push(aStr);
+ }
+ if (!isDuplicate) {
+ this._set[util.toSetString(aStr)] = idx;
+ }
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
- this._toSetString(aStr));
+ util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
- return this._set[this._toSetString(aStr)];
+ return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
@@ -7465,11 +7992,11 @@
exports.ArraySet = ArraySet;
});
-},{"amdefine":16}],9:[function(require,module,exports){
+},{"./util":16,"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
@@ -7503,11 +8030,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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64 = require('./base64');
@@ -7611,19 +8138,19 @@
};
};
});
-},{"./base64":10,"amdefine":16}],10:[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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
@@ -7655,19 +8182,19 @@
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
-},{"amdefine":16}],11:[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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* Recursive implementation of binary search.
@@ -7688,11 +8215,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]);
+ var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
@@ -7738,19 +8265,19 @@
: null;
};
});
-},{"amdefine":16}],12:[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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('./util');
var binarySearch = require('./binary-search');
@@ -7768,10 +8295,11 @@
*
* - 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]:
*
@@ -7792,71 +8320,139 @@
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
- var names = util.getArg(sourceMap, 'names');
+ // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
+ // requires the array) to play nice here.
+ var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
+ var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
- var file = util.getArg(sourceMap, 'file');
+ var file = util.getArg(sourceMap, 'file', null);
- if (version !== this._version) {
+ // Once again, Sass deviates from the spec and supplies the version as a
+ // string rather than a number, so we use loose equality checking here.
+ if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
- this._names = ArraySet.fromArray(names);
- this._sources = ArraySet.fromArray(sources);
- this._sourceRoot = sourceRoot;
- this.file = file;
+ // 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._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);
+ this.sourceRoot = sourceRoot;
+ this.sourcesContent = sourcesContent;
+ this._mappings = mappings;
+ this.file = file;
}
/**
+ * 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 (an ordered list in this._generatedMappings).
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
@@ -7889,16 +8485,11 @@
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
- if (aSourceRoot) {
- mapping.source = util.join(aSourceRoot, this._sources.at(previousSource + temp.value));
- }
- else {
- mapping.source = this._sources.at(previousSource + temp.value);
- }
+ 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');
}
@@ -7927,49 +8518,21 @@
previousName += temp.value;
str = temp.rest;
}
}
- this._generatedMappings.push(mapping);
- this._originalMappings.push(mapping);
+ this.__generatedMappings.push(mapping);
+ if (typeof mapping.originalLine === 'number') {
+ this.__originalMappings.push(mapping);
+ }
}
}
- this._originalMappings.sort(this._compareOriginalPositions);
+ this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
- * 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,
@@ -8015,15 +8578,19 @@
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
- this._compareGeneratedPositions)
+ util.compareByGeneratedPositions);
if (mapping) {
+ var source = util.getArg(mapping, 'source', null);
+ if (source && this.sourceRoot) {
+ source = util.join(this.sourceRoot, source);
+ }
return {
- source: util.getArg(mapping, 'source', null),
+ source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
@@ -8035,10 +8602,51 @@
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.
@@ -8056,15 +8664,19 @@
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",
- this._compareOriginalPositions)
+ util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
@@ -8083,12 +8695,11 @@
/**
* 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. This function should
- * not mutate the mapping.
+ * The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
@@ -8112,26 +8723,40 @@
break;
default:
throw new Error("Unknown order of iteration.");
}
- mappings.forEach(aCallback, context);
+ 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);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
-},{"./array-set":8,"./base64-vlq":9,"./binary-search":11,"./util":15,"amdefine":16}],13:[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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var base64VLQ = require('./base64-vlq');
var util = require('./util');
@@ -8149,15 +8774,63 @@
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.
@@ -8181,18 +8854,124 @@
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
- generated: generated,
- original: original,
+ generatedLine: generated.line,
+ generatedColumn: generated.column,
+ originalLine: original != null && original.line,
+ originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
+ * Set the source content for a source file.
+ */
+ SourceMapGenerator.prototype.setSourceContent =
+ function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
+ var source = aSourceFile;
+ if (this._sourceRoot) {
+ 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
@@ -8217,11 +8996,16 @@
&& aSource) {
// Cases 2 and 3.
return;
}
else {
- throw new Error('Invalid mapping.');
+ throw new Error('Invalid mapping: ' + JSON.stringify({
+ generated: aGenerated,
+ source: aSource,
+ orginal: aOriginal,
+ name: aName
+ }));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
@@ -8236,55 +9020,53 @@
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
- // The mappings must be guarenteed to be in sorted order before we start
+ // The mappings must be guaranteed 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(function (mappingA, mappingB) {
- var cmp = mappingA.generated.line - mappingB.generated.line;
- return cmp === 0
- ? mappingA.generated.column - mappingB.generated.column
- : cmp;
- });
+ this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
- if (mapping.generated.line !== previousGeneratedLine) {
+ if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
- while (mapping.generated.line !== previousGeneratedLine) {
+ while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
+ if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
+ continue;
+ }
result += ',';
}
}
- result += base64VLQ.encode(mapping.generated.column
+ result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
- previousGeneratedColumn = mapping.generated.column;
+ previousGeneratedColumn = mapping.generatedColumn;
- if (mapping.source && mapping.original) {
+ if (mapping.source) {
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.original.line - 1
+ result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
- previousOriginalLine = mapping.original.line - 1;
+ previousOriginalLine = mapping.originalLine - 1;
- result += base64VLQ.encode(mapping.original.column
+ result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
- previousOriginalColumn = mapping.original.column;
+ previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
@@ -8293,10 +9075,27 @@
}
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() {
@@ -8308,10 +9107,14 @@
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.
@@ -8323,23 +9126,24 @@
exports.SourceMapGenerator = SourceMapGenerator;
});
-},{"./array-set":8,"./base64-vlq":9,"./util":15,"amdefine":16}],14:[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);
+ var define = require('amdefine')(module, require);
}
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.
@@ -8347,20 +9151,126 @@
* @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) {
+ function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
- this.line = aLine;
- this.column = aColumn;
- this.source = aSource;
+ 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;
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.
*/
@@ -8412,20 +9322,25 @@
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
- this.children.forEach(function (chunk) {
+ var chunk;
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
- aFn(chunk, { source: this.source, line: this.line, column: this.column });
+ aFn(chunk, { source: this.source,
+ line: this.line,
+ column: this.column,
+ name: this.name });
}
}
- }, this);
+ }
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
@@ -8433,11 +9348,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);
@@ -8468,10 +9383,42 @@
}
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 = "";
@@ -8490,53 +9437,81 @@
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 (original.source !== null
+ && original.line !== null
+ && original.column !== null) {
+ if(lastOriginalSource !== original.source
+ || lastOriginalLine !== original.line
+ || lastOriginalColumn !== original.column
+ || lastOriginalName !== original.name) {
+ map.addMapping({
+ source: original.source,
+ original: {
+ line: original.line,
+ column: original.column
+ },
+ generated: {
+ line: generated.line,
+ column: generated.column
+ },
+ name: original.name
+ });
+ }
+ lastOriginalSource = original.source;
+ lastOriginalLine = original.line;
+ lastOriginalColumn = original.column;
+ lastOriginalName = original.name;
+ sourceMappingActive = true;
+ } else if (sourceMappingActive) {
map.addMapping({
- 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 (char) {
- if (char === '\n') {
+ chunk.split('').forEach(function (ch) {
+ if (ch === '\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":13,"amdefine":16}],15:[function(require,module,exports){
+},{"./source-map-generator":14,"./util":16,"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);
+ var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
@@ -8557,20 +9532,185 @@
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) {
- return aPath.charAt(0) === '/'
- ? aPath
- : aRoot.replace(/\/*$/, '') + '/' + 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;
}
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":16}],16:[function(require,module,exports){
+},{"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
*/
@@ -8867,11 +10007,11 @@
return define;
}
module.exports = amdefine;
-},{"__browserify_process":4,"path":2}],17:[function(require,module,exports){
+},{"__browserify_process":1,"path":5}],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.
@@ -8900,11 +10040,11 @@
return '';
}
var commentStartRe = /^\/\*\*?/;
-var commentEndRe = /\*\/$/;
+var commentEndRe = /\*+\/$/;
var wsRe = /[\t ]+/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;
@@ -8955,11 +10095,11 @@
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
-},{}],18:[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.
@@ -8984,16 +10124,12 @@
*
* Parses input source with esprima, applies the given list of visitors to the
* AST tree, and returns the resulting output.
*/
var esprima = require('esprima-fb');
+var utils = require('./utils');
-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} node
* @param {object} parentNode
@@ -9038,15 +10174,15 @@
&& node.body[0].type === Syntax.ExpressionStatement
&& node.body[0].expression.type === Syntax.Literal
&& node.body[0].expression.value === 'use strict';
if (node.type === Syntax.Program) {
- state = updateState(state, {
+ state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
- state = updateState(state, {
+ state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {}
},
@@ -9079,11 +10215,11 @@
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
- state = updateState(state, {
+ state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {}
}
@@ -9096,30 +10232,30 @@
}
}
// Only catchup() before and after traversing a child node
function traverser(node, path, state) {
- node.range && catchup(node.range[0], state);
+ node.range && utils.catchup(node.range[0], state);
traverse(node, path, state);
- node.range && catchup(node.range[1], state);
+ node.range && utils.catchup(node.range[1], state);
}
- analyzeAndTraverse(walker, traverser, node, path, state);
+ utils.analyzeAndTraverse(walker, traverser, node, path, state);
}
function collectClosureIdentsAndTraverse(node, path, state) {
- analyzeAndTraverse(
+ utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
collectClosureIdentsAndTraverse,
node,
path,
state
);
}
function collectBlockIdentsAndTraverse(node, path, state) {
- analyzeAndTraverse(
+ utils.analyzeAndTraverse(
visitLocalBlockIdentifiers,
collectBlockIdentsAndTraverse,
node,
path,
state
@@ -9183,20 +10319,20 @@
});
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
- var state = createState(source, ast, options);
+ var state = utils.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'});
}
traverse(ast, [], state);
- catchup(source.length, state);
+ utils.catchup(source.length, state);
var ret = {code: state.g.buffer};
if (options.sourceMap) {
ret.sourceMap = state.g.sourceMap;
ret.sourceMapFilename = options.filename || 'source.js';
@@ -9204,11 +10340,11 @@
return ret;
}
exports.transform = transform;
-},{"./utils":19,"esprima-fb":5,"source-map":7}],19:[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.
@@ -9685,11 +10821,11 @@
exports.move = move;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
exports.analyzeAndTraverse = analyzeAndTraverse;
-},{"./docblock":17}],20:[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.
@@ -9702,10 +10838,129 @@
* 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*/
+
+/**
+ * Desugars ES6 Arrow functions to ES3 function expressions.
+ * If the function contains `this` expression -- automatically
+ * binds the funciton to current value of `this`.
+ *
+ * Single parameter, simple expression:
+ *
+ * [1, 2, 3].map(x => x * x);
+ *
+ * [1, 2, 3].map(function(x) { return x * x; });
+ *
+ * Several parameters, complex block:
+ *
+ * this.users.forEach((user, idx) => {
+ * return this.isActive(idx) && this.send(user);
+ * });
+ *
+ * this.users.forEach(function(user, idx) {
+ * return this.isActive(idx) && this.send(user);
+ * }.bind(this));
+ *
+ */
+var restParamVisitors = require('./es6-rest-param-visitors');
+var Syntax = require('esprima-fb').Syntax;
+var utils = require('../src/utils');
+
+/**
+ * @public
+ */
+function visitArrowFunction(traverse, node, path, state) {
+ // Prologue.
+ utils.append('function', state);
+ renderParams(node, state);
+
+ // Skip arrow.
+ utils.catchupWhiteSpace(node.body.range[0], state);
+
+ var renderBody = node.body.type == Syntax.BlockStatement
+ ? renderStatementBody
+ : renderExpressionBody;
+
+ path.unshift(node);
+ renderBody(traverse, node, path, state);
+ path.shift();
+
+ // Bind the function only if `this` value is used
+ // inside it or inside any sub-expression.
+ if (utils.containsChildOfType(node.body, Syntax.ThisExpression)) {
+ utils.append('.bind(this)', state);
+ }
+
+ return false;
+}
+
+function renderParams(node, state) {
+ // To preserve inline typechecking directives, we
+ // distinguish between parens-free and paranthesized single param.
+ if (isParensFreeSingleParam(node, state) || !node.params.length) {
+ utils.append('(', state);
+ }
+ if (node.params.length !== 0) {
+ utils.catchup(node.params[node.params.length - 1].range[1], state);
+ }
+ utils.append(')', state);
+}
+
+function isParensFreeSingleParam(node, state) {
+ return node.params.length === 1 &&
+ state.g.source[state.g.position] !== '(';
+}
+
+function renderExpressionBody(traverse, node, path, state) {
+ // Wrap simple expression bodies into a block
+ // with explicit return statement.
+ utils.append('{', state);
+ if (node.rest) {
+ utils.append(
+ restParamVisitors.renderRestParamSetup(node),
+ state
+ );
+ }
+ utils.append('return ', state);
+ renderStatementBody(traverse, node, path, state);
+ utils.append(';}', state);
+}
+
+function renderStatementBody(traverse, node, path, state) {
+ traverse(node.body, path, state);
+ utils.catchup(node.body.range[1], state);
+}
+
+visitArrowFunction.test = function(node, path, state) {
+ return node.type === Syntax.ArrowFunctionExpression;
+};
+
+exports.visitorList = [
+ visitArrowFunction
+];
+
+
+},{"../src/utils":20,"./es6-rest-param-visitors":24,"esprima-fb":6}],22:[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.
+ */
+
/*jslint node:true*/
/**
* @typechecks
*/
@@ -9853,11 +11108,11 @@
var methodName = methodNode.key.name;
if (_shouldMungeIdentifier(methodNode.key, state)) {
methodName = _getMungedName(methodName, state);
}
- var prototypeOrStatic = methodNode.static ? '' : 'prototype.';
+ var prototypeOrStatic = methodNode["static"] ? '' : 'prototype.';
utils.append(
state.className + '.' + prototypeOrStatic + methodName + '=function',
state
);
}
@@ -10165,11 +11420,11 @@
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
-},{"../src/utils":19,"base62":6,"esprima-fb":5}],21:[function(require,module,exports){
+},{"../src/utils":20,"base62":7,"esprima-fb":6}],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.
@@ -10181,41 +11436,416 @@
* 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.
*/
+
+/*jslint node: true*/
+
+/**
+ * Desugars ES6 Object Literal short notations into ES3 full notation.
+ *
+ * // Easier return values.
+ * function foo(x, y) {
+ * return {x, y}; // {x: x, y: y}
+ * };
+ *
+ * // Destrucruting.
+ * function init({port, ip, coords: {x, y}}) { ... }
+ *
+ */
+var Syntax = require('esprima-fb').Syntax;
+var utils = require('../src/utils');
+
+/**
+ * @public
+ */
+function visitObjectLiteralShortNotation(traverse, node, path, state) {
+ utils.catchup(node.key.range[1], state);
+ utils.append(':' + node.key.name, state);
+ return false;
+}
+
+visitObjectLiteralShortNotation.test = function(node, path, state) {
+ return node.type === Syntax.Property &&
+ node.kind === 'init' &&
+ node.shorthand === true;
+};
+
+exports.visitorList = [
+ visitObjectLiteralShortNotation
+];
+
+
+},{"../src/utils":20,"esprima-fb":6}],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.
+ * 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.
+ */
+
+/*jslint node:true*/
+
+/**
+ * Desugars ES6 rest parameters into ES3 arguments slicing.
+ *
+ * function printf(template, ...args) {
+ * args.forEach(...);
+ * };
+ *
+ * function printf(template) {
+ * var args = [].slice.call(arguments, 1);
+ * args.forEach(...);
+ * };
+ *
+ */
+var Syntax = require('esprima-fb').Syntax;
+var utils = require('../src/utils');
+
+function _nodeIsFunctionWithRestParam(node) {
+ return (node.type === Syntax.FunctionDeclaration
+ || node.type === Syntax.FunctionExpression
+ || node.type === Syntax.ArrowFunctionExpression)
+ && node.rest;
+}
+
+function visitFunctionParamsWithRestParam(traverse, node, path, state) {
+ // Render params.
+ if (node.params.length) {
+ utils.catchup(node.params[node.params.length - 1].range[1], state);
+ } else {
+ // -3 is for ... of the rest.
+ utils.catchup(node.rest.range[0] - 3, state);
+ }
+ utils.catchupWhiteSpace(node.rest.range[1], state);
+}
+
+visitFunctionParamsWithRestParam.test = function(node, path, state) {
+ return _nodeIsFunctionWithRestParam(node);
+};
+
+function renderRestParamSetup(functionNode) {
+ return 'var ' + functionNode.rest.name + '=Array.prototype.slice.call(' +
+ 'arguments,' +
+ functionNode.params.length +
+ ');';
+}
+
+function visitFunctionBodyWithRestParam(traverse, node, path, state) {
+ utils.catchup(node.range[0] + 1, state);
+ var parentNode = path[0];
+ utils.append(renderRestParamSetup(parentNode), state);
+ traverse(node.body, path, state);
+ return false;
+}
+
+visitFunctionBodyWithRestParam.test = function(node, path, state) {
+ return node.type === Syntax.BlockStatement
+ && _nodeIsFunctionWithRestParam(path[0]);
+};
+
+exports.renderRestParamSetup = renderRestParamSetup;
+exports.visitorList = [
+ visitFunctionParamsWithRestParam,
+ visitFunctionBodyWithRestParam
+];
+
+},{"../src/utils":20,"esprima-fb":6}],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.
+ * 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.
+ */
+
+/*jslint node:true*/
+
+/**
+ * @typechecks
+ */
+'use strict';
+
+var Syntax = require('esprima-fb').Syntax;
+var utils = require('../src/utils');
+
+/**
+ * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
+ */
+function visitTemplateLiteral(traverse, node, path, state) {
+ var templateElements = node.quasis;
+
+ utils.append('(', state);
+ for (var ii = 0; ii < templateElements.length; ii++) {
+ var templateElement = templateElements[ii];
+ if (templateElement.value.raw !== '') {
+ utils.append(getCookedValue(templateElement), state);
+ if (!templateElement.tail) {
+ // + between element and substitution
+ utils.append(' + ', state);
+ }
+ // maintain line numbers
+ utils.move(templateElement.range[0], state);
+ utils.catchupNewlines(templateElement.range[1], state);
+ }
+ utils.move(templateElement.range[1], state);
+ if (!templateElement.tail) {
+ var substitution = node.expressions[ii];
+ if (substitution.type === Syntax.Identifier ||
+ substitution.type === Syntax.MemberExpression ||
+ substitution.type === Syntax.CallExpression) {
+ utils.catchup(substitution.range[1], state);
+ } else {
+ utils.append('(', state);
+ traverse(substitution, path, state);
+ utils.catchup(substitution.range[1], state);
+ utils.append(')', state);
+ }
+ // if next templateElement isn't empty...
+ if (templateElements[ii + 1].value.cooked !== '') {
+ utils.append(' + ', state);
+ }
+ }
+ }
+ utils.move(node.range[1], state);
+ utils.append(')', state);
+ return false;
+}
+
+visitTemplateLiteral.test = function(node, path, state) {
+ return node.type === Syntax.TemplateLiteral;
+};
+
+/**
+ * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
+ */
+function visitTaggedTemplateExpression(traverse, node, path, state) {
+ var template = node.quasi;
+ var numQuasis = template.quasis.length;
+
+ // print the tag
+ utils.move(node.tag.range[0], state);
+ traverse(node.tag, path, state);
+ utils.catchup(node.tag.range[1], state);
+
+ // print array of template elements
+ utils.append('(function() { var siteObj = [', state);
+ for (var ii = 0; ii < numQuasis; ii++) {
+ utils.append(getCookedValue(template.quasis[ii]), state);
+ if (ii !== numQuasis - 1) {
+ utils.append(', ', state);
+ }
+ }
+ utils.append(']; siteObj.raw = [', state);
+ for (ii = 0; ii < numQuasis; ii++) {
+ utils.append(getRawValue(template.quasis[ii]), state);
+ if (ii !== numQuasis - 1) {
+ utils.append(', ', state);
+ }
+ }
+ utils.append(
+ ']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
+ state
+ );
+
+ // print substitutions
+ if (numQuasis > 1) {
+ for (ii = 0; ii < template.expressions.length; ii++) {
+ var expression = template.expressions[ii];
+ utils.append(', ', state);
+
+ // maintain line numbers by calling catchupWhiteSpace over the whole
+ // previous TemplateElement
+ utils.move(template.quasis[ii].range[0], state);
+ utils.catchupNewlines(template.quasis[ii].range[1], state);
+
+ utils.move(expression.range[0], state);
+ traverse(expression, path, state);
+ utils.catchup(expression.range[1], state);
+ }
+ }
+
+ // print blank lines to push the closing ) down to account for the final
+ // TemplateElement.
+ utils.catchupNewlines(node.range[1], state);
+
+ utils.append(')', state);
+
+ return false;
+}
+
+visitTaggedTemplateExpression.test = function(node, path, state) {
+ return node.type === Syntax.TaggedTemplateExpression;
+};
+
+function getCookedValue(templateElement) {
+ return JSON.stringify(templateElement.value.cooked);
+}
+
+function getRawValue(templateElement) {
+ return JSON.stringify(templateElement.value.raw);
+}
+
+exports.visitorList = [
+ visitTemplateLiteral,
+ visitTaggedTemplateExpression
+];
+
+},{"../src/utils":20,"esprima-fb":6}],26:[function(require,module,exports){
+/**
+ * Copyright 2013-2014 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.
+ */
/* jshint browser: true */
/* jslint evil: true */
'use strict';
var runScripts;
var headEl;
+var buffer = require('buffer');
var transform = require('jstransform').transform;
var visitors = require('./fbtransform/visitors').transformVisitors;
-var transform = transform.bind(null, visitors.react);
var docblock = require('jstransform/src/docblock');
+// The source-map library relies on Object.defineProperty, but IE8 doesn't
+// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
+// throws when Object.prototype.__defineGetter__ is missing, so we skip building
+// the source map in that case.
+var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
-exports.transform = transform;
+function transformReact(source) {
+ return transform(visitors.react, source, {
+ sourceMap: supportsAccessors
+ });
+}
+exports.transform = transformReact;
+
exports.exec = function(code) {
- return eval(transform(code).code);
+ return eval(transformReact(code).code);
};
-if (typeof window === "undefined" || window === null) {
- return;
-}
-headEl = document.getElementsByTagName('head')[0];
+var inlineScriptCount = 0;
-var run = exports.run = function(code) {
+// This method returns a nicely formated line of code pointing the
+// exactly location of the error `e`.
+// The line is limited in size so big lines of code are also shown
+// in a readable way.
+// Example:
+//
+// ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
+// ^
+var createSourceCodeErrorMessage = function(code, e) {
+ var sourceLines = code.split('\n');
+ var erroneousLine = sourceLines[e.lineNumber - 1];
+
+ // Removes any leading indenting spaces and gets the number of
+ // chars indenting the `erroneousLine`
+ var indentation = 0;
+ erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
+ indentation = leadingSpaces.length;
+ return '';
+ });
+
+ // Defines the number of characters that are going to show
+ // before and after the erroneous code
+ var LIMIT = 30;
+ var errorColumn = e.column - indentation;
+
+ if (errorColumn > LIMIT) {
+ erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
+ errorColumn = 4 + LIMIT;
+ }
+ if (erroneousLine.length - errorColumn > LIMIT) {
+ erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
+ }
+ var message = '\n\n' + erroneousLine + '\n';
+ message += new Array(errorColumn - 1).join(' ') + '^';
+ return message;
+};
+
+var transformCode = function(code, source) {
var jsx = docblock.parseAsObject(docblock.extract(code)).jsx;
- var functionBody = jsx ? transform(code).code : code;
- var scriptEl = document.createElement('script');
+ if (jsx) {
+ try {
+ var transformed = transformReact(code);
+ } catch(e) {
+ e.message += '\n at ';
+ if (source) {
+ if ('fileName' in e) {
+ // We set `fileName` if it's supported by this error object and
+ // a `source` was provided.
+ // The error will correctly point to `source` in Firefox.
+ e.fileName = source;
+ }
+ e.message += source + ':' + e.lineNumber + ':' + e.column;
+ } else {
+ e.message += location.href;
+ }
+ e.message += createSourceCodeErrorMessage(code, e);
+ throw e;
+ }
- scriptEl.text = functionBody;
+ if (!transformed.sourceMap) {
+ return transformed.code;
+ }
+
+ var map = transformed.sourceMap.toJSON();
+ if (source == null) {
+ source = "Inline JSX script";
+ inlineScriptCount++;
+ if (inlineScriptCount > 1) {
+ source += ' (' + inlineScriptCount + ')';
+ }
+ }
+ map.sources = [source];
+ map.sourcesContent = [code];
+
+ return (
+ transformed.code +
+ '//# sourceMappingURL=data:application/json;base64,' +
+ buffer.Buffer(JSON.stringify(map)).toString('base64')
+ );
+ } else {
+ return code;
+ }
+};
+
+var run = exports.run = function(code, source) {
+ var scriptEl = document.createElement('script');
+ scriptEl.text = transformCode(code, source);
headEl.appendChild(scriptEl);
};
var load = exports.load = function(url, callback) {
var xhr;
@@ -10229,11 +11859,11 @@
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
- run(xhr.responseText);
+ run(xhr.responseText, url);
} else {
throw new Error("Could not load " + url);
}
if (callback) {
return callback();
@@ -10243,39 +11873,43 @@
return xhr.send(null);
};
runScripts = function() {
var scripts = document.getElementsByTagName('script');
-
+
// Array.prototype.slice cannot be used on NodeList on IE8
var jsxScripts = [];
for (var i = 0; i < scripts.length; i++) {
if (scripts.item(i).type === 'text/jsx') {
jsxScripts.push(scripts.item(i));
}
}
-
+
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);
+ run(script.innerHTML, null);
}
});
};
-if (window.addEventListener) {
- window.addEventListener('DOMContentLoaded', runScripts, false);
-} else {
- window.attachEvent('onload', runScripts);
+if (typeof window !== "undefined" && window !== null) {
+ headEl = document.getElementsByTagName('head')[0];
+
+ if (window.addEventListener) {
+ window.addEventListener('DOMContentLoaded', runScripts, false);
+ } else {
+ window.attachEvent('onload', runScripts);
+ }
}
-},{"./fbtransform/visitors":25,"jstransform":18,"jstransform/src/docblock":17}],22:[function(require,module,exports){
+},{"./fbtransform/visitors":30,"buffer":2,"jstransform":19,"jstransform/src/docblock":18}],27:[function(require,module,exports){
/**
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2013-2014 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
*
@@ -10313,56 +11947,52 @@
* javascript since "class" is not a valid object key in javascript.
*/
var JSX_ATTRIBUTE_TRANSFORMS = {
cxName: function(attr) {
- if (attr.value.type !== Syntax.Literal) {
- throw new Error("cx only accepts a string literal");
- } else {
- var classNames = attr.value.value.split(/\s+/g);
- return 'cx(' + classNames.map(JSON.stringify).join(',') + ')';
- }
+ throw new Error(
+ "cxName is no longer supported, use className={cx(...)} instead"
+ );
}
};
function visitReactTag(traverse, object, path, state) {
var jsxObjIdent = utils.getDocblock(state).jsx;
+ var openingElement = object.openingElement;
+ var nameObject = openingElement.name;
+ var attributesObject = openingElement.attributes;
- utils.catchup(object.openingElement.range[0], state);
+ utils.catchup(openingElement.range[0], state);
- if (object.name.namespace) {
+ if (nameObject.namespace) {
throw new Error(
'Namespace tags are not supported. ReactJSX is not XML.');
}
- var isFallbackTag = FALLBACK_TAGS[object.name.name];
+ var isFallbackTag = FALLBACK_TAGS[nameObject.name];
utils.append(
- (isFallbackTag ? jsxObjIdent + '.' : '') + (object.name.name) + '(',
+ (isFallbackTag ? jsxObjIdent + '.' : '') + (nameObject.name) + '(',
state
);
- utils.move(object.name.range[1], state);
+ utils.move(nameObject.range[1], state);
- var childrenToRender = object.children.filter(function(child) {
- return !(child.type === Syntax.Literal && !child.value.match(/\S/));
- });
-
// if we don't have any attributes, pass in null
- if (object.attributes.length === 0) {
+ if (attributesObject.length === 0) {
utils.append('null', state);
}
// write attributes
- object.attributes.forEach(function(attr, index) {
+ attributesObject.forEach(function(attr, index) {
utils.catchup(attr.range[0], state);
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
}
var name = attr.name.name;
var isFirst = index === 0;
- var isLast = index === object.attributes.length - 1;
+ var isLast = index === attributesObject.length - 1;
if (isFirst) {
utils.append('{', state);
}
@@ -10397,26 +12027,28 @@
}
utils.catchup(attr.range[1], state);
});
- if (!object.selfClosing) {
- utils.catchup(object.openingElement.range[1] - 1, state);
- utils.move(object.openingElement.range[1], state);
+ if (!openingElement.selfClosing) {
+ utils.catchup(openingElement.range[1] - 1, state);
+ utils.move(openingElement.range[1], state);
}
// filter out whitespace
+ var childrenToRender = object.children.filter(function(child) {
+ return !(child.type === Syntax.Literal
+ && typeof child.value === 'string'
+ && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
+ });
if (childrenToRender.length > 0) {
utils.append(', ', state);
- object.children.forEach(function(child) {
- if (child.type === Syntax.Literal && !child.value.match(/\S/)) {
- return;
- }
+ childrenToRender.forEach(function(child, index) {
utils.catchup(child.range[0], state);
- var isLast = child === childrenToRender[childrenToRender.length - 1];
+ var isLast = index === childrenToRender.length - 1;
if (child.type === Syntax.Literal) {
renderXJSLiteral(child, isLast, state);
} else if (child.type === Syntax.XJSExpressionContainer) {
renderXJSExpressionContainer(traverse, child, isLast, path, state);
@@ -10430,14 +12062,14 @@
utils.catchup(child.range[1], state);
});
}
- if (object.selfClosing) {
+ if (openingElement.selfClosing) {
// everything up to />
- utils.catchup(object.openingElement.range[1] - 2, state);
- utils.move(object.openingElement.range[1], state);
+ utils.catchup(openingElement.range[1] - 2, state);
+ utils.move(openingElement.range[1], state);
} else {
// everything up to </ sdflksjfd>
utils.catchup(object.closingElement.range[0], state);
utils.move(object.closingElement.range[1], state);
}
@@ -10450,15 +12082,17 @@
// only run react when react @jsx namespace is specified in docblock
var jsx = utils.getDocblock(state).jsx;
return object.type === Syntax.XJSElement && jsx && jsx.length;
};
-exports.visitReactTag = visitReactTag;
+exports.visitorList = [
+ visitReactTag
+];
-},{"./xjs":24,"esprima-fb":5,"jstransform/src/utils":19}],23:[function(require,module,exports){
+},{"./xjs":29,"esprima-fb":6,"jstransform/src/utils":20}],28:[function(require,module,exports){
/**
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2013-2014 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
*
@@ -10474,10 +12108,36 @@
"use strict";
var Syntax = require('esprima-fb').Syntax;
var utils = require('jstransform/src/utils');
+function addDisplayName(displayName, object, state) {
+ if (object &&
+ object.type === Syntax.CallExpression &&
+ object.callee.type === Syntax.MemberExpression &&
+ object.callee.object.type === Syntax.Identifier &&
+ object.callee.object.name === 'React' &&
+ object.callee.property.type === Syntax.Identifier &&
+ object.callee.property.name === 'createClass' &&
+ object['arguments'].length === 1 &&
+ object['arguments'][0].type === Syntax.ObjectExpression) {
+ // Verify that the displayName property isn't already set
+ var properties = object['arguments'][0].properties;
+ var safe = properties.every(function(property) {
+ var value = property.key.type === Syntax.Identifier ?
+ property.key.name :
+ property.key.value;
+ return value !== 'displayName';
+ });
+
+ if (safe) {
+ utils.catchup(object['arguments'][0].range[0] + 1, state);
+ utils.append("displayName: '" + displayName + "',", state);
+ }
+ }
+}
+
/**
* Transforms the following:
*
* var MyComponent = React.createClass({
* render: ...
@@ -10487,41 +12147,61 @@
*
* var MyComponent = React.createClass({
* displayName: 'MyComponent',
* render: ...
* });
+ *
+ * Also catches:
+ *
+ * MyComponent = React.createClass(...);
+ * exports.MyComponent = React.createClass(...);
+ * module.exports = {MyComponent: React.createClass(...)};
*/
function visitReactDisplayName(traverse, object, path, state) {
- if (object.id.type === Syntax.Identifier &&
- object.init &&
- object.init.type === Syntax.CallExpression &&
- object.init.callee.type === Syntax.MemberExpression &&
- object.init.callee.object.type === Syntax.Identifier &&
- object.init.callee.object.name === 'React' &&
- object.init.callee.property.type === Syntax.Identifier &&
- object.init.callee.property.name === 'createClass' &&
- object.init['arguments'].length === 1 &&
- object.init['arguments'][0].type === Syntax.ObjectExpression) {
+ var left, right;
- var displayName = object.id.name;
- utils.catchup(object.init['arguments'][0].range[0] + 1, state);
- utils.append("displayName: '" + displayName + "',", state);
+ if (object.type === Syntax.AssignmentExpression) {
+ left = object.left;
+ right = object.right;
+ } else if (object.type === Syntax.Property) {
+ left = object.key;
+ right = object.value;
+ } else if (object.type === Syntax.VariableDeclarator) {
+ left = object.id;
+ right = object.init;
}
+
+ if (left && left.type === Syntax.MemberExpression) {
+ left = left.property;
+ }
+ if (left && left.type === Syntax.Identifier) {
+ addDisplayName(left.name, right, state);
+ }
}
/**
* Will only run on @jsx files for now.
*/
visitReactDisplayName.test = function(object, path, state) {
- return object.type === Syntax.VariableDeclarator && !!utils.getDocblock(state).jsx;
+ if (utils.getDocblock(state).jsx) {
+ return (
+ object.type === Syntax.AssignmentExpression ||
+ object.type === Syntax.Property ||
+ object.type === Syntax.VariableDeclarator
+ );
+ } else {
+ return false;
+ }
};
-exports.visitReactDisplayName = visitReactDisplayName;
+exports.visitorList = [
+ visitReactDisplayName
+];
-},{"esprima-fb":5,"jstransform/src/utils":19}],24:[function(require,module,exports){
+},{"esprima-fb":6,"jstransform/src/utils":20}],29:[function(require,module,exports){
/**
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2013-2014 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
*
@@ -10533,14 +12213,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*global exports:true*/
"use strict";
-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 utils = require('jstransform/src/utils');
var knownTags = {
a: true,
abbr: true,
address: true,
@@ -10567,10 +12245,11 @@
colgroup: true,
command: true,
data: true,
datalist: true,
dd: true,
+ defs: true,
del: true,
details: true,
dfn: true,
dialog: true,
div: true,
@@ -10605,10 +12284,11 @@
keygen: true,
label: true,
legend: true,
li: true,
line: true,
+ linearGradient: true,
link: true,
main: true,
map: true,
mark: true,
marquee: true,
@@ -10628,10 +12308,11 @@
path: true,
polyline: true,
pre: true,
progress: true,
q: true,
+ radialGradient: true,
rect: true,
rp: true,
rt: true,
ruby: true,
s: true,
@@ -10640,10 +12321,11 @@
section: true,
select: true,
small: true,
source: true,
span: true,
+ stop: true,
strong: true,
style: true,
sub: true,
summary: true,
sup: true,
@@ -10665,138 +12347,85 @@
'var': true,
video: true,
wbr: true
};
-function safeTrim(string) {
- return string.replace(/^[ \t]+/, '').replace(/[ \t]+$/, '');
-}
+function renderXJSLiteral(object, isLast, state, start, end) {
+ var lines = object.value.split(/\r\n|\n|\r/);
-// Replace all trailing whitespace characters with a single space character
-function trimWithSingleSpace(string) {
- return string.replace(/^[ \t\xA0]{2,}/, ' ').
- replace(/[ \t\xA0]{2,}$/, ' ').replace(/^\s+$/, '');
-}
+ if (start) {
+ utils.append(start, state);
+ }
-/**
- * Special handling for multiline string literals
- * print lines:
- *
- * line
- * line
- *
- * as:
- *
- * "line "+
- * "line"
- */
-function renderXJSLiteral(object, isLast, state, start, end) {
- /** Added blank check filtering and triming*/
- var trimmedChildValue = safeTrim(object.value);
- var hasFinalNewLine = false;
+ var lastNonEmptyLine = 0;
- if (trimmedChildValue) {
- // head whitespace
- append(object.value.match(/^[\t ]*/)[0], state);
- if (start) {
- append(start, state);
+ lines.forEach(function (line, index) {
+ if (line.match(/[^ \t]/)) {
+ lastNonEmptyLine = index;
}
+ });
- var trimmedChildValueWithSpace = trimWithSingleSpace(object.value);
+ lines.forEach(function (line, index) {
+ var isFirstLine = index === 0;
+ var isLastLine = index === lines.length - 1;
+ var isLastNonEmptyLine = index === lastNonEmptyLine;
- /**
- */
- var initialLines = trimmedChildValue.split(/\r\n|\n|\r/);
+ // replace rendered whitespace tabs with spaces
+ var trimmedLine = line.replace(/\t/g, ' ');
- var lines = initialLines.filter(function(line) {
- return safeTrim(line).length > 0;
- });
+ // trim whitespace touching a newline
+ if (!isFirstLine) {
+ trimmedLine = trimmedLine.replace(/^[ ]+/, '');
+ }
+ if (!isLastLine) {
+ trimmedLine = trimmedLine.replace(/[ ]+$/, '');
+ }
- var hasInitialNewLine = initialLines[0] !== lines[0];
- hasFinalNewLine =
- initialLines[initialLines.length - 1] !== lines[lines.length - 1];
+ utils.append(line.match(/^[ \t]*/)[0], state);
- var numLines = lines.length;
- lines.forEach(function (line, ii) {
- var lastLine = ii === numLines - 1;
- var trimmedLine = safeTrim(line);
- if (trimmedLine === '' && !lastLine) {
- append(line, state);
- } else {
- var preString = '';
- var postString = '';
- var leading = line.match(/^[ \t]*/)[0];
+ if (trimmedLine || isLastNonEmptyLine) {
+ utils.append(
+ JSON.stringify(trimmedLine) +
+ (!isLastNonEmptyLine ? "+' '+" : ''),
+ state);
- if (ii === 0) {
- if (hasInitialNewLine) {
- preString = ' ';
- 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 = ' ';
- }
+ if (isLastNonEmptyLine) {
+ if (end) {
+ utils.append(end, state);
}
- if (!lastLine || trimmedChildValueWithSpace.substr(
- trimmedChildValueWithSpace.length - 1, 1) === ' ' ||
- hasFinalNewLine
- ) {
- // If either not on the last line, or the original content ends with
- // whitespace, place a single character at the end.
- postString = ' ';
+ if (!isLast) {
+ utils.append(',', state);
}
+ }
- append(
- leading +
- JSON.stringify(
- preString + trimmedLine + postString
- ) +
- (lastLine ? '' : '+') +
- line.match(/[ \t]*$/)[0],
- state);
+ // only restore tail whitespace if line had literals
+ if (trimmedLine) {
+ utils.append(line.match(/[ \t]*$/)[0], state);
}
- if (!lastLine) {
- append('\n', state);
- }
- });
- } else {
- if (start) {
- append(start, state);
}
- append('""', state);
- }
- if (end) {
- append(end, state);
- }
- // add comma before trailing whitespace
- if (!isLast) {
- append(',', state);
- }
+ if (!isLastLine) {
+ utils.append('\n', state);
+ }
+ });
- // tail whitespace
- if (hasFinalNewLine) {
- append('\n', state);
- }
- append(object.value.match(/[ \t]*$/)[0], state);
- move(object.range[1], state);
+ utils.move(object.range[1], state);
}
function renderXJSExpressionContainer(traverse, object, isLast, path, state) {
// Plus 1 to skip `{`.
- move(object.range[0] + 1, state);
+ utils.move(object.range[0] + 1, state);
traverse(object.expression, path, state);
if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) {
// If we need to append a comma, make sure to do so after the expression.
- catchup(object.expression.range[1], state);
- append(',', state);
+ utils.catchup(object.expression.range[1], state);
+ utils.append(',', state);
}
// Minus 1 to skip `}`.
- catchup(object.range[1] - 1, state);
- move(object.range[1], state);
+ utils.catchup(object.range[1] - 1, state);
+ utils.move(object.range[1], state);
return false;
}
function quoteAttrName(attr) {
// Quote invalid JS identifiers.
@@ -10809,54 +12438,62 @@
exports.knownTags = knownTags;
exports.renderXJSExpressionContainer = renderXJSExpressionContainer;
exports.renderXJSLiteral = renderXJSLiteral;
exports.quoteAttrName = quoteAttrName;
-},{"esprima-fb":5,"jstransform/src/utils":19}],25:[function(require,module,exports){
+},{"esprima-fb":6,"jstransform/src/utils":20}],30:[function(require,module,exports){
/*global exports:true*/
-var es6Classes = require('jstransform/visitors/es6-class-visitors').visitorList;
+var es6ArrowFunctions = require('jstransform/visitors/es6-arrow-function-visitors');
+var es6Classes = require('jstransform/visitors/es6-class-visitors');
+var es6ObjectShortNotation = require('jstransform/visitors/es6-object-short-notation-visitors');
+var es6RestParameters = require('jstransform/visitors/es6-rest-param-visitors');
+var es6Templates = require('jstransform/visitors/es6-template-visitors');
var react = require('./transforms/react');
var reactDisplayName = require('./transforms/reactDisplayName');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
- 'es6-classes': es6Classes,
- 'react': [
- react.visitReactTag,
- reactDisplayName.visitReactDisplayName
- ]
+ 'es6-arrow-functions': es6ArrowFunctions.visitorList,
+ 'es6-classes': es6Classes.visitorList,
+ 'es6-object-short-notation': es6ObjectShortNotation.visitorList,
+ 'es6-rest-params': es6RestParameters.visitorList,
+ 'es6-templates': es6Templates.visitorList,
+ 'react': react.visitorList.concat(reactDisplayName.visitorList)
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
+ 'es6-arrow-functions',
+ 'es6-object-short-notation',
'es6-classes',
+ 'es6-rest-params',
+ 'es6-templates',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
-function getVisitorsList(excludes) {
+function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
-exports.getVisitorsList = getVisitorsList;
+exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
-},{"./transforms/react":22,"./transforms/reactDisplayName":23,"jstransform/visitors/es6-class-visitors":20}]},{},[21])
-(21)
-});
-;
+},{"./transforms/react":27,"./transforms/reactDisplayName":28,"jstransform/visitors/es6-arrow-function-visitors":21,"jstransform/visitors/es6-class-visitors":22,"jstransform/visitors/es6-object-short-notation-visitors":23,"jstransform/visitors/es6-rest-param-visitors":24,"jstransform/visitors/es6-template-visitors":25}]},{},[26])
+(26)
+});
\ No newline at end of file