Skip to content

Instantly share code, notes, and snippets.

@chengfred
Created March 13, 2014 15:52
Show Gist options
  • Save chengfred/9531061 to your computer and use it in GitHub Desktop.
Save chengfred/9531061 to your computer and use it in GitHub Desktop.
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"0+/Abx":[function(require,module,exports){
/**
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* 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.
*/
/**
* @fileoverview Computes the difference between two texts to create a patch.
* Applies the patch onto another text, allowing for errors.
* @author fraser@google.com (Neil Fraser)
*/
/**
* Class containing the diff, match and patch methods.
* @constructor
*/
function diff_match_patch() {
// Defaults.
// Redefine these in your program to override the defaults.
// Number of seconds to map a diff before giving up (0 for infinity).
this.Diff_Timeout = 1.0;
// Cost of an empty edit operation in terms of edit characters.
this.Diff_EditCost = 4;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose).
this.Match_Threshold = 0.5;
// How far to search for a match (0 = exact location, 1000+ = broad match).
// A match this many characters away from the expected location will add
// 1.0 to the score (0.0 is a perfect match).
this.Match_Distance = 1000;
// When deleting a large block of text (over ~64 characters), how close do
// the contents have to be to match the expected contents. (0.0 = perfection,
// 1.0 = very loose). Note that Match_Threshold controls how closely the
// end points of a delete need to match.
this.Patch_DeleteThreshold = 0.5;
// Chunk size for context length.
this.Patch_Margin = 4;
// The number of bits in an int.
this.Match_MaxBits = 32;
}
// DIFF FUNCTIONS
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
var DIFF_DELETE = -1;
var DIFF_INSERT = 1;
var DIFF_EQUAL = 0;
/** @typedef {{0: number, 1: string}} */
diff_match_patch.Diff;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean=} opt_checklines Optional speedup flag. If present and false,
* then don't run a line-level diff first to identify the changed areas.
* Defaults to true, which does a faster, slightly less optimal diff.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
*/
diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,
opt_deadline) {
// Set a deadline by which time the diff must be complete.
if (typeof opt_deadline == 'undefined') {
if (this.Diff_Timeout <= 0) {
opt_deadline = Number.MAX_VALUE;
} else {
opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;
}
}
var deadline = opt_deadline;
// Check for null inputs.
if (text1 == null || text2 == null) {
throw new Error('Null input. (diff_main)');
}
// Check for equality (speedup).
if (text1 == text2) {
if (text1) {
return [[DIFF_EQUAL, text1]];
}
return [];
}
if (typeof opt_checklines == 'undefined') {
opt_checklines = true;
}
var checklines = opt_checklines;
// Trim off common prefix (speedup).
var commonlength = this.diff_commonPrefix(text1, text2);
var commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = this.diff_commonSuffix(text1, text2);
var commonsuffix = text1.substring(text1.length - commonlength);
text1 = text1.substring(0, text1.length - commonlength);
text2 = text2.substring(0, text2.length - commonlength);
// Compute the diff on the middle block.
var diffs = this.diff_compute_(text1, text2, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix) {
diffs.unshift([DIFF_EQUAL, commonprefix]);
}
if (commonsuffix) {
diffs.push([DIFF_EQUAL, commonsuffix]);
}
this.diff_cleanupMerge(diffs);
return diffs;
};
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster, slightly less optimal diff.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,
deadline) {
var diffs;
if (!text1) {
// Just add some text (speedup).
return [[DIFF_INSERT, text2]];
}
if (!text2) {
// Just delete some text (speedup).
return [[DIFF_DELETE, text1]];
}
/** @type {?string} */
var longtext = text1.length > text2.length ? text1 : text2;
/** @type {?string} */
var shorttext = text1.length > text2.length ? text2 : text1;
var i = longtext.indexOf(shorttext);
if (i != -1) {
// Shorter text is inside the longer text (speedup).
diffs = [[DIFF_INSERT, longtext.substring(0, i)],
[DIFF_EQUAL, shorttext],
[DIFF_INSERT, longtext.substring(i + shorttext.length)]];
// Swap insertions for deletions if diff is reversed.
if (text1.length > text2.length) {
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
}
return diffs;
}
if (shorttext.length == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
}
longtext = shorttext = null; // Garbage collect.
// Check to see if the problem can be split in two.
var hm = this.diff_halfMatch_(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
var text1_a = hm[0];
var text1_b = hm[1];
var text2_a = hm[2];
var text2_b = hm[3];
var mid_common = hm[4];
// Send both pairs off for separate processing.
var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);
var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);
// Merge the results.
return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
}
if (checklines && text1.length > 100 && text2.length > 100) {
return this.diff_lineMode_(text1, text2, deadline);
}
return this.diff_bisect_(text1, text2, deadline);
};
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {
// Scan the text on a line-by-line basis first.
var a = this.diff_linesToChars_(text1, text2);
text1 = a.chars1;
text2 = a.chars2;
var linearray = a.lineArray;
var diffs = this.diff_main(text1, text2, false, deadline);
// Convert the diff back to original text.
this.diff_charsToLines_(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
this.diff_cleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.push([DIFF_EQUAL, '']);
var pointer = 0;
var count_delete = 0;
var count_insert = 0;
var text_delete = '';
var text_insert = '';
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
count_insert++;
text_insert += diffs[pointer][1];
break;
case DIFF_DELETE:
count_delete++;
text_delete += diffs[pointer][1];
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete >= 1 && count_insert >= 1) {
// Delete the offending records and add the merged ones.
diffs.splice(pointer - count_delete - count_insert,
count_delete + count_insert);
pointer = pointer - count_delete - count_insert;
var a = this.diff_main(text_delete, text_insert, false, deadline);
for (var j = a.length - 1; j >= 0; j--) {
diffs.splice(pointer, 0, a[j]);
}
pointer = pointer + a.length;
}
count_insert = 0;
count_delete = 0;
text_delete = '';
text_insert = '';
break;
}
pointer++;
}
diffs.pop(); // Remove the dummy entry at the end.
return diffs;
};
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {
// Cache the text lengths to prevent multiple calls.
var text1_length = text1.length;
var text2_length = text2.length;
var max_d = Math.ceil((text1_length + text2_length) / 2);
var v_offset = max_d;
var v_length = 2 * max_d;
var v1 = new Array(v_length);
var v2 = new Array(v_length);
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for (var x = 0; x < v_length; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
var delta = text1_length - text2_length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
var front = (delta % 2 != 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
var k1start = 0;
var k1end = 0;
var k2start = 0;
var k2end = 0;
for (var d = 0; d < max_d; d++) {
// Bail out if deadline is reached.
if ((new Date()).getTime() > deadline) {
break;
}
// Walk the front path one step.
for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
var k1_offset = v_offset + k1;
var x1;
if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
x1 = v1[k1_offset + 1];
} else {
x1 = v1[k1_offset - 1] + 1;
}
var y1 = x1 - k1;
while (x1 < text1_length && y1 < text2_length &&
text1.charAt(x1) == text2.charAt(y1)) {
x1++;
y1++;
}
v1[k1_offset] = x1;
if (x1 > text1_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
var k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
// Mirror x2 onto top-left coordinate system.
var x2 = text1_length - v2[k2_offset];
if (x1 >= x2) {
// Overlap detected.
return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
}
}
}
}
// Walk the reverse path one step.
for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
var k2_offset = v_offset + k2;
var x2;
if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
x2 = v2[k2_offset + 1];
} else {
x2 = v2[k2_offset - 1] + 1;
}
var y2 = x2 - k2;
while (x2 < text1_length && y2 < text2_length &&
text1.charAt(text1_length - x2 - 1) ==
text2.charAt(text2_length - y2 - 1)) {
x2++;
y2++;
}
v2[k2_offset] = x2;
if (x2 > text1_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
var k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
var x1 = v1[k1_offset];
var y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if (x1 >= x2) {
// Overlap detected.
return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
};
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @private
*/
diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,
deadline) {
var text1a = text1.substring(0, x);
var text2a = text2.substring(0, y);
var text1b = text1.substring(x);
var text2b = text2.substring(y);
// Compute both diffs serially.
var diffs = this.diff_main(text1a, text2a, false, deadline);
var diffsb = this.diff_main(text1b, text2b, false, deadline);
return diffs.concat(diffsb);
};
/**
* Split two texts into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
* An object containing the encoded text1, the encoded text2 and
* the array of unique strings.
* The zeroth element of the array of unique strings is intentionally blank.
* @private
*/
diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {
var lineArray = []; // e.g. lineArray[4] == 'Hello\n'
var lineHash = {}; // e.g. lineHash['Hello\n'] == 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = '';
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/
function diff_linesToCharsMunge_(text) {
var chars = '';
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
var lineStart = 0;
var lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
var lineArrayLength = lineArray.length;
while (lineEnd < text.length - 1) {
lineEnd = text.indexOf('\n', lineStart);
if (lineEnd == -1) {
lineEnd = text.length - 1;
}
var line = text.substring(lineStart, lineEnd + 1);
lineStart = lineEnd + 1;
if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
(lineHash[line] !== undefined)) {
chars += String.fromCharCode(lineHash[line]);
} else {
chars += String.fromCharCode(lineArrayLength);
lineHash[line] = lineArrayLength;
lineArray[lineArrayLength++] = line;
}
}
return chars;
}
var chars1 = diff_linesToCharsMunge_(text1);
var chars2 = diff_linesToCharsMunge_(text2);
return {chars1: chars1, chars2: chars2, lineArray: lineArray};
};
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @param {!Array.<string>} lineArray Array of unique strings.
* @private
*/
diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {
for (var x = 0; x < diffs.length; x++) {
var chars = diffs[x][1];
var text = [];
for (var y = 0; y < chars.length; y++) {
text[y] = lineArray[chars.charCodeAt(y)];
}
diffs[x][1] = text.join('');
}
};
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerstart = 0;
while (pointermin < pointermid) {
if (text1.substring(pointerstart, pointermid) ==
text2.substring(pointerstart, pointermid)) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 ||
text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerend = 0;
while (pointermin < pointermid) {
if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
text2.substring(text2.length - pointermid, text2.length - pointerend)) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
*/
diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {
// Cache the text lengths to prevent multiple calls.
var text1_length = text1.length;
var text2_length = text2.length;
// Eliminate the null case.
if (text1_length == 0 || text2_length == 0) {
return 0;
}
// Truncate the longer string.
if (text1_length > text2_length) {
text1 = text1.substring(text1_length - text2_length);
} else if (text1_length < text2_length) {
text2 = text2.substring(0, text1_length);
}
var text_length = Math.min(text1_length, text2_length);
// Quick check for the worst case.
if (text1 == text2) {
return text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
var best = 0;
var length = 1;
while (true) {
var pattern = text1.substring(text_length - length);
var found = text2.indexOf(pattern);
if (found == -1) {
return best;
}
length += found;
if (found == 0 || text1.substring(text_length - length) ==
text2.substring(0, length)) {
best = length;
length++;
}
}
};
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
* @private
*/
diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {
if (this.Diff_Timeout <= 0) {
// Don't risk returning a non-optimal diff if we have unlimited time.
return null;
}
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
return null; // Pointless.
}
var dmp = this; // 'this' becomes 'window' in a closure.
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diff_halfMatchI_(longtext, shorttext, i) {
// Start with a 1/4 length substring at position i as a seed.
var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
var j = -1;
var best_common = '';
var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),
shorttext.substring(j));
var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),
shorttext.substring(0, j));
if (best_common.length < suffixLength + prefixLength) {
best_common = shorttext.substring(j - suffixLength, j) +
shorttext.substring(j, j + prefixLength);
best_longtext_a = longtext.substring(0, i - suffixLength);
best_longtext_b = longtext.substring(i + prefixLength);
best_shorttext_a = shorttext.substring(0, j - suffixLength);
best_shorttext_b = shorttext.substring(j + prefixLength);
}
}
if (best_common.length * 2 >= longtext.length) {
return [best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common];
} else {
return null;
}
}
// First check if the second quarter is the seed for a half-match.
var hm1 = diff_halfMatchI_(longtext, shorttext,
Math.ceil(longtext.length / 4));
// Check again based on the third quarter.
var hm2 = diff_halfMatchI_(longtext, shorttext,
Math.ceil(longtext.length / 2));
var hm;
if (!hm1 && !hm2) {
return null;
} else if (!hm2) {
hm = hm1;
} else if (!hm1) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
var text1_a, text1_b, text2_a, text2_b;
if (text1.length > text2.length) {
text1_a = hm[0];
text1_b = hm[1];
text2_a = hm[2];
text2_b = hm[3];
} else {
text2_a = hm[0];
text2_b = hm[1];
text1_a = hm[2];
text1_b = hm[3];
}
var mid_common = hm[4];
return [text1_a, text1_b, text2_a, text2_b, mid_common];
};
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {
var changes = false;
var equalities = []; // Stack of indices where equalities are found.
var equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
var lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
var pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
var length_insertions1 = 0;
var length_deletions1 = 0;
// Number of characters that changed after the equality.
var length_insertions2 = 0;
var length_deletions2 = 0;
while (pointer < diffs.length) {
if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
equalities[equalitiesLength++] = pointer;
length_insertions1 = length_insertions2;
length_deletions1 = length_deletions2;
length_insertions2 = 0;
length_deletions2 = 0;
lastequality = diffs[pointer][1];
} else { // An insertion or deletion.
if (diffs[pointer][0] == DIFF_INSERT) {
length_insertions2 += diffs[pointer][1].length;
} else {
length_deletions2 += diffs[pointer][1].length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (lastequality && (lastequality.length <=
Math.max(length_insertions1, length_deletions1)) &&
(lastequality.length <= Math.max(length_insertions2,
length_deletions2))) {
// Duplicate record.
diffs.splice(equalities[equalitiesLength - 1], 0,
[DIFF_DELETE, lastequality]);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
// Throw away the equality we just deleted.
equalitiesLength--;
// Throw away the previous equality (it needs to be reevaluated).
equalitiesLength--;
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
length_insertions1 = 0; // Reset the counters.
length_deletions1 = 0;
length_insertions2 = 0;
length_deletions2 = 0;
lastequality = null;
changes = true;
}
}
pointer++;
}
// Normalize the diff.
if (changes) {
this.diff_cleanupMerge(diffs);
}
this.diff_cleanupSemanticLossless(diffs);
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while (pointer < diffs.length) {
if (diffs[pointer - 1][0] == DIFF_DELETE &&
diffs[pointer][0] == DIFF_INSERT) {
var deletion = diffs[pointer - 1][1];
var insertion = diffs[pointer][1];
var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);
var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);
if (overlap_length1 >= overlap_length2) {
if (overlap_length1 >= deletion.length / 2 ||
overlap_length1 >= insertion.length / 2) {
// Overlap found. Insert an equality and trim the surrounding edits.
diffs.splice(pointer, 0,
[DIFF_EQUAL, insertion.substring(0, overlap_length1)]);
diffs[pointer - 1][1] =
deletion.substring(0, deletion.length - overlap_length1);
diffs[pointer + 1][1] = insertion.substring(overlap_length1);
pointer++;
}
} else {
if (overlap_length2 >= deletion.length / 2 ||
overlap_length2 >= insertion.length / 2) {
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.splice(pointer, 0,
[DIFF_EQUAL, deletion.substring(0, overlap_length2)]);
diffs[pointer - 1][0] = DIFF_INSERT;
diffs[pointer - 1][1] =
insertion.substring(0, insertion.length - overlap_length2);
diffs[pointer + 1][0] = DIFF_DELETE;
diffs[pointer + 1][1] =
deletion.substring(overlap_length2);
pointer++;
}
}
pointer++;
}
pointer++;
}
};
/**
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {
/**
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* Closure, but does not reference any external variables.
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
*/
function diff_cleanupSemanticScore_(one, two) {
if (!one || !two) {
// Edges are the best.
return 6;
}
// Each port of this function behaves slightly differently due to
// subtle differences in each language's definition of things like
// 'whitespace'. Since this function's purpose is largely cosmetic,
// the choice has been made to use each language's native features
// rather than force total conformity.
var char1 = one.charAt(one.length - 1);
var char2 = two.charAt(0);
var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);
var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);
var whitespace1 = nonAlphaNumeric1 &&
char1.match(diff_match_patch.whitespaceRegex_);
var whitespace2 = nonAlphaNumeric2 &&
char2.match(diff_match_patch.whitespaceRegex_);
var lineBreak1 = whitespace1 &&
char1.match(diff_match_patch.linebreakRegex_);
var lineBreak2 = whitespace2 &&
char2.match(diff_match_patch.linebreakRegex_);
var blankLine1 = lineBreak1 &&
one.match(diff_match_patch.blanklineEndRegex_);
var blankLine2 = lineBreak2 &&
two.match(diff_match_patch.blanklineStartRegex_);
if (blankLine1 || blankLine2) {
// Five points for blank lines.
return 5;
} else if (lineBreak1 || lineBreak2) {
// Four points for line breaks.
return 4;
} else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
// Three points for end of sentences.
return 3;
} else if (whitespace1 || whitespace2) {
// Two points for whitespace.
return 2;
} else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
// One point for non-alphanumeric.
return 1;
}
return 0;
}
var pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] == DIFF_EQUAL &&
diffs[pointer + 1][0] == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
var equality1 = diffs[pointer - 1][1];
var edit = diffs[pointer][1];
var equality2 = diffs[pointer + 1][1];
// First, shift the edit as far left as possible.
var commonOffset = this.diff_commonSuffix(equality1, edit);
if (commonOffset) {
var commonString = edit.substring(edit.length - commonOffset);
equality1 = equality1.substring(0, equality1.length - commonOffset);
edit = commonString + edit.substring(0, edit.length - commonOffset);
equality2 = commonString + equality2;
}
// Second, step character by character right, looking for the best fit.
var bestEquality1 = equality1;
var bestEdit = edit;
var bestEquality2 = equality2;
var bestScore = diff_cleanupSemanticScore_(equality1, edit) +
diff_cleanupSemanticScore_(edit, equality2);
while (edit.charAt(0) === equality2.charAt(0)) {
equality1 += edit.charAt(0);
edit = edit.substring(1) + equality2.charAt(0);
equality2 = equality2.substring(1);
var score = diff_cleanupSemanticScore_(equality1, edit) +
diff_cleanupSemanticScore_(edit, equality2);
// The >= encourages trailing rather than leading whitespace on edits.
if (score >= bestScore) {
bestScore = score;
bestEquality1 = equality1;
bestEdit = edit;
bestEquality2 = equality2;
}
}
if (diffs[pointer - 1][1] != bestEquality1) {
// We have an improvement, save it back to the diff.
if (bestEquality1) {
diffs[pointer - 1][1] = bestEquality1;
} else {
diffs.splice(pointer - 1, 1);
pointer--;
}
diffs[pointer][1] = bestEdit;
if (bestEquality2) {
diffs[pointer + 1][1] = bestEquality2;
} else {
diffs.splice(pointer + 1, 1);
pointer--;
}
}
}
pointer++;
}
};
// Define some regex patterns for matching boundaries.
diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
diff_match_patch.whitespaceRegex_ = /\s/;
diff_match_patch.linebreakRegex_ = /[\r\n]/;
diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/;
diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/;
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {
var changes = false;
var equalities = []; // Stack of indices where equalities are found.
var equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
var lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
var pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
var pre_ins = false;
// Is there a deletion operation before the last equality.
var pre_del = false;
// Is there an insertion operation after the last equality.
var post_ins = false;
// Is there a deletion operation after the last equality.
var post_del = false;
while (pointer < diffs.length) {
if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
if (diffs[pointer][1].length < this.Diff_EditCost &&
(post_ins || post_del)) {
// Candidate found.
equalities[equalitiesLength++] = pointer;
pre_ins = post_ins;
pre_del = post_del;
lastequality = diffs[pointer][1];
} else {
// Not a candidate, and can never become one.
equalitiesLength = 0;
lastequality = null;
}
post_ins = post_del = false;
} else { // An insertion or deletion.
if (diffs[pointer][0] == DIFF_DELETE) {
post_del = true;
} else {
post_ins = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if (lastequality && ((pre_ins && pre_del && post_ins && post_del) ||
((lastequality.length < this.Diff_EditCost / 2) &&
(pre_ins + pre_del + post_ins + post_del) == 3))) {
// Duplicate record.
diffs.splice(equalities[equalitiesLength - 1], 0,
[DIFF_DELETE, lastequality]);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
equalitiesLength--; // Throw away the equality we just deleted;
lastequality = null;
if (pre_ins && pre_del) {
// No changes made which could affect previous entry, keep going.
post_ins = post_del = true;
equalitiesLength = 0;
} else {
equalitiesLength--; // Throw away the previous equality.
pointer = equalitiesLength > 0 ?
equalities[equalitiesLength - 1] : -1;
post_ins = post_del = false;
}
changes = true;
}
}
pointer++;
}
if (changes) {
this.diff_cleanupMerge(diffs);
}
};
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
*/
diff_match_patch.prototype.diff_cleanupMerge = function(diffs) {
diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end.
var pointer = 0;
var count_delete = 0;
var count_insert = 0;
var text_delete = '';
var text_insert = '';
var commonlength;
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
count_insert++;
text_insert += diffs[pointer][1];
pointer++;
break;
case DIFF_DELETE:
count_delete++;
text_delete += diffs[pointer][1];
pointer++;
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (count_delete + count_insert > 1) {
if (count_delete !== 0 && count_insert !== 0) {
// Factor out any common prefixies.
commonlength = this.diff_commonPrefix(text_insert, text_delete);
if (commonlength !== 0) {
if ((pointer - count_delete - count_insert) > 0 &&
diffs[pointer - count_delete - count_insert - 1][0] ==
DIFF_EQUAL) {
diffs[pointer - count_delete - count_insert - 1][1] +=
text_insert.substring(0, commonlength);
} else {
diffs.splice(0, 0, [DIFF_EQUAL,
text_insert.substring(0, commonlength)]);
pointer++;
}
text_insert = text_insert.substring(commonlength);
text_delete = text_delete.substring(commonlength);
}
// Factor out any common suffixies.
commonlength = this.diff_commonSuffix(text_insert, text_delete);
if (commonlength !== 0) {
diffs[pointer][1] = text_insert.substring(text_insert.length -
commonlength) + diffs[pointer][1];
text_insert = text_insert.substring(0, text_insert.length -
commonlength);
text_delete = text_delete.substring(0, text_delete.length -
commonlength);
}
}
// Delete the offending records and add the merged ones.
if (count_delete === 0) {
diffs.splice(pointer - count_insert,
count_delete + count_insert, [DIFF_INSERT, text_insert]);
} else if (count_insert === 0) {
diffs.splice(pointer - count_delete,
count_delete + count_insert, [DIFF_DELETE, text_delete]);
} else {
diffs.splice(pointer - count_delete - count_insert,
count_delete + count_insert, [DIFF_DELETE, text_delete],
[DIFF_INSERT, text_insert]);
}
pointer = pointer - count_delete - count_insert +
(count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1;
} else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
// Merge this equality with the previous one.
diffs[pointer - 1][1] += diffs[pointer][1];
diffs.splice(pointer, 1);
} else {
pointer++;
}
count_insert = 0;
count_delete = 0;
text_delete = '';
text_insert = '';
break;
}
}
if (diffs[diffs.length - 1][1] === '') {
diffs.pop(); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by equalities
// which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
var changes = false;
pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] == DIFF_EQUAL &&
diffs[pointer + 1][0] == DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
if (diffs[pointer][1].substring(diffs[pointer][1].length -
diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
// Shift the edit over the previous equality.
diffs[pointer][1] = diffs[pointer - 1][1] +
diffs[pointer][1].substring(0, diffs[pointer][1].length -
diffs[pointer - 1][1].length);
diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
diffs.splice(pointer - 1, 1);
changes = true;
} else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
diffs[pointer + 1][1]) {
// Shift the edit over the next equality.
diffs[pointer - 1][1] += diffs[pointer + 1][1];
diffs[pointer][1] =
diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
diffs[pointer + 1][1];
diffs.splice(pointer + 1, 1);
changes = true;
}
}
pointer++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if (changes) {
this.diff_cleanupMerge(diffs);
}
};
/**
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
*/
diff_match_patch.prototype.diff_xIndex = function(diffs, loc) {
var chars1 = 0;
var chars2 = 0;
var last_chars1 = 0;
var last_chars2 = 0;
var x;
for (x = 0; x < diffs.length; x++) {
if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.
chars1 += diffs[x][1].length;
}
if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.
chars2 += diffs[x][1].length;
}
if (chars1 > loc) { // Overshot the location.
break;
}
last_chars1 = chars1;
last_chars2 = chars2;
}
// Was the location was deleted?
if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
return last_chars2;
}
// Add the remaining character length.
return last_chars2 + (loc - last_chars1);
};
/**
* Convert a diff array into a pretty HTML report.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} HTML representation.
*/
diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
var html = [];
var pattern_amp = /&/g;
var pattern_lt = /</g;
var pattern_gt = />/g;
var pattern_para = /\n/g;
for (var x = 0; x < diffs.length; x++) {
var op = diffs[x][0]; // Operation (insert, delete, equal)
var data = diffs[x][1]; // Text of change.
var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
.replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
switch (op) {
case DIFF_INSERT:
html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>';
break;
case DIFF_DELETE:
html[x] = '<del style="background:#ffe6e6;">' + text + '</del>';
break;
case DIFF_EQUAL:
html[x] = '<span>' + text + '</span>';
break;
}
}
return html.join('');
};
/**
* Compute and return the source text (all equalities and deletions).
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} Source text.
*/
diff_match_patch.prototype.diff_text1 = function(diffs) {
var text = [];
for (var x = 0; x < diffs.length; x++) {
if (diffs[x][0] !== DIFF_INSERT) {
text[x] = diffs[x][1];
}
}
return text.join('');
};
/**
* Compute and return the destination text (all equalities and insertions).
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} Destination text.
*/
diff_match_patch.prototype.diff_text2 = function(diffs) {
var text = [];
for (var x = 0; x < diffs.length; x++) {
if (diffs[x][0] !== DIFF_DELETE) {
text[x] = diffs[x][1];
}
}
return text.join('');
};
/**
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {number} Number of changes.
*/
diff_match_patch.prototype.diff_levenshtein = function(diffs) {
var levenshtein = 0;
var insertions = 0;
var deletions = 0;
for (var x = 0; x < diffs.length; x++) {
var op = diffs[x][0];
var data = diffs[x][1];
switch (op) {
case DIFF_INSERT:
insertions += data.length;
break;
case DIFF_DELETE:
deletions += data.length;
break;
case DIFF_EQUAL:
// A deletion and an insertion is one substitution.
levenshtein += Math.max(insertions, deletions);
insertions = 0;
deletions = 0;
break;
}
}
levenshtein += Math.max(insertions, deletions);
return levenshtein;
};
/**
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
* @return {string} Delta text.
*/
diff_match_patch.prototype.diff_toDelta = function(diffs) {
var text = [];
for (var x = 0; x < diffs.length; x++) {
switch (diffs[x][0]) {
case DIFF_INSERT:
text[x] = '+' + encodeURI(diffs[x][1]);
break;
case DIFF_DELETE:
text[x] = '-' + diffs[x][1].length;
break;
case DIFF_EQUAL:
text[x] = '=' + diffs[x][1].length;
break;
}
}
return text.join('\t').replace(/%20/g, ' ');
};
/**
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
* @throws {!Error} If invalid input.
*/
diff_match_patch.prototype.diff_fromDelta = function(text1, delta) {
var diffs = [];
var diffsLength = 0; // Keeping our own length var is faster in JS.
var pointer = 0; // Cursor in text1
var tokens = delta.split(/\t/g);
for (var x = 0; x < tokens.length; x++) {
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
var param = tokens[x].substring(1);
switch (tokens[x].charAt(0)) {
case '+':
try {
diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)];
} catch (ex) {
// Malformed URI sequence.
throw new Error('Illegal escape in diff_fromDelta: ' + param);
}
break;
case '-':
// Fall through.
case '=':
var n = parseInt(param, 10);
if (isNaN(n) || n < 0) {
throw new Error('Invalid number in diff_fromDelta: ' + param);
}
var text = text1.substring(pointer, pointer += n);
if (tokens[x].charAt(0) == '=') {
diffs[diffsLength++] = [DIFF_EQUAL, text];
} else {
diffs[diffsLength++] = [DIFF_DELETE, text];
}
break;
default:
// Blank tokens are ok (from a trailing \t).
// Anything else is an error.
if (tokens[x]) {
throw new Error('Invalid diff operation in diff_fromDelta: ' +
tokens[x]);
}
}
}
if (pointer != text1.length) {
throw new Error('Delta length (' + pointer +
') does not equal source text length (' + text1.length + ').');
}
return diffs;
};
// MATCH FUNCTIONS
/**
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
*/
diff_match_patch.prototype.match_main = function(text, pattern, loc) {
// Check for null inputs.
if (text == null || pattern == null || loc == null) {
throw new Error('Null input. (match_main)');
}
loc = Math.max(0, Math.min(loc, text.length));
if (text == pattern) {
// Shortcut (potentially not guaranteed by the algorithm)
return 0;
} else if (!text.length) {
// Nothing to match.
return -1;
} else if (text.substring(loc, loc + pattern.length) == pattern) {
// Perfect match at the perfect spot! (Includes case of null pattern)
return loc;
} else {
// Do a fuzzy compare.
return this.match_bitap_(text, pattern, loc);
}
};
/**
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
*/
diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {
if (pattern.length > this.Match_MaxBits) {
throw new Error('Pattern too long for this browser.');
}
// Initialise the alphabet.
var s = this.match_alphabet_(pattern);
var dmp = this; // 'this' becomes 'window' in a closure.
/**
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
*/
function match_bitapScore_(e, x) {
var accuracy = e / pattern.length;
var proximity = Math.abs(loc - x);
if (!dmp.Match_Distance) {
// Dodge divide by zero error.
return proximity ? 1.0 : accuracy;
}
return accuracy + (proximity / dmp.Match_Distance);
}
// Highest score beyond which we give up.
var score_threshold = this.Match_Threshold;
// Is there a nearby exact match? (speedup)
var best_loc = text.indexOf(pattern, loc);
if (best_loc != -1) {
score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
// What about in the other direction? (speedup)
best_loc = text.lastIndexOf(pattern, loc + pattern.length);
if (best_loc != -1) {
score_threshold =
Math.min(match_bitapScore_(0, best_loc), score_threshold);
}
}
// Initialise the bit arrays.
var matchmask = 1 << (pattern.length - 1);
best_loc = -1;
var bin_min, bin_mid;
var bin_max = pattern.length + text.length;
var last_rd;
for (var d = 0; d < pattern.length; d++) {
// Scan for the best match; each iteration allows for one more error.
// Run a binary search to determine how far from 'loc' we can stray at this
// error level.
bin_min = 0;
bin_mid = bin_max;
while (bin_min < bin_mid) {
if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
bin_min = bin_mid;
} else {
bin_max = bin_mid;
}
bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
}
// Use the result from this iteration as the maximum for the next.
bin_max = bin_mid;
var start = Math.max(1, loc - bin_mid + 1);
var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
var rd = Array(finish + 2);
rd[finish + 1] = (1 << d) - 1;
for (var j = finish; j >= start; j--) {
// The alphabet (s) is a sparse hash, so the following line generates
// warnings.
var charMatch = s[text.charAt(j - 1)];
if (d === 0) { // First pass: exact match.
rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
} else { // Subsequent passes: fuzzy match.
rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |
(((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
last_rd[j + 1];
}
if (rd[j] & matchmask) {
var score = match_bitapScore_(d, j - 1);
// This match will almost certainly be better than any existing match.
// But check anyway.
if (score <= score_threshold) {
// Told you so.
score_threshold = score;
best_loc = j - 1;
if (best_loc > loc) {
// When passing loc, don't exceed our current distance from loc.
start = Math.max(1, 2 * loc - best_loc);
} else {
// Already passed loc, downhill from here on in.
break;
}
}
}
}
// No hope for a (better) match at greater error levels.
if (match_bitapScore_(d + 1, loc) > score_threshold) {
break;
}
last_rd = rd;
}
return best_loc;
};
/**
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {!Object} Hash of character locations.
* @private
*/
diff_match_patch.prototype.match_alphabet_ = function(pattern) {
var s = {};
for (var i = 0; i < pattern.length; i++) {
s[pattern.charAt(i)] = 0;
}
for (var i = 0; i < pattern.length; i++) {
s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);
}
return s;
};
// PATCH FUNCTIONS
/**
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {!diff_match_patch.patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
*/
diff_match_patch.prototype.patch_addContext_ = function(patch, text) {
if (text.length == 0) {
return;
}
var pattern = text.substring(patch.start2, patch.start2 + patch.length1);
var padding = 0;
// Look for the first and last matches of pattern in text. If two different
// matches are found, increase the pattern length.
while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&
pattern.length < this.Match_MaxBits - this.Patch_Margin -
this.Patch_Margin) {
padding += this.Patch_Margin;
pattern = text.substring(patch.start2 - padding,
patch.start2 + patch.length1 + padding);
}
// Add one chunk for good luck.
padding += this.Patch_Margin;
// Add the prefix.
var prefix = text.substring(patch.start2 - padding, patch.start2);
if (prefix) {
patch.diffs.unshift([DIFF_EQUAL, prefix]);
}
// Add the suffix.
var suffix = text.substring(patch.start2 + patch.length1,
patch.start2 + patch.length1 + padding);
if (suffix) {
patch.diffs.push([DIFF_EQUAL, suffix]);
}
// Roll back the start points.
patch.start1 -= prefix.length;
patch.start2 -= prefix.length;
// Extend the lengths.
patch.length1 += prefix.length + suffix.length;
patch.length2 += prefix.length + suffix.length;
};
/**
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples
* for text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
*/
diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {
var text1, diffs;
if (typeof a == 'string' && typeof opt_b == 'string' &&
typeof opt_c == 'undefined') {
// Method 1: text1, text2
// Compute diffs from text1 and text2.
text1 = /** @type {string} */(a);
diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);
if (diffs.length > 2) {
this.diff_cleanupSemantic(diffs);
this.diff_cleanupEfficiency(diffs);
}
} else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&
typeof opt_c == 'undefined') {
// Method 2: diffs
// Compute text1 from diffs.
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);
text1 = this.diff_text1(diffs);
} else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&
typeof opt_c == 'undefined') {
// Method 3: text1, diffs
text1 = /** @type {string} */(a);
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);
} else if (typeof a == 'string' && typeof opt_b == 'string' &&
opt_c && typeof opt_c == 'object') {
// Method 4: text1, text2, diffs
// text2 is not used.
text1 = /** @type {string} */(a);
diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);
} else {
throw new Error('Unknown call format to patch_make.');
}
if (diffs.length === 0) {
return []; // Get rid of the null case.
}
var patches = [];
var patch = new diff_match_patch.patch_obj();
var patchDiffLength = 0; // Keeping our own length var is faster in JS.
var char_count1 = 0; // Number of characters into the text1 string.
var char_count2 = 0; // Number of characters into the text2 string.
// Start with text1 (prepatch_text) and apply the diffs until we arrive at
// text2 (postpatch_text). We recreate the patches one by one to determine
// context info.
var prepatch_text = text1;
var postpatch_text = text1;
for (var x = 0; x < diffs.length; x++) {
var diff_type = diffs[x][0];
var diff_text = diffs[x][1];
if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
// A new patch starts here.
patch.start1 = char_count1;
patch.start2 = char_count2;
}
switch (diff_type) {
case DIFF_INSERT:
patch.diffs[patchDiffLength++] = diffs[x];
patch.length2 += diff_text.length;
postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +
postpatch_text.substring(char_count2);
break;
case DIFF_DELETE:
patch.length1 += diff_text.length;
patch.diffs[patchDiffLength++] = diffs[x];
postpatch_text = postpatch_text.substring(0, char_count2) +
postpatch_text.substring(char_count2 +
diff_text.length);
break;
case DIFF_EQUAL:
if (diff_text.length <= 2 * this.Patch_Margin &&
patchDiffLength && diffs.length != x + 1) {
// Small equality inside a patch.
patch.diffs[patchDiffLength++] = diffs[x];
patch.length1 += diff_text.length;
patch.length2 += diff_text.length;
} else if (diff_text.length >= 2 * this.Patch_Margin) {
// Time for a new patch.
if (patchDiffLength) {
this.patch_addContext_(patch, prepatch_text);
patches.push(patch);
patch = new diff_match_patch.patch_obj();
patchDiffLength = 0;
// Unlike Unidiff, our patch lists have a rolling context.
// http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
// Update prepatch text & pos to reflect the application of the
// just completed patch.
prepatch_text = postpatch_text;
char_count1 = char_count2;
}
}
break;
}
// Update the current character count.
if (diff_type !== DIFF_INSERT) {
char_count1 += diff_text.length;
}
if (diff_type !== DIFF_DELETE) {
char_count2 += diff_text.length;
}
}
// Pick up the leftover patch if not empty.
if (patchDiffLength) {
this.patch_addContext_(patch, prepatch_text);
patches.push(patch);
}
return patches;
};
/**
* Given an array of patches, return another array that is identical.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
*/
diff_match_patch.prototype.patch_deepCopy = function(patches) {
// Making deep copies is hard in JavaScript.
var patchesCopy = [];
for (var x = 0; x < patches.length; x++) {
var patch = patches[x];
var patchCopy = new diff_match_patch.patch_obj();
patchCopy.diffs = [];
for (var y = 0; y < patch.diffs.length; y++) {
patchCopy.diffs[y] = patch.diffs[y].slice();
}
patchCopy.start1 = patch.start1;
patchCopy.start2 = patch.start2;
patchCopy.length1 = patch.length1;
patchCopy.length2 = patch.length2;
patchesCopy[x] = patchCopy;
}
return patchesCopy;
};
/**
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @param {string} text Old text.
* @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
* new text and an array of boolean values.
*/
diff_match_patch.prototype.patch_apply = function(patches, text) {
if (patches.length == 0) {
return [text, []];
}
// Deep copy the patches so that no changes are made to originals.
patches = this.patch_deepCopy(patches);
var nullPadding = this.patch_addPadding(patches);
text = nullPadding + text + nullPadding;
this.patch_splitMax(patches);
// delta keeps track of the offset between the expected and actual location
// of the previous patch. If there are patches expected at positions 10 and
// 20, but the first patch was found at 12, delta is 2 and the second patch
// has an effective expected position of 22.
var delta = 0;
var results = [];
for (var x = 0; x < patches.length; x++) {
var expected_loc = patches[x].start2 + delta;
var text1 = this.diff_text1(patches[x].diffs);
var start_loc;
var end_loc = -1;
if (text1.length > this.Match_MaxBits) {
// patch_splitMax will only provide an oversized pattern in the case of
// a monster delete.
start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),
expected_loc);
if (start_loc != -1) {
end_loc = this.match_main(text,
text1.substring(text1.length - this.Match_MaxBits),
expected_loc + text1.length - this.Match_MaxBits);
if (end_loc == -1 || start_loc >= end_loc) {
// Can't find valid trailing context. Drop this patch.
start_loc = -1;
}
}
} else {
start_loc = this.match_main(text, text1, expected_loc);
}
if (start_loc == -1) {
// No match found. :(
results[x] = false;
// Subtract the delta for this failed patch from subsequent patches.
delta -= patches[x].length2 - patches[x].length1;
} else {
// Found a match. :)
results[x] = true;
delta = start_loc - expected_loc;
var text2;
if (end_loc == -1) {
text2 = text.substring(start_loc, start_loc + text1.length);
} else {
text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);
}
if (text1 == text2) {
// Perfect match, just shove the replacement text in.
text = text.substring(0, start_loc) +
this.diff_text2(patches[x].diffs) +
text.substring(start_loc + text1.length);
} else {
// Imperfect match. Run a diff to get a framework of equivalent
// indices.
var diffs = this.diff_main(text1, text2, false);
if (text1.length > this.Match_MaxBits &&
this.diff_levenshtein(diffs) / text1.length >
this.Patch_DeleteThreshold) {
// The end points match, but the content is unacceptably bad.
results[x] = false;
} else {
this.diff_cleanupSemanticLossless(diffs);
var index1 = 0;
var index2;
for (var y = 0; y < patches[x].diffs.length; y++) {
var mod = patches[x].diffs[y];
if (mod[0] !== DIFF_EQUAL) {
index2 = this.diff_xIndex(diffs, index1);
}
if (mod[0] === DIFF_INSERT) { // Insertion
text = text.substring(0, start_loc + index2) + mod[1] +
text.substring(start_loc + index2);
} else if (mod[0] === DIFF_DELETE) { // Deletion
text = text.substring(0, start_loc + index2) +
text.substring(start_loc + this.diff_xIndex(diffs,
index1 + mod[1].length));
}
if (mod[0] !== DIFF_DELETE) {
index1 += mod[1].length;
}
}
}
}
}
}
// Strip the padding off.
text = text.substring(nullPadding.length, text.length - nullPadding.length);
return [text, results];
};
/**
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @return {string} The padding string added to each side.
*/
diff_match_patch.prototype.patch_addPadding = function(patches) {
var paddingLength = this.Patch_Margin;
var nullPadding = '';
for (var x = 1; x <= paddingLength; x++) {
nullPadding += String.fromCharCode(x);
}
// Bump all the patches forward.
for (var x = 0; x < patches.length; x++) {
patches[x].start1 += paddingLength;
patches[x].start2 += paddingLength;
}
// Add some padding on start of first diff.
var patch = patches[0];
var diffs = patch.diffs;
if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
// Add nullPadding equality.
diffs.unshift([DIFF_EQUAL, nullPadding]);
patch.start1 -= paddingLength; // Should be 0.
patch.start2 -= paddingLength; // Should be 0.
patch.length1 += paddingLength;
patch.length2 += paddingLength;
} else if (paddingLength > diffs[0][1].length) {
// Grow first equality.
var extraLength = paddingLength - diffs[0][1].length;
diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];
patch.start1 -= extraLength;
patch.start2 -= extraLength;
patch.length1 += extraLength;
patch.length2 += extraLength;
}
// Add some padding on end of last diff.
patch = patches[patches.length - 1];
diffs = patch.diffs;
if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
// Add nullPadding equality.
diffs.push([DIFF_EQUAL, nullPadding]);
patch.length1 += paddingLength;
patch.length2 += paddingLength;
} else if (paddingLength > diffs[diffs.length - 1][1].length) {
// Grow last equality.
var extraLength = paddingLength - diffs[diffs.length - 1][1].length;
diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);
patch.length1 += extraLength;
patch.length2 += extraLength;
}
return nullPadding;
};
/**
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
*/
diff_match_patch.prototype.patch_splitMax = function(patches) {
var patch_size = this.Match_MaxBits;
for (var x = 0; x < patches.length; x++) {
if (patches[x].length1 <= patch_size) {
continue;
}
var bigpatch = patches[x];
// Remove the big old patch.
patches.splice(x--, 1);
var start1 = bigpatch.start1;
var start2 = bigpatch.start2;
var precontext = '';
while (bigpatch.diffs.length !== 0) {
// Create one of several smaller patches.
var patch = new diff_match_patch.patch_obj();
var empty = true;
patch.start1 = start1 - precontext.length;
patch.start2 = start2 - precontext.length;
if (precontext !== '') {
patch.length1 = patch.length2 = precontext.length;
patch.diffs.push([DIFF_EQUAL, precontext]);
}
while (bigpatch.diffs.length !== 0 &&
patch.length1 < patch_size - this.Patch_Margin) {
var diff_type = bigpatch.diffs[0][0];
var diff_text = bigpatch.diffs[0][1];
if (diff_type === DIFF_INSERT) {
// Insertions are harmless.
patch.length2 += diff_text.length;
start2 += diff_text.length;
patch.diffs.push(bigpatch.diffs.shift());
empty = false;
} else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&
patch.diffs[0][0] == DIFF_EQUAL &&
diff_text.length > 2 * patch_size) {
// This is a large deletion. Let it pass in one chunk.
patch.length1 += diff_text.length;
start1 += diff_text.length;
empty = false;
patch.diffs.push([diff_type, diff_text]);
bigpatch.diffs.shift();
} else {
// Deletion or equality. Only take as much as we can stomach.
diff_text = diff_text.substring(0,
patch_size - patch.length1 - this.Patch_Margin);
patch.length1 += diff_text.length;
start1 += diff_text.length;
if (diff_type === DIFF_EQUAL) {
patch.length2 += diff_text.length;
start2 += diff_text.length;
} else {
empty = false;
}
patch.diffs.push([diff_type, diff_text]);
if (diff_text == bigpatch.diffs[0][1]) {
bigpatch.diffs.shift();
} else {
bigpatch.diffs[0][1] =
bigpatch.diffs[0][1].substring(diff_text.length);
}
}
}
// Compute the head context for the next patch.
precontext = this.diff_text2(patch.diffs);
precontext =
precontext.substring(precontext.length - this.Patch_Margin);
// Append the end context for this patch.
var postcontext = this.diff_text1(bigpatch.diffs)
.substring(0, this.Patch_Margin);
if (postcontext !== '') {
patch.length1 += postcontext.length;
patch.length2 += postcontext.length;
if (patch.diffs.length !== 0 &&
patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {
patch.diffs[patch.diffs.length - 1][1] += postcontext;
} else {
patch.diffs.push([DIFF_EQUAL, postcontext]);
}
}
if (!empty) {
patches.splice(++x, 0, patch);
}
}
}
};
/**
* Take a list of patches and return a textual representation.
* @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
* @return {string} Text representation of patches.
*/
diff_match_patch.prototype.patch_toText = function(patches) {
var text = [];
for (var x = 0; x < patches.length; x++) {
text[x] = patches[x];
}
return text.join('');
};
/**
* Parse a textual representation of patches and return a list of Patch objects.
* @param {string} textline Text representation of patches.
* @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
* @throws {!Error} If invalid input.
*/
diff_match_patch.prototype.patch_fromText = function(textline) {
var patches = [];
if (!textline) {
return patches;
}
var text = textline.split('\n');
var textPointer = 0;
var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
while (textPointer < text.length) {
var m = text[textPointer].match(patchHeader);
if (!m) {
throw new Error('Invalid patch string: ' + text[textPointer]);
}
var patch = new diff_match_patch.patch_obj();
patches.push(patch);
patch.start1 = parseInt(m[1], 10);
if (m[2] === '') {
patch.start1--;
patch.length1 = 1;
} else if (m[2] == '0') {
patch.length1 = 0;
} else {
patch.start1--;
patch.length1 = parseInt(m[2], 10);
}
patch.start2 = parseInt(m[3], 10);
if (m[4] === '') {
patch.start2--;
patch.length2 = 1;
} else if (m[4] == '0') {
patch.length2 = 0;
} else {
patch.start2--;
patch.length2 = parseInt(m[4], 10);
}
textPointer++;
while (textPointer < text.length) {
var sign = text[textPointer].charAt(0);
try {
var line = decodeURI(text[textPointer].substring(1));
} catch (ex) {
// Malformed URI sequence.
throw new Error('Illegal escape in patch_fromText: ' + line);
}
if (sign == '-') {
// Deletion.
patch.diffs.push([DIFF_DELETE, line]);
} else if (sign == '+') {
// Insertion.
patch.diffs.push([DIFF_INSERT, line]);
} else if (sign == ' ') {
// Minor equality.
patch.diffs.push([DIFF_EQUAL, line]);
} else if (sign == '@') {
// Start of next patch.
break;
} else if (sign === '') {
// Blank line? Whatever.
} else {
// WTF?
throw new Error('Invalid patch mode "' + sign + '" in: ' + line);
}
textPointer++;
}
}
return patches;
};
/**
* Class representing one patch operation.
* @constructor
*/
diff_match_patch.patch_obj = function() {
/** @type {!Array.<!diff_match_patch.Diff>} */
this.diffs = [];
/** @type {?number} */
this.start1 = null;
/** @type {?number} */
this.start2 = null;
/** @type {number} */
this.length1 = 0;
/** @type {number} */
this.length2 = 0;
};
/**
* Emmulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* Indicies are printed as 1-based, not 0-based.
* @return {string} The GNU diff string.
*/
diff_match_patch.patch_obj.prototype.toString = function() {
var coords1, coords2;
if (this.length1 === 0) {
coords1 = this.start1 + ',0';
} else if (this.length1 == 1) {
coords1 = this.start1 + 1;
} else {
coords1 = (this.start1 + 1) + ',' + this.length1;
}
if (this.length2 === 0) {
coords2 = this.start2 + ',0';
} else if (this.length2 == 1) {
coords2 = this.start2 + 1;
} else {
coords2 = (this.start2 + 1) + ',' + this.length2;
}
var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n'];
var op;
// Escape the body of the patch with %xx notation.
for (var x = 0; x < this.diffs.length; x++) {
switch (this.diffs[x][0]) {
case DIFF_INSERT:
op = '+';
break;
case DIFF_DELETE:
op = '-';
break;
case DIFF_EQUAL:
op = ' ';
break;
}
text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n';
}
return text.join('').replace(/%20/g, ' ');
};
// Export these global variables so that they survive Google's JS compiler.
// In a browser, 'this' will be 'window'.
// Users of node.js should 'require' the uncompressed version since Google's
// JS compiler may break the following exports for non-browser environments.
this['diff_match_patch'] = diff_match_patch;
this['DIFF_DELETE'] = DIFF_DELETE;
this['DIFF_INSERT'] = DIFF_INSERT;
this['DIFF_EQUAL'] = DIFF_EQUAL;
},{}],"dmp":[function(require,module,exports){
module.exports=require('0+/Abx');
},{}],"oUUvvc":[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};(function browserifyShim(module, exports, define, browserify_shim__define__module__export__) {
// Generated by CoffeeScript 1.6.3
(function() {
var jsondiff,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty;
jsondiff = (function() {
var DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT;
DIFF_INSERT = 1;
DIFF_DELETE = -1;
DIFF_EQUAL = 0;
function jsondiff() {
this.patch_apply_with_offsets = __bind(this.patch_apply_with_offsets, this);
this.transform_object_diff = __bind(this.transform_object_diff, this);
this.transform_list_diff_dmp = __bind(this.transform_list_diff_dmp, this);
this.transform_list_diff = __bind(this.transform_list_diff, this);
this.apply_diff = __bind(this.apply_diff, this);
this.apply_object_diff_with_offsets = __bind(this.apply_object_diff_with_offsets, this);
this.apply_object_diff = __bind(this.apply_object_diff, this);
this.apply_list_diff_dmp = __bind(this.apply_list_diff_dmp, this);
this.apply_list_diff = __bind(this.apply_list_diff, this);
this.diff = __bind(this.diff, this);
this.object_diff = __bind(this.object_diff, this);
this._text_to_array = __bind(this._text_to_array, this);
this._serialize_to_text = __bind(this._serialize_to_text, this);
this.list_diff_dmp = __bind(this.list_diff_dmp, this);
this.list_diff = __bind(this.list_diff, this);
this._common_suffix = __bind(this._common_suffix, this);
this._common_prefix = __bind(this._common_prefix, this);
this.object_equals = __bind(this.object_equals, this);
this.list_equals = __bind(this.list_equals, this);
this.equals = __bind(this.equals, this);
this.deepCopy = __bind(this.deepCopy, this);
this.typeOf = __bind(this.typeOf, this);
this.entries = __bind(this.entries, this);
this.dmp = new diff_match_patch();
}
jsondiff.prototype.entries = function(obj) {
var key, n, value;
n = 0;
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = obj[key];
n++;
}
return n;
};
jsondiff.prototype.typeOf = function(value) {
var s;
s = typeof value;
if (s === 'object') {
if (value) {
if (typeof value.length === 'number' && typeof value.splice === 'function' && !value.propertyIsEnumerable('length')) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
};
jsondiff.prototype.deepCopy = function(obj) {
return JSON.parse(JSON.stringify(obj));
};
jsondiff.prototype.equals = function(a, b) {
var typea, typeb;
typea = this.typeOf(a);
typeb = this.typeOf(b);
if (typea === 'boolean' && typeb === 'number') {
return Number(a) === b;
}
if (typea === 'number' && typeb === 'boolean') {
return Number(b) === a;
}
if (typea !== typeb) {
return false;
}
if (typea === 'array') {
return this.list_equals(a, b);
} else if (typea === 'object') {
return this.object_equals(a, b);
} else {
return a === b;
}
};
jsondiff.prototype.list_equals = function(a, b) {
var alength, i, _i;
alength = a.length;
if (alength !== b.length) {
return false;
}
for (i = _i = 0; 0 <= alength ? _i < alength : _i > alength; i = 0 <= alength ? ++_i : --_i) {
if (!this.equals(a[i], b[i])) {
return false;
}
}
return true;
};
jsondiff.prototype.object_equals = function(a, b) {
var key;
for (key in a) {
if (!__hasProp.call(a, key)) continue;
if (!(key in b)) {
return false;
}
if (!this.equals(a[key], b[key])) {
return false;
}
}
for (key in b) {
if (!__hasProp.call(b, key)) continue;
if (!(key in a)) {
return false;
}
}
return true;
};
jsondiff.prototype._common_prefix = function(a, b) {
var i, minlen, _i;
minlen = Math.min(a.length, b.length);
for (i = _i = 0; 0 <= minlen ? _i < minlen : _i > minlen; i = 0 <= minlen ? ++_i : --_i) {
if (!this.equals(a[i], b[i])) {
return i;
}
}
return minlen;
};
jsondiff.prototype._common_suffix = function(a, b) {
var i, lena, lenb, minlen, _i;
lena = a.length;
lenb = b.length;
minlen = Math.min(a.length, b.length);
if (minlen === 0) {
return 0;
}
for (i = _i = 0; 0 <= minlen ? _i < minlen : _i > minlen; i = 0 <= minlen ? ++_i : --_i) {
if (!this.equals(a[lena - i - 1], b[lenb - i - 1])) {
return i;
}
}
return minlen;
};
jsondiff.prototype.list_diff = function(a, b, policy) {
var diffs, i, lena, lenb, maxlen, prefix_len, suffix_len, _i;
if ((policy != null) && 'item' in policy) {
policy = policy['item'];
} else {
policy = null;
}
diffs = {};
lena = a.length;
lenb = b.length;
prefix_len = this._common_prefix(a, b);
suffix_len = this._common_suffix(a, b);
a = a.slice(prefix_len, lena - suffix_len);
b = b.slice(prefix_len, lenb - suffix_len);
lena = a.length;
lenb = b.length;
maxlen = Math.max(lena, lenb);
for (i = _i = 0; 0 <= maxlen ? _i <= maxlen : _i >= maxlen; i = 0 <= maxlen ? ++_i : --_i) {
if (i < lena && i < lenb) {
if (!this.equals(a[i], b[i])) {
diffs[i + prefix_len] = this.diff(a[i], b[i], policy);
}
} else if (i < lena) {
diffs[i + prefix_len] = {
'o': '-'
};
} else if (i < lenb) {
diffs[i + prefix_len] = {
'o': '+',
'v': b[i]
};
}
}
return diffs;
};
jsondiff.prototype.list_diff_dmp = function(a, b, policy) {
var atext, btext, delta, diffs, lena, lenb;
lena = a.length;
lenb = b.length;
atext = this._serialize_to_text(a);
btext = this._serialize_to_text(b);
diffs = this.dmp.diff_lineMode_(atext, btext);
this.dmp.diff_cleanupEfficiency(diffs);
delta = this.dmp.diff_toDelta(diffs);
return delta;
};
jsondiff.prototype._serialize_to_text = function(a) {
var i, s, _i, _len;
s = '';
for (_i = 0, _len = a.length; _i < _len; _i++) {
i = a[_i];
s += "" + (JSON.stringify(i)) + "\n";
}
return s;
};
jsondiff.prototype._text_to_array = function(s) {
var a, sa, x;
a = [];
sa = s.split("\n");
a = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = sa.length; _i < _len; _i++) {
x = sa[_i];
if (x.length > 0) {
_results.push(JSON.parse(x));
}
}
return _results;
})();
return a;
};
jsondiff.prototype.object_diff = function(a, b, policy) {
var diffs, key, sub_policy;
diffs = {};
if ((policy != null) && 'attributes' in policy) {
policy = policy['attributes'];
}
if ((a == null) || (b == null)) {
return {};
}
for (key in a) {
if (!__hasProp.call(a, key)) continue;
if ((policy != null) && key in policy) {
sub_policy = policy[key];
} else {
sub_policy = null;
}
if (key in b) {
if (!this.equals(a[key], b[key])) {
diffs[key] = this.diff(a[key], b[key], sub_policy);
}
} else {
diffs[key] = {
'o': '-'
};
}
}
for (key in b) {
if (!__hasProp.call(b, key)) continue;
if (!(key in a) && (b[key] != null)) {
diffs[key] = {
'o': '+',
'v': b[key]
};
}
}
return diffs;
};
jsondiff.prototype.diff = function(a, b, policy) {
var diffs, otype, typea;
if (this.equals(a, b)) {
return {};
}
if ((policy != null) && 'attributes' in policy) {
policy = policy['attributes'];
}
if ((policy != null) && 'otype' in policy) {
otype = policy['otype'];
switch (otype) {
case 'replace':
return {
'o': 'r',
'v': b
};
case 'list':
return {
'o': 'L',
'v': this.list_diff(a, b, policy)
};
case 'list_dmp':
return {
'o': 'dL',
'v': this.list_diff_dmp(a, b, policy)
};
case 'integer':
return {
'o': 'I',
'v': b - a
};
case 'string':
diffs = this.dmp.diff_main(a, b);
if (diffs.length > 2) {
this.dmp.diff_cleanupEfficiency(diffs);
}
if (diffs.length > 0) {
return {
'o': 'd',
'v': this.dmp.diff_toDelta(diffs)
};
}
}
}
typea = this.typeOf(a);
if (typea !== this.typeOf(b)) {
return {
'o': 'r',
'v': b
};
}
switch (typea) {
case 'boolean':
return {
'o': 'r',
'v': b
};
case 'number':
return {
'o': 'r',
'v': b
};
case 'array':
return {
'o': 'r',
'v': b
};
case 'object':
return {
'o': 'O',
'v': this.object_diff(a, b, policy)
};
case 'string':
diffs = this.dmp.diff_main(a, b);
if (diffs.length > 2) {
this.dmp.diff_cleanupEfficiency(diffs);
}
if (diffs.length > 0) {
return {
'o': 'd',
'v': this.dmp.diff_toDelta(diffs)
};
}
}
return {};
};
jsondiff.prototype.apply_list_diff = function(s, diffs) {
var deleted, dmp_diffs, dmp_patches, dmp_result, index, indexes, key, op, patched, s_index, shift, x, _i, _len, _ref, _ref1;
patched = this.deepCopy(s);
indexes = [];
deleted = [];
for (key in diffs) {
if (!__hasProp.call(diffs, key)) continue;
indexes.push(key);
indexes.sort();
}
for (_i = 0, _len = indexes.length; _i < _len; _i++) {
index = indexes[_i];
op = diffs[index];
shift = ((function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = deleted.length; _j < _len1; _j++) {
x = deleted[_j];
if (x <= index) {
_results.push(x);
}
}
return _results;
})()).length;
s_index = index - shift;
switch (op['o']) {
case '+':
[].splice.apply(patched, [s_index, (s_index - 1) - s_index + 1].concat(_ref = op['v'])), _ref;
break;
case '-':
[].splice.apply(patched, [s_index, s_index - s_index + 1].concat(_ref1 = [])), _ref1;
deleted[deleted.length] = s_index;
break;
case 'r':
patched[s_index] = op['v'];
break;
case 'I':
patched[s_index] += op['v'];
break;
case 'L':
patched[s_index] = this.apply_list_diff(patched[s_index], op['v']);
break;
case 'dL':
patched[s_index] = this.apply_list_diff_dmp(patched[s_index], op['v']);
break;
case 'O':
patched[s_index] = this.apply_object_diff(patched[s_index], op['v']);
break;
case 'd':
dmp_diffs = this.dmp.diff_fromDelta(patched[s_index], op['v']);
dmp_patches = this.dmp.patch_make(patched[s_index], dmp_diffs);
dmp_result = this.dmp.patch_apply(dmp_patches, patched[s_index]);
patched[s_index] = dmp_result[0];
}
}
return patched;
};
jsondiff.prototype.apply_list_diff_dmp = function(s, delta) {
var dmp_diffs, dmp_patches, dmp_result, ptext;
ptext = this._serialize_to_text(s);
dmp_diffs = this.dmp.diff_fromDelta(ptext, delta);
dmp_patches = this.dmp.patch_make(ptext, dmp_diffs);
dmp_result = this.dmp.patch_apply(dmp_patches, ptext);
return this._text_to_array(dmp_result[0]);
};
jsondiff.prototype.apply_object_diff = function(s, diffs) {
var key, op, patched;
patched = this.deepCopy(s);
for (key in diffs) {
if (!__hasProp.call(diffs, key)) continue;
op = diffs[key];
if (op['o'] === '-') {
delete patched[key];
} else {
patched[key] = this.apply_diff(patched[key], op);
}
}
return patched;
};
jsondiff.prototype.apply_object_diff_with_offsets = function(s, diffs, field, offsets) {
var dmp_diffs, dmp_patches, dmp_result, key, op, patched;
patched = this.deepCopy(s);
for (key in diffs) {
if (!__hasProp.call(diffs, key)) continue;
op = diffs[key];
switch (op['o']) {
case '+':
patched[key] = op['v'];
break;
case '-':
delete patched[key];
break;
case 'r':
patched[key] = op['v'];
break;
case 'I':
patched[key] += op['v'];
break;
case 'L':
patched[key] = this.apply_list_diff(patched[key], op['v']);
break;
case 'O':
patched[key] = this.apply_object_diff(patched[key], op['v']);
break;
case 'd':
dmp_diffs = this.dmp.diff_fromDelta(patched[key], op['v']);
dmp_patches = this.dmp.patch_make(patched[key], dmp_diffs);
if (key === field) {
patched[key] = this.patch_apply_with_offsets(dmp_patches, patched[key], offsets);
} else {
dmp_result = this.dmp.patch_apply(dmp_patches, patched[key]);
patched[key] = dmp_result[0];
}
}
}
return patched;
};
jsondiff.prototype.apply_diff = function(a, op) {
var dmp_diffs, dmp_patches, dmp_result;
switch (op['o']) {
case '+':
return op['v'];
case '-':
return null;
case 'r':
return op['v'];
case 'I':
return a + op['v'];
case 'L':
return this.apply_list_diff(a, op['v']);
case 'dL':
return this.apply_list_diff_dmp(a, op['v']);
case 'O':
return this.apply_object_diff(a, op['v']);
case 'd':
dmp_diffs = this.dmp.diff_fromDelta(a, op['v']);
dmp_patches = this.dmp.patch_make(a, dmp_diffs);
dmp_result = this.dmp.patch_apply(dmp_patches, a);
return dmp_result[0];
}
};
jsondiff.prototype.transform_list_diff = function(ad, bd, s, policy) {
var ad_new, b_deletes, b_inserts, diff, index, last_index, last_shift, op, other_op, shift_l, shift_r, sindex, target_op, x;
ad_new = {};
b_inserts = [];
b_deletes = [];
if ((policy != null) && 'item' in policy) {
policy = policy['item'];
} else {
policy = null;
}
for (index in bd) {
if (!__hasProp.call(bd, index)) continue;
op = bd[index];
index = parseInt(index);
if (op['o'] === '+') {
b_inserts.push(index);
}
if (op['o'] === '-') {
b_deletes.push(index);
}
}
last_index = 0;
last_shift = 0;
for (index in ad) {
if (!__hasProp.call(ad, index)) continue;
op = ad[index];
index = parseInt(index);
shift_r = ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = b_inserts.length; _i < _len; _i++) {
x = b_inserts[_i];
if (x < index) {
_results.push(x);
}
}
return _results;
})()).length;
shift_l = ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = b_deletes.length; _i < _len; _i++) {
x = b_deletes[_i];
if (x < index) {
_results.push(x);
}
}
return _results;
})()).length;
if (last_index + 1 === index) {
index = index + last_shift;
} else {
index = index + shift_r - shift_l;
}
last_index = index;
last_shift = shift_r - shift_l;
sindex = String(index);
ad_new[sindex] = op;
if (sindex in bd) {
if (op['o'] === '+' && bd[index]['o'] === '+') {
continue;
} else if (op['o'] === '-') {
if (bd[index]['o'] === '-') {
delete ad_new[sindex];
}
} else if (bd[index]['o'] === '-') {
if (op['o'] === 'r') {
ad_new[sindex] = {
'o': '+',
'v': op['v']
};
}
if (op['o'] === !'+') {
ad_new[sindex] = {
'o': '+',
'v': this.apply_object_diff(s[sindex], op['v'])
};
}
} else {
target_op = {};
target_op[sindex] = op;
other_op = {};
other_op[sindex] = bd[index];
diff = this.transform_object_diff(target_op, other_op, s, policy);
ad_new[sindex] = diff[sindex];
}
}
}
return ad_new;
};
jsondiff.prototype.transform_list_diff_dmp = function(ad, bd, s, policy) {
var a_patches, ab_text, b_patches, b_text, dmp_diffs, stext;
stext = this._serialize_to_text(s);
a_patches = this.dmp.patch_make(stext, this.dmp.diff_fromDelta(stext, ad));
b_patches = this.dmp.patch_make(stext, this.dmp.diff_fromDelta(stext, bd));
b_text = (this.dmp.patch_apply(b_patches, stext))[0];
ab_text = (this.dmp.patch_apply(a_patches, b_text))[0];
if (ab_text !== b_text) {
dmp_diffs = this.dmp.diff_lineMode_(b_text, ab_text);
if (dmp_diffs.length > 2) {
this.dmp.diff_cleanupEfficiency(dmp_diffs);
}
if (dmp_diffs.length > 0) {
return this.dmp.diff_toDelta(dmp_diffs);
}
}
return "";
};
jsondiff.prototype.transform_object_diff = function(ad, bd, s, policy) {
var a_patches, ab_text, ad_new, aop, b_patches, b_text, bop, dmp_diffs, key, sk, _ref;
ad_new = this.deepCopy(ad);
if ((policy != null) && 'attributes' in policy) {
policy = policy['attributes'];
}
for (key in ad) {
if (!__hasProp.call(ad, key)) continue;
aop = ad[key];
if (!(key in bd)) {
continue;
}
if ((policy != null) && 'attributes' in policy) {
policy = policy['attributes'];
if ((policy != null) && key in policy) {
policy = policy[key];
} else {
policy = null;
}
} else {
policy = null;
}
sk = s[key];
bop = bd[key];
if (aop['o'] === '+' && bop['o'] === '+') {
if (this.equals(aop['v'], bop['v'])) {
delete ad_new[key];
} else {
ad_new[key] = this.diff(bop['v'], aop['v'], policy);
}
} else if (aop['o'] === '-' && bop['o'] === '-') {
delete ad_new[key];
} else if (bop['o'] === '-' && ((_ref = aop['o']) !== '+' && _ref !== '-')) {
ad_new[key] = {
'o': '+'
};
ad_new[key]['v'] = this.apply_diff(sk, aop);
} else if (aop['o'] === 'O' && bop['o'] === 'O') {
ad_new[key] = {
'o': 'O',
'v': this.transform_object_diff(aop['v'], bop['v'], sk, policy)
};
} else if (aop['o'] === 'L' && bop['o'] === 'L') {
ad_new[key] = {
'o': 'L',
'v': this.transform_list_diff(aop['v'], bop['v'], sk, policy)
};
} else if (aop['o'] === 'dL' && bop['o'] === 'dL') {
ad_new[key] = {
'o': 'dL',
'v': this.transform_list_diff_dmp(aop['v'], bop['v'], sk, policy)
};
} else if (aop['o'] === 'd' && bop['o'] === 'd') {
delete ad_new[key];
a_patches = this.dmp.patch_make(sk, this.dmp.diff_fromDelta(sk, aop['v']));
b_patches = this.dmp.patch_make(sk, this.dmp.diff_fromDelta(sk, bop['v']));
b_text = (this.dmp.patch_apply(b_patches, sk))[0];
ab_text = (this.dmp.patch_apply(a_patches, b_text))[0];
if (ab_text !== b_text) {
dmp_diffs = this.dmp.diff_main(b_text, ab_text);
if (dmp_diffs.length > 2) {
this.dmp.diff_cleanupEfficiency(dmp_diffs);
}
if (dmp_diffs.length > 0) {
ad_new[key] = {
'o': 'd',
'v': this.dmp.diff_toDelta(dmp_diffs)
};
}
}
}
return ad_new;
}
};
jsondiff.prototype.patch_apply_with_offsets = function(patches, text, offsets) {
var del_end, del_start, delta, diffs, end_loc, expected_loc, i, index1, index2, mod, nullPadding, start_loc, text1, text2, x, y, _i, _j, _k, _l, _ref, _ref1, _ref2, _ref3;
if (patches.length === 0) {
return text;
}
patches = this.dmp.patch_deepCopy(patches);
nullPadding = this.dmp.patch_addPadding(patches);
text = nullPadding + text + nullPadding;
this.dmp.patch_splitMax(patches);
delta = 0;
for (x = _i = 0, _ref = patches.length; 0 <= _ref ? _i < _ref : _i > _ref; x = 0 <= _ref ? ++_i : --_i) {
expected_loc = patches[x].start2 + delta;
text1 = this.dmp.diff_text1(patches[x].diffs);
end_loc = -1;
if (text1.length > this.dmp.Match_MaxBits) {
start_loc = this.dmp.match_main(text, text1.substring(0, this.dmp.Match_MaxBits), expected_loc);
if (start_loc !== -1) {
end_loc = this.dmp.match_main(text, text1.substring(text1.length - this.dmp.Match_MaxBits), expected_loc + text1.length - this.dmp.Match_MaxBits);
if (end_loc === -1 || start_loc >= end_loc) {
start_loc = -1;
}
}
} else {
start_loc = this.dmp.match_main(text, text1, expected_loc);
}
if (start_loc === -1) {
delta -= patches[x].length2 - patches[x].length1;
} else {
delta = start_loc - expected_loc;
if (end_loc === -1) {
text2 = text.substring(start_loc, start_loc + text1.length);
} else {
text2 = text.substring(start_loc, end_loc + this.dmp.Match_MaxBits);
}
diffs = this.dmp.diff_main(text1, text2, false);
if (text1.length > this.dmp.Match_MaxBits && this.dmp.diff_levenshtein(diffs) / text1.length > this.dmp.Patch_DeleteThreshold) {
} else {
index1 = 0;
for (y = _j = 0, _ref1 = patches[x].diffs.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; y = 0 <= _ref1 ? ++_j : --_j) {
mod = patches[x].diffs[y];
if (mod[0] !== DIFF_EQUAL) {
index2 = this.dmp.diff_xIndex(diffs, index1);
}
if (mod[0] === DIFF_INSERT) {
text = text.substring(0, start_loc + index2) + mod[1] + text.substring(start_loc + index2);
for (i = _k = 0, _ref2 = offsets.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) {
if (offsets[i] + nullPadding.length > start_loc + index2) {
offsets[i] += mod[1].length;
}
}
} else if (mod[0] === DIFF_DELETE) {
del_start = start_loc + index2;
del_end = start_loc + this.dmp.diff_xIndex(diffs, index1 + mod[1].length);
text = text.substring(0, del_start) + text.substring(del_end);
for (i = _l = 0, _ref3 = offsets.length; 0 <= _ref3 ? _l < _ref3 : _l > _ref3; i = 0 <= _ref3 ? ++_l : --_l) {
if (offsets[i] + nullPadding.length > del_start) {
if (offsets[i] + nullPadding.length < del_end) {
offsets[i] = del_start - nullPadding.length;
} else {
offsets[i] -= del_end - del_start;
}
}
}
}
if (mod[0] !== DIFF_DELETE) {
index1 += mod[1].length;
}
}
}
}
}
text = text.substring(nullPadding.length, text.length - nullPadding.length);
return text;
};
return jsondiff;
})();
window['jsondiff'] = jsondiff;
}).call(this);
; browserify_shim__define__module__export__(typeof jsondiff != "undefined" ? jsondiff : window.jsondiff);
}).call(global, undefined, undefined, undefined, function defineExport(ex) { module.exports = ex; });
},{}],"jsondiff":[function(require,module,exports){
module.exports=require('oUUvvc');
},{}],"+z1VBF":[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};(function browserifyShim(module, exports, define, browserify_shim__define__module__export__) {
/* SockJS client, version 0.3.4, http://sockjs.org, MIT License
Copyright (c) 2011-2012 VMware, Inc.
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.
*/
// JSON2 by Douglas Crockford (minified).
var JSON;JSON||(JSON={}),function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i&&typeof i=="object"&&typeof i.toJSON=="function"&&(i=i.toJSON(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1)h[c]=str(c,i)||"null";e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g;return e}if(rep&&typeof rep=="object"){f=rep.length;for(c=0;c<f;c+=1)typeof rep[c]=="string"&&(d=rep[c],e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e))}else for(d in i)Object.prototype.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g;return e}}function quote(a){escapable.lastIndex=0;return escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b=="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function f(a){return a<10?"0"+a:a}"use strict",typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()});var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;typeof JSON.stringify!="function"&&(JSON.stringify=function(a,b,c){var d;gap="",indent="";if(typeof c=="number")for(d=0;d<c;d+=1)indent+=" ";else typeof c=="string"&&(indent=c);rep=b;if(!b||typeof b=="function"||typeof b=="object"&&typeof b.length=="number")return str("",{"":a});throw new Error("JSON.stringify")}),typeof JSON.parse!="function"&&(JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=walk(e,c),d!==undefined?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver=="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")})}()
// [*] Including lib/index.js
// Public object
SockJS = (function(){
var _document = document;
var _window = window;
var utils = {};
// [*] Including lib/reventtarget.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
/* Simplified implementation of DOM2 EventTarget.
* http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget
*/
var REventTarget = function() {};
REventTarget.prototype.addEventListener = function (eventType, listener) {
if(!this._listeners) {
this._listeners = {};
}
if(!(eventType in this._listeners)) {
this._listeners[eventType] = [];
}
var arr = this._listeners[eventType];
if(utils.arrIndexOf(arr, listener) === -1) {
arr.push(listener);
}
return;
};
REventTarget.prototype.removeEventListener = function (eventType, listener) {
if(!(this._listeners && (eventType in this._listeners))) {
return;
}
var arr = this._listeners[eventType];
var idx = utils.arrIndexOf(arr, listener);
if (idx !== -1) {
if(arr.length > 1) {
this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) );
} else {
delete this._listeners[eventType];
}
return;
}
return;
};
REventTarget.prototype.dispatchEvent = function (event) {
var t = event.type;
var args = Array.prototype.slice.call(arguments, 0);
if (this['on'+t]) {
this['on'+t].apply(this, args);
}
if (this._listeners && t in this._listeners) {
for(var i=0; i < this._listeners[t].length; i++) {
this._listeners[t][i].apply(this, args);
}
}
};
// [*] End of lib/reventtarget.js
// [*] Including lib/simpleevent.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var SimpleEvent = function(type, obj) {
this.type = type;
if (typeof obj !== 'undefined') {
for(var k in obj) {
if (!obj.hasOwnProperty(k)) continue;
this[k] = obj[k];
}
}
};
SimpleEvent.prototype.toString = function() {
var r = [];
for(var k in this) {
if (!this.hasOwnProperty(k)) continue;
var v = this[k];
if (typeof v === 'function') v = '[function]';
r.push(k + '=' + v);
}
return 'SimpleEvent(' + r.join(', ') + ')';
};
// [*] End of lib/simpleevent.js
// [*] Including lib/eventemitter.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventEmitter = function(events) {
var that = this;
that._events = events || [];
that._listeners = {};
};
EventEmitter.prototype.emit = function(type) {
var that = this;
that._verifyType(type);
if (that._nuked) return;
var args = Array.prototype.slice.call(arguments, 1);
if (that['on'+type]) {
that['on'+type].apply(that, args);
}
if (type in that._listeners) {
for(var i = 0; i < that._listeners[type].length; i++) {
that._listeners[type][i].apply(that, args);
}
}
};
EventEmitter.prototype.on = function(type, callback) {
var that = this;
that._verifyType(type);
if (that._nuked) return;
if (!(type in that._listeners)) {
that._listeners[type] = [];
}
that._listeners[type].push(callback);
};
EventEmitter.prototype._verifyType = function(type) {
var that = this;
if (utils.arrIndexOf(that._events, type) === -1) {
utils.log('Event ' + JSON.stringify(type) +
' not listed ' + JSON.stringify(that._events) +
' in ' + that);
}
};
EventEmitter.prototype.nuke = function() {
var that = this;
that._nuked = true;
for(var i=0; i<that._events.length; i++) {
delete that[that._events[i]];
}
that._listeners = {};
};
// [*] End of lib/eventemitter.js
// [*] Including lib/utils.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var random_string_chars = 'abcdefghijklmnopqrstuvwxyz0123456789_';
utils.random_string = function(length, max) {
max = max || random_string_chars.length;
var i, ret = [];
for(i=0; i < length; i++) {
ret.push( random_string_chars.substr(Math.floor(Math.random() * max),1) );
}
return ret.join('');
};
utils.random_number = function(max) {
return Math.floor(Math.random() * max);
};
utils.random_number_string = function(max) {
var t = (''+(max - 1)).length;
var p = Array(t+1).join('0');
return (p + utils.random_number(max)).slice(-t);
};
// Assuming that url looks like: http://asdasd:111/asd
utils.getOrigin = function(url) {
url += '/';
var parts = url.split('/').slice(0, 3);
return parts.join('/');
};
utils.isSameOriginUrl = function(url_a, url_b) {
// location.origin would do, but it's not always available.
if (!url_b) url_b = _window.location.href;
return (url_a.split('/').slice(0,3).join('/')
===
url_b.split('/').slice(0,3).join('/'));
};
utils.getParentDomain = function(url) {
// ipv4 ip address
if (/^[0-9.]*$/.test(url)) return url;
// ipv6 ip address
if (/^\[/.test(url)) return url;
// no dots
if (!(/[.]/.test(url))) return url;
var parts = url.split('.').slice(1);
return parts.join('.');
};
utils.objectExtend = function(dst, src) {
for(var k in src) {
if (src.hasOwnProperty(k)) {
dst[k] = src[k];
}
}
return dst;
};
var WPrefix = '_jp';
utils.polluteGlobalNamespace = function() {
if (!(WPrefix in _window)) {
_window[WPrefix] = {};
}
};
utils.closeFrame = function (code, reason) {
return 'c'+JSON.stringify([code, reason]);
};
utils.userSetCode = function (code) {
return code === 1000 || (code >= 3000 && code <= 4999);
};
// See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
// and RFC 2988.
utils.countRTO = function (rtt) {
var rto;
if (rtt > 100) {
rto = 3 * rtt; // rto > 300msec
} else {
rto = rtt + 200; // 200msec < rto <= 300msec
}
return rto;
}
utils.log = function() {
if (_window.console && console.log && console.log.apply) {
console.log.apply(console, arguments);
}
};
utils.bind = function(fun, that) {
if (fun.bind) {
return fun.bind(that);
} else {
return function() {
return fun.apply(that, arguments);
};
}
};
utils.flatUrl = function(url) {
return url.indexOf('?') === -1 && url.indexOf('#') === -1;
};
utils.amendUrl = function(url) {
var dl = _document.location;
if (!url) {
throw new Error('Wrong url for SockJS');
}
if (!utils.flatUrl(url)) {
throw new Error('Only basic urls are supported in SockJS');
}
// '//abc' --> 'http://abc'
if (url.indexOf('//') === 0) {
url = dl.protocol + url;
}
// '/abc' --> 'http://localhost:80/abc'
if (url.indexOf('/') === 0) {
url = dl.protocol + '//' + dl.host + url;
}
// strip trailing slashes
url = url.replace(/[/]+$/,'');
return url;
};
// IE doesn't support [].indexOf.
utils.arrIndexOf = function(arr, obj){
for(var i=0; i < arr.length; i++){
if(arr[i] === obj){
return i;
}
}
return -1;
};
utils.arrSkip = function(arr, obj) {
var idx = utils.arrIndexOf(arr, obj);
if (idx === -1) {
return arr.slice();
} else {
var dst = arr.slice(0, idx);
return dst.concat(arr.slice(idx+1));
}
};
// Via: https://gist.github.com/1133122/2121c601c5549155483f50be3da5305e83b8c5df
utils.isArray = Array.isArray || function(value) {
return {}.toString.call(value).indexOf('Array') >= 0
};
utils.delay = function(t, fun) {
if(typeof t === 'function') {
fun = t;
t = 0;
}
return setTimeout(fun, t);
};
// Chars worth escaping, as defined by Douglas Crockford:
// https://github.com/douglascrockford/JSON-js/blob/47a9882cddeb1e8529e07af9736218075372b8ac/json2.js#L196
var json_escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
json_lookup = {
"\u0000":"\\u0000","\u0001":"\\u0001","\u0002":"\\u0002","\u0003":"\\u0003",
"\u0004":"\\u0004","\u0005":"\\u0005","\u0006":"\\u0006","\u0007":"\\u0007",
"\b":"\\b","\t":"\\t","\n":"\\n","\u000b":"\\u000b","\f":"\\f","\r":"\\r",
"\u000e":"\\u000e","\u000f":"\\u000f","\u0010":"\\u0010","\u0011":"\\u0011",
"\u0012":"\\u0012","\u0013":"\\u0013","\u0014":"\\u0014","\u0015":"\\u0015",
"\u0016":"\\u0016","\u0017":"\\u0017","\u0018":"\\u0018","\u0019":"\\u0019",
"\u001a":"\\u001a","\u001b":"\\u001b","\u001c":"\\u001c","\u001d":"\\u001d",
"\u001e":"\\u001e","\u001f":"\\u001f","\"":"\\\"","\\":"\\\\",
"\u007f":"\\u007f","\u0080":"\\u0080","\u0081":"\\u0081","\u0082":"\\u0082",
"\u0083":"\\u0083","\u0084":"\\u0084","\u0085":"\\u0085","\u0086":"\\u0086",
"\u0087":"\\u0087","\u0088":"\\u0088","\u0089":"\\u0089","\u008a":"\\u008a",
"\u008b":"\\u008b","\u008c":"\\u008c","\u008d":"\\u008d","\u008e":"\\u008e",
"\u008f":"\\u008f","\u0090":"\\u0090","\u0091":"\\u0091","\u0092":"\\u0092",
"\u0093":"\\u0093","\u0094":"\\u0094","\u0095":"\\u0095","\u0096":"\\u0096",
"\u0097":"\\u0097","\u0098":"\\u0098","\u0099":"\\u0099","\u009a":"\\u009a",
"\u009b":"\\u009b","\u009c":"\\u009c","\u009d":"\\u009d","\u009e":"\\u009e",
"\u009f":"\\u009f","\u00ad":"\\u00ad","\u0600":"\\u0600","\u0601":"\\u0601",
"\u0602":"\\u0602","\u0603":"\\u0603","\u0604":"\\u0604","\u070f":"\\u070f",
"\u17b4":"\\u17b4","\u17b5":"\\u17b5","\u200c":"\\u200c","\u200d":"\\u200d",
"\u200e":"\\u200e","\u200f":"\\u200f","\u2028":"\\u2028","\u2029":"\\u2029",
"\u202a":"\\u202a","\u202b":"\\u202b","\u202c":"\\u202c","\u202d":"\\u202d",
"\u202e":"\\u202e","\u202f":"\\u202f","\u2060":"\\u2060","\u2061":"\\u2061",
"\u2062":"\\u2062","\u2063":"\\u2063","\u2064":"\\u2064","\u2065":"\\u2065",
"\u2066":"\\u2066","\u2067":"\\u2067","\u2068":"\\u2068","\u2069":"\\u2069",
"\u206a":"\\u206a","\u206b":"\\u206b","\u206c":"\\u206c","\u206d":"\\u206d",
"\u206e":"\\u206e","\u206f":"\\u206f","\ufeff":"\\ufeff","\ufff0":"\\ufff0",
"\ufff1":"\\ufff1","\ufff2":"\\ufff2","\ufff3":"\\ufff3","\ufff4":"\\ufff4",
"\ufff5":"\\ufff5","\ufff6":"\\ufff6","\ufff7":"\\ufff7","\ufff8":"\\ufff8",
"\ufff9":"\\ufff9","\ufffa":"\\ufffa","\ufffb":"\\ufffb","\ufffc":"\\ufffc",
"\ufffd":"\\ufffd","\ufffe":"\\ufffe","\uffff":"\\uffff"};
// Some extra characters that Chrome gets wrong, and substitutes with
// something else on the wire.
var extra_escapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g,
extra_lookup;
// JSON Quote string. Use native implementation when possible.
var JSONQuote = (JSON && JSON.stringify) || function(string) {
json_escapable.lastIndex = 0;
if (json_escapable.test(string)) {
string = string.replace(json_escapable, function(a) {
return json_lookup[a];
});
}
return '"' + string + '"';
};
// This may be quite slow, so let's delay until user actually uses bad
// characters.
var unroll_lookup = function(escapable) {
var i;
var unrolled = {}
var c = []
for(i=0; i<65536; i++) {
c.push( String.fromCharCode(i) );
}
escapable.lastIndex = 0;
c.join('').replace(escapable, function (a) {
unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
return '';
});
escapable.lastIndex = 0;
return unrolled;
};
// Quote string, also taking care of unicode characters that browsers
// often break. Especially, take care of unicode surrogates:
// http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
utils.quote = function(string) {
var quoted = JSONQuote(string);
// In most cases this should be very fast and good enough.
extra_escapable.lastIndex = 0;
if(!extra_escapable.test(quoted)) {
return quoted;
}
if(!extra_lookup) extra_lookup = unroll_lookup(extra_escapable);
return quoted.replace(extra_escapable, function(a) {
return extra_lookup[a];
});
}
var _all_protocols = ['websocket',
'xdr-streaming',
'xhr-streaming',
'iframe-eventsource',
'iframe-htmlfile',
'xdr-polling',
'xhr-polling',
'iframe-xhr-polling',
'jsonp-polling'];
utils.probeProtocols = function() {
var probed = {};
for(var i=0; i<_all_protocols.length; i++) {
var protocol = _all_protocols[i];
// User can have a typo in protocol name.
probed[protocol] = SockJS[protocol] &&
SockJS[protocol].enabled();
}
return probed;
};
utils.detectProtocols = function(probed, protocols_whitelist, info) {
var pe = {},
protocols = [];
if (!protocols_whitelist) protocols_whitelist = _all_protocols;
for(var i=0; i<protocols_whitelist.length; i++) {
var protocol = protocols_whitelist[i];
pe[protocol] = probed[protocol];
}
var maybe_push = function(protos) {
var proto = protos.shift();
if (pe[proto]) {
protocols.push(proto);
} else {
if (protos.length > 0) {
maybe_push(protos);
}
}
}
// 1. Websocket
if (info.websocket !== false) {
maybe_push(['websocket']);
}
// 2. Streaming
if (pe['xhr-streaming'] && !info.null_origin) {
protocols.push('xhr-streaming');
} else {
if (pe['xdr-streaming'] && !info.cookie_needed && !info.null_origin) {
protocols.push('xdr-streaming');
} else {
maybe_push(['iframe-eventsource',
'iframe-htmlfile']);
}
}
// 3. Polling
if (pe['xhr-polling'] && !info.null_origin) {
protocols.push('xhr-polling');
} else {
if (pe['xdr-polling'] && !info.cookie_needed && !info.null_origin) {
protocols.push('xdr-polling');
} else {
maybe_push(['iframe-xhr-polling',
'jsonp-polling']);
}
}
return protocols;
}
// [*] End of lib/utils.js
// [*] Including lib/dom.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// May be used by htmlfile jsonp and transports.
var MPrefix = '_sockjs_global';
utils.createHook = function() {
var window_id = 'a' + utils.random_string(8);
if (!(MPrefix in _window)) {
var map = {};
_window[MPrefix] = function(window_id) {
if (!(window_id in map)) {
map[window_id] = {
id: window_id,
del: function() {delete map[window_id];}
};
}
return map[window_id];
}
}
return _window[MPrefix](window_id);
};
utils.attachMessage = function(listener) {
utils.attachEvent('message', listener);
};
utils.attachEvent = function(event, listener) {
if (typeof _window.addEventListener !== 'undefined') {
_window.addEventListener(event, listener, false);
} else {
// IE quirks.
// According to: http://stevesouders.com/misc/test-postmessage.php
// the message gets delivered only to 'document', not 'window'.
_document.attachEvent("on" + event, listener);
// I get 'window' for ie8.
_window.attachEvent("on" + event, listener);
}
};
utils.detachMessage = function(listener) {
utils.detachEvent('message', listener);
};
utils.detachEvent = function(event, listener) {
if (typeof _window.addEventListener !== 'undefined') {
_window.removeEventListener(event, listener, false);
} else {
_document.detachEvent("on" + event, listener);
_window.detachEvent("on" + event, listener);
}
};
var on_unload = {};
// Things registered after beforeunload are to be called immediately.
var after_unload = false;
var trigger_unload_callbacks = function() {
for(var ref in on_unload) {
on_unload[ref]();
delete on_unload[ref];
};
};
var unload_triggered = function() {
if(after_unload) return;
after_unload = true;
trigger_unload_callbacks();
};
// 'unload' alone is not reliable in opera within an iframe, but we
// can't use `beforeunload` as IE fires it on javascript: links.
utils.attachEvent('unload', unload_triggered);
utils.unload_add = function(listener) {
var ref = utils.random_string(8);
on_unload[ref] = listener;
if (after_unload) {
utils.delay(trigger_unload_callbacks);
}
return ref;
};
utils.unload_del = function(ref) {
if (ref in on_unload)
delete on_unload[ref];
};
utils.createIframe = function (iframe_url, error_callback) {
var iframe = _document.createElement('iframe');
var tref, unload_ref;
var unattach = function() {
clearTimeout(tref);
// Explorer had problems with that.
try {iframe.onload = null;} catch (x) {}
iframe.onerror = null;
};
var cleanup = function() {
if (iframe) {
unattach();
// This timeout makes chrome fire onbeforeunload event
// within iframe. Without the timeout it goes straight to
// onunload.
setTimeout(function() {
if(iframe) {
iframe.parentNode.removeChild(iframe);
}
iframe = null;
}, 0);
utils.unload_del(unload_ref);
}
};
var onerror = function(r) {
if (iframe) {
cleanup();
error_callback(r);
}
};
var post = function(msg, origin) {
try {
// When the iframe is not loaded, IE raises an exception
// on 'contentWindow'.
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(msg, origin);
}
} catch (x) {};
};
iframe.src = iframe_url;
iframe.style.display = 'none';
iframe.style.position = 'absolute';
iframe.onerror = function(){onerror('onerror');};
iframe.onload = function() {
// `onload` is triggered before scripts on the iframe are
// executed. Give it few seconds to actually load stuff.
clearTimeout(tref);
tref = setTimeout(function(){onerror('onload timeout');}, 2000);
};
_document.body.appendChild(iframe);
tref = setTimeout(function(){onerror('timeout');}, 15000);
unload_ref = utils.unload_add(cleanup);
return {
post: post,
cleanup: cleanup,
loaded: unattach
};
};
utils.createHtmlfile = function (iframe_url, error_callback) {
var doc = new ActiveXObject('htmlfile');
var tref, unload_ref;
var iframe;
var unattach = function() {
clearTimeout(tref);
};
var cleanup = function() {
if (doc) {
unattach();
utils.unload_del(unload_ref);
iframe.parentNode.removeChild(iframe);
iframe = doc = null;
CollectGarbage();
}
};
var onerror = function(r) {
if (doc) {
cleanup();
error_callback(r);
}
};
var post = function(msg, origin) {
try {
// When the iframe is not loaded, IE raises an exception
// on 'contentWindow'.
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(msg, origin);
}
} catch (x) {};
};
doc.open();
doc.write('<html><s' + 'cript>' +
'document.domain="' + document.domain + '";' +
'</s' + 'cript></html>');
doc.close();
doc.parentWindow[WPrefix] = _window[WPrefix];
var c = doc.createElement('div');
doc.body.appendChild(c);
iframe = doc.createElement('iframe');
c.appendChild(iframe);
iframe.src = iframe_url;
tref = setTimeout(function(){onerror('timeout');}, 15000);
unload_ref = utils.unload_add(cleanup);
return {
post: post,
cleanup: cleanup,
loaded: unattach
};
};
// [*] End of lib/dom.js
// [*] Including lib/dom2.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var AbstractXHRObject = function(){};
AbstractXHRObject.prototype = new EventEmitter(['chunk', 'finish']);
AbstractXHRObject.prototype._start = function(method, url, payload, opts) {
var that = this;
try {
that.xhr = new XMLHttpRequest();
} catch(x) {};
if (!that.xhr) {
try {
that.xhr = new _window.ActiveXObject('Microsoft.XMLHTTP');
} catch(x) {};
}
if (_window.ActiveXObject || _window.XDomainRequest) {
// IE8 caches even POSTs
url += ((url.indexOf('?') === -1) ? '?' : '&') + 't='+(+new Date);
}
// Explorer tends to keep connection open, even after the
// tab gets closed: http://bugs.jquery.com/ticket/5280
that.unload_ref = utils.unload_add(function(){that._cleanup(true);});
try {
that.xhr.open(method, url, true);
} catch(e) {
// IE raises an exception on wrong port.
that.emit('finish', 0, '');
that._cleanup();
return;
};
if (!opts || !opts.no_credentials) {
// Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest :
// "This never affects same-site requests."
that.xhr.withCredentials = 'true';
}
if (opts && opts.headers) {
for(var key in opts.headers) {
that.xhr.setRequestHeader(key, opts.headers[key]);
}
}
that.xhr.onreadystatechange = function() {
if (that.xhr) {
var x = that.xhr;
switch (x.readyState) {
case 3:
// IE doesn't like peeking into responseText or status
// on Microsoft.XMLHTTP and readystate=3
try {
var status = x.status;
var text = x.responseText;
} catch (x) {};
// IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
if (status === 1223) status = 204;
// IE does return readystate == 3 for 404 answers.
if (text && text.length > 0) {
that.emit('chunk', status, text);
}
break;
case 4:
var status = x.status;
// IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
if (status === 1223) status = 204;
that.emit('finish', status, x.responseText);
that._cleanup(false);
break;
}
}
};
that.xhr.send(payload);
};
AbstractXHRObject.prototype._cleanup = function(abort) {
var that = this;
if (!that.xhr) return;
utils.unload_del(that.unload_ref);
// IE needs this field to be a function
that.xhr.onreadystatechange = function(){};
if (abort) {
try {
that.xhr.abort();
} catch(x) {};
}
that.unload_ref = that.xhr = null;
};
AbstractXHRObject.prototype.close = function() {
var that = this;
that.nuke();
that._cleanup(true);
};
var XHRCorsObject = utils.XHRCorsObject = function() {
var that = this, args = arguments;
utils.delay(function(){that._start.apply(that, args);});
};
XHRCorsObject.prototype = new AbstractXHRObject();
var XHRLocalObject = utils.XHRLocalObject = function(method, url, payload) {
var that = this;
utils.delay(function(){
that._start(method, url, payload, {
no_credentials: true
});
});
};
XHRLocalObject.prototype = new AbstractXHRObject();
// References:
// http://ajaxian.com/archives/100-line-ajax-wrapper
// http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx
var XDRObject = utils.XDRObject = function(method, url, payload) {
var that = this;
utils.delay(function(){that._start(method, url, payload);});
};
XDRObject.prototype = new EventEmitter(['chunk', 'finish']);
XDRObject.prototype._start = function(method, url, payload) {
var that = this;
var xdr = new XDomainRequest();
// IE caches even POSTs
url += ((url.indexOf('?') === -1) ? '?' : '&') + 't='+(+new Date);
var onerror = xdr.ontimeout = xdr.onerror = function() {
that.emit('finish', 0, '');
that._cleanup(false);
};
xdr.onprogress = function() {
that.emit('chunk', 200, xdr.responseText);
};
xdr.onload = function() {
that.emit('finish', 200, xdr.responseText);
that._cleanup(false);
};
that.xdr = xdr;
that.unload_ref = utils.unload_add(function(){that._cleanup(true);});
try {
// Fails with AccessDenied if port number is bogus
that.xdr.open(method, url);
that.xdr.send(payload);
} catch(x) {
onerror();
}
};
XDRObject.prototype._cleanup = function(abort) {
var that = this;
if (!that.xdr) return;
utils.unload_del(that.unload_ref);
that.xdr.ontimeout = that.xdr.onerror = that.xdr.onprogress =
that.xdr.onload = null;
if (abort) {
try {
that.xdr.abort();
} catch(x) {};
}
that.unload_ref = that.xdr = null;
};
XDRObject.prototype.close = function() {
var that = this;
that.nuke();
that._cleanup(true);
};
// 1. Is natively via XHR
// 2. Is natively via XDR
// 3. Nope, but postMessage is there so it should work via the Iframe.
// 4. Nope, sorry.
utils.isXHRCorsCapable = function() {
if (_window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()) {
return 1;
}
// XDomainRequest doesn't work if page is served from file://
if (_window.XDomainRequest && _document.domain) {
return 2;
}
if (IframeTransport.enabled()) {
return 3;
}
return 4;
};
// [*] End of lib/dom2.js
// [*] Including lib/sockjs.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var SockJS = function(url, dep_protocols_whitelist, options) {
if (this === _window) {
// makes `new` optional
return new SockJS(url, dep_protocols_whitelist, options);
}
var that = this, protocols_whitelist;
that._options = {devel: false, debug: false, protocols_whitelist: [],
info: undefined, rtt: undefined};
if (options) {
utils.objectExtend(that._options, options);
}
that._base_url = utils.amendUrl(url);
that._server = that._options.server || utils.random_number_string(1000);
if (that._options.protocols_whitelist &&
that._options.protocols_whitelist.length) {
protocols_whitelist = that._options.protocols_whitelist;
} else {
// Deprecated API
if (typeof dep_protocols_whitelist === 'string' &&
dep_protocols_whitelist.length > 0) {
protocols_whitelist = [dep_protocols_whitelist];
} else if (utils.isArray(dep_protocols_whitelist)) {
protocols_whitelist = dep_protocols_whitelist
} else {
protocols_whitelist = null;
}
if (protocols_whitelist) {
that._debug('Deprecated API: Use "protocols_whitelist" option ' +
'instead of supplying protocol list as a second ' +
'parameter to SockJS constructor.');
}
}
that._protocols = [];
that.protocol = null;
that.readyState = SockJS.CONNECTING;
that._ir = createInfoReceiver(that._base_url);
that._ir.onfinish = function(info, rtt) {
that._ir = null;
if (info) {
if (that._options.info) {
// Override if user supplies the option
info = utils.objectExtend(info, that._options.info);
}
if (that._options.rtt) {
rtt = that._options.rtt;
}
that._applyInfo(info, rtt, protocols_whitelist);
that._didClose();
} else {
that._didClose(1002, 'Can\'t connect to server', true);
}
};
};
// Inheritance
SockJS.prototype = new REventTarget();
SockJS.version = "0.3.4";
SockJS.CONNECTING = 0;
SockJS.OPEN = 1;
SockJS.CLOSING = 2;
SockJS.CLOSED = 3;
SockJS.prototype._debug = function() {
if (this._options.debug)
utils.log.apply(utils, arguments);
};
SockJS.prototype._dispatchOpen = function() {
var that = this;
if (that.readyState === SockJS.CONNECTING) {
if (that._transport_tref) {
clearTimeout(that._transport_tref);
that._transport_tref = null;
}
that.readyState = SockJS.OPEN;
that.dispatchEvent(new SimpleEvent("open"));
} else {
// The server might have been restarted, and lost track of our
// connection.
that._didClose(1006, "Server lost session");
}
};
SockJS.prototype._dispatchMessage = function(data) {
var that = this;
if (that.readyState !== SockJS.OPEN)
return;
that.dispatchEvent(new SimpleEvent("message", {data: data}));
};
SockJS.prototype._dispatchHeartbeat = function(data) {
var that = this;
if (that.readyState !== SockJS.OPEN)
return;
that.dispatchEvent(new SimpleEvent('heartbeat', {}));
};
SockJS.prototype._didClose = function(code, reason, force) {
var that = this;
if (that.readyState !== SockJS.CONNECTING &&
that.readyState !== SockJS.OPEN &&
that.readyState !== SockJS.CLOSING)
throw new Error('INVALID_STATE_ERR');
if (that._ir) {
that._ir.nuke();
that._ir = null;
}
if (that._transport) {
that._transport.doCleanup();
that._transport = null;
}
var close_event = new SimpleEvent("close", {
code: code,
reason: reason,
wasClean: utils.userSetCode(code)});
if (!utils.userSetCode(code) &&
that.readyState === SockJS.CONNECTING && !force) {
if (that._try_next_protocol(close_event)) {
return;
}
close_event = new SimpleEvent("close", {code: 2000,
reason: "All transports failed",
wasClean: false,
last_event: close_event});
}
that.readyState = SockJS.CLOSED;
utils.delay(function() {
that.dispatchEvent(close_event);
});
};
SockJS.prototype._didMessage = function(data) {
var that = this;
var type = data.slice(0, 1);
switch(type) {
case 'o':
that._dispatchOpen();
break;
case 'a':
var payload = JSON.parse(data.slice(1) || '[]');
for(var i=0; i < payload.length; i++){
that._dispatchMessage(payload[i]);
}
break;
case 'm':
var payload = JSON.parse(data.slice(1) || 'null');
that._dispatchMessage(payload);
break;
case 'c':
var payload = JSON.parse(data.slice(1) || '[]');
that._didClose(payload[0], payload[1]);
break;
case 'h':
that._dispatchHeartbeat();
break;
}
};
SockJS.prototype._try_next_protocol = function(close_event) {
var that = this;
if (that.protocol) {
that._debug('Closed transport:', that.protocol, ''+close_event);
that.protocol = null;
}
if (that._transport_tref) {
clearTimeout(that._transport_tref);
that._transport_tref = null;
}
while(1) {
var protocol = that.protocol = that._protocols.shift();
if (!protocol) {
return false;
}
// Some protocols require access to `body`, what if were in
// the `head`?
if (SockJS[protocol] &&
SockJS[protocol].need_body === true &&
(!_document.body ||
(typeof _document.readyState !== 'undefined'
&& _document.readyState !== 'complete'))) {
that._protocols.unshift(protocol);
that.protocol = 'waiting-for-load';
utils.attachEvent('load', function(){
that._try_next_protocol();
});
return true;
}
if (!SockJS[protocol] ||
!SockJS[protocol].enabled(that._options)) {
that._debug('Skipping transport:', protocol);
} else {
var roundTrips = SockJS[protocol].roundTrips || 1;
var to = ((that._options.rto || 0) * roundTrips) || 5000;
that._transport_tref = utils.delay(to, function() {
if (that.readyState === SockJS.CONNECTING) {
// I can't understand how it is possible to run
// this timer, when the state is CLOSED, but
// apparently in IE everythin is possible.
that._didClose(2007, "Transport timeouted");
}
});
var connid = utils.random_string(8);
var trans_url = that._base_url + '/' + that._server + '/' + connid;
that._debug('Opening transport:', protocol, ' url:'+trans_url,
' RTO:'+that._options.rto);
that._transport = new SockJS[protocol](that, trans_url,
that._base_url);
return true;
}
}
};
SockJS.prototype.close = function(code, reason) {
var that = this;
if (code && !utils.userSetCode(code))
throw new Error("INVALID_ACCESS_ERR");
if(that.readyState !== SockJS.CONNECTING &&
that.readyState !== SockJS.OPEN) {
return false;
}
that.readyState = SockJS.CLOSING;
that._didClose(code || 1000, reason || "Normal closure");
return true;
};
SockJS.prototype.send = function(data) {
var that = this;
if (that.readyState === SockJS.CONNECTING)
throw new Error('INVALID_STATE_ERR');
if (that.readyState === SockJS.OPEN) {
that._transport.doSend(utils.quote('' + data));
}
return true;
};
SockJS.prototype._applyInfo = function(info, rtt, protocols_whitelist) {
var that = this;
that._options.info = info;
that._options.rtt = rtt;
that._options.rto = utils.countRTO(rtt);
that._options.info.null_origin = !_document.domain;
var probed = utils.probeProtocols();
that._protocols = utils.detectProtocols(probed, protocols_whitelist, info);
};
// [*] End of lib/sockjs.js
// [*] Including lib/trans-websocket.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var WebSocketTransport = SockJS.websocket = function(ri, trans_url) {
var that = this;
var url = trans_url + '/websocket';
if (url.slice(0, 5) === 'https') {
url = 'wss' + url.slice(5);
} else {
url = 'ws' + url.slice(4);
}
that.ri = ri;
that.url = url;
var Constructor = _window.WebSocket || _window.MozWebSocket;
that.ws = new Constructor(that.url);
that.ws.onmessage = function(e) {
that.ri._didMessage(e.data);
};
// Firefox has an interesting bug. If a websocket connection is
// created after onunload, it stays alive even when user
// navigates away from the page. In such situation let's lie -
// let's not open the ws connection at all. See:
// https://github.com/sockjs/sockjs-client/issues/28
// https://bugzilla.mozilla.org/show_bug.cgi?id=696085
that.unload_ref = utils.unload_add(function(){that.ws.close()});
that.ws.onclose = function() {
that.ri._didMessage(utils.closeFrame(1006, "WebSocket connection broken"));
};
};
WebSocketTransport.prototype.doSend = function(data) {
this.ws.send('[' + data + ']');
};
WebSocketTransport.prototype.doCleanup = function() {
var that = this;
var ws = that.ws;
if (ws) {
ws.onmessage = ws.onclose = null;
ws.close();
utils.unload_del(that.unload_ref);
that.unload_ref = that.ri = that.ws = null;
}
};
WebSocketTransport.enabled = function() {
return !!(_window.WebSocket || _window.MozWebSocket);
};
// In theory, ws should require 1 round trip. But in chrome, this is
// not very stable over SSL. Most likely a ws connection requires a
// separate SSL connection, in which case 2 round trips are an
// absolute minumum.
WebSocketTransport.roundTrips = 2;
// [*] End of lib/trans-websocket.js
// [*] Including lib/trans-sender.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var BufferedSender = function() {};
BufferedSender.prototype.send_constructor = function(sender) {
var that = this;
that.send_buffer = [];
that.sender = sender;
};
BufferedSender.prototype.doSend = function(message) {
var that = this;
that.send_buffer.push(message);
if (!that.send_stop) {
that.send_schedule();
}
};
// For polling transports in a situation when in the message callback,
// new message is being send. If the sending connection was started
// before receiving one, it is possible to saturate the network and
// timeout due to the lack of receiving socket. To avoid that we delay
// sending messages by some small time, in order to let receiving
// connection be started beforehand. This is only a halfmeasure and
// does not fix the big problem, but it does make the tests go more
// stable on slow networks.
BufferedSender.prototype.send_schedule_wait = function() {
var that = this;
var tref;
that.send_stop = function() {
that.send_stop = null;
clearTimeout(tref);
};
tref = utils.delay(25, function() {
that.send_stop = null;
that.send_schedule();
});
};
BufferedSender.prototype.send_schedule = function() {
var that = this;
if (that.send_buffer.length > 0) {
var payload = '[' + that.send_buffer.join(',') + ']';
that.send_stop = that.sender(that.trans_url, payload, function(success, abort_reason) {
that.send_stop = null;
if (success === false) {
that.ri._didClose(1006, 'Sending error ' + abort_reason);
} else {
that.send_schedule_wait();
}
});
that.send_buffer = [];
}
};
BufferedSender.prototype.send_destructor = function() {
var that = this;
if (that._send_stop) {
that._send_stop();
}
that._send_stop = null;
};
var jsonPGenericSender = function(url, payload, callback) {
var that = this;
if (!('_send_form' in that)) {
var form = that._send_form = _document.createElement('form');
var area = that._send_area = _document.createElement('textarea');
area.name = 'd';
form.style.display = 'none';
form.style.position = 'absolute';
form.method = 'POST';
form.enctype = 'application/x-www-form-urlencoded';
form.acceptCharset = "UTF-8";
form.appendChild(area);
_document.body.appendChild(form);
}
var form = that._send_form;
var area = that._send_area;
var id = 'a' + utils.random_string(8);
form.target = id;
form.action = url + '/jsonp_send?i=' + id;
var iframe;
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
iframe = _document.createElement('<iframe name="'+ id +'">');
} catch(x) {
iframe = _document.createElement('iframe');
iframe.name = id;
}
iframe.id = id;
form.appendChild(iframe);
iframe.style.display = 'none';
try {
area.value = payload;
} catch(e) {
utils.log('Your browser is seriously broken. Go home! ' + e.message);
}
form.submit();
var completed = function(e) {
if (!iframe.onerror) return;
iframe.onreadystatechange = iframe.onerror = iframe.onload = null;
// Opera mini doesn't like if we GC iframe
// immediately, thus this timeout.
utils.delay(500, function() {
iframe.parentNode.removeChild(iframe);
iframe = null;
});
area.value = '';
// It is not possible to detect if the iframe succeeded or
// failed to submit our form.
callback(true);
};
iframe.onerror = iframe.onload = completed;
iframe.onreadystatechange = function(e) {
if (iframe.readyState == 'complete') completed();
};
return completed;
};
var createAjaxSender = function(AjaxObject) {
return function(url, payload, callback) {
var xo = new AjaxObject('POST', url + '/xhr_send', payload);
xo.onfinish = function(status, text) {
callback(status === 200 || status === 204,
'http status ' + status);
};
return function(abort_reason) {
callback(false, abort_reason);
};
};
};
// [*] End of lib/trans-sender.js
// [*] Including lib/trans-jsonp-receiver.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// Parts derived from Socket.io:
// https://github.com/LearnBoost/socket.io/blob/0.6.17/lib/socket.io/transports/jsonp-polling.js
// and jQuery-JSONP:
// https://code.google.com/p/jquery-jsonp/source/browse/trunk/core/jquery.jsonp.js
var jsonPGenericReceiver = function(url, callback) {
var tref;
var script = _document.createElement('script');
var script2; // Opera synchronous load trick.
var close_script = function(frame) {
if (script2) {
script2.parentNode.removeChild(script2);
script2 = null;
}
if (script) {
clearTimeout(tref);
// Unfortunately, you can't really abort script loading of
// the script.
script.parentNode.removeChild(script);
script.onreadystatechange = script.onerror =
script.onload = script.onclick = null;
script = null;
callback(frame);
callback = null;
}
};
// IE9 fires 'error' event after orsc or before, in random order.
var loaded_okay = false;
var error_timer = null;
script.id = 'a' + utils.random_string(8);
script.src = url;
script.type = 'text/javascript';
script.charset = 'UTF-8';
script.onerror = function(e) {
if (!error_timer) {
// Delay firing close_script.
error_timer = setTimeout(function() {
if (!loaded_okay) {
close_script(utils.closeFrame(
1006,
"JSONP script loaded abnormally (onerror)"));
}
}, 1000);
}
};
script.onload = function(e) {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onload)"));
};
script.onreadystatechange = function(e) {
if (/loaded|closed/.test(script.readyState)) {
if (script && script.htmlFor && script.onclick) {
loaded_okay = true;
try {
// In IE, actually execute the script.
script.onclick();
} catch (x) {}
}
if (script) {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onreadystatechange)"));
}
}
};
// IE: event/htmlFor/onclick trick.
// One can't rely on proper order for onreadystatechange. In order to
// make sure, set a 'htmlFor' and 'event' properties, so that
// script code will be installed as 'onclick' handler for the
// script object. Later, onreadystatechange, manually execute this
// code. FF and Chrome doesn't work with 'event' and 'htmlFor'
// set. For reference see:
// http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
// Also, read on that about script ordering:
// http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
if (typeof script.async === 'undefined' && _document.attachEvent) {
// According to mozilla docs, in recent browsers script.async defaults
// to 'true', so we may use it to detect a good browser:
// https://developer.mozilla.org/en/HTML/Element/script
if (!/opera/i.test(navigator.userAgent)) {
// Naively assume we're in IE
try {
script.htmlFor = script.id;
script.event = "onclick";
} catch (x) {}
script.async = true;
} else {
// Opera, second sync script hack
script2 = _document.createElement('script');
script2.text = "try{var a = document.getElementById('"+script.id+"'); if(a)a.onerror();}catch(x){};";
script.async = script2.async = false;
}
}
if (typeof script.async !== 'undefined') {
script.async = true;
}
// Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty.
tref = setTimeout(function() {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (timeout)"));
}, 35000);
var head = _document.getElementsByTagName('head')[0];
head.insertBefore(script, head.firstChild);
if (script2) {
head.insertBefore(script2, head.firstChild);
}
return close_script;
};
// [*] End of lib/trans-jsonp-receiver.js
// [*] Including lib/trans-jsonp-polling.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// The simplest and most robust transport, using the well-know cross
// domain hack - JSONP. This transport is quite inefficient - one
// mssage could use up to one http request. But at least it works almost
// everywhere.
// Known limitations:
// o you will get a spinning cursor
// o for Konqueror a dumb timer is needed to detect errors
var JsonPTransport = SockJS['jsonp-polling'] = function(ri, trans_url) {
utils.polluteGlobalNamespace();
var that = this;
that.ri = ri;
that.trans_url = trans_url;
that.send_constructor(jsonPGenericSender);
that._schedule_recv();
};
// Inheritnace
JsonPTransport.prototype = new BufferedSender();
JsonPTransport.prototype._schedule_recv = function() {
var that = this;
var callback = function(data) {
that._recv_stop = null;
if (data) {
// no data - heartbeat;
if (!that._is_closing) {
that.ri._didMessage(data);
}
}
// The message can be a close message, and change is_closing state.
if (!that._is_closing) {
that._schedule_recv();
}
};
that._recv_stop = jsonPReceiverWrapper(that.trans_url + '/jsonp',
jsonPGenericReceiver, callback);
};
JsonPTransport.enabled = function() {
return true;
};
JsonPTransport.need_body = true;
JsonPTransport.prototype.doCleanup = function() {
var that = this;
that._is_closing = true;
if (that._recv_stop) {
that._recv_stop();
}
that.ri = that._recv_stop = null;
that.send_destructor();
};
// Abstract away code that handles global namespace pollution.
var jsonPReceiverWrapper = function(url, constructReceiver, user_callback) {
var id = 'a' + utils.random_string(6);
var url_id = url + '?c=' + escape(WPrefix + '.' + id);
// Unfortunately it is not possible to abort loading of the
// script. We need to keep track of frake close frames.
var aborting = 0;
// Callback will be called exactly once.
var callback = function(frame) {
switch(aborting) {
case 0:
// Normal behaviour - delete hook _and_ emit message.
delete _window[WPrefix][id];
user_callback(frame);
break;
case 1:
// Fake close frame - emit but don't delete hook.
user_callback(frame);
aborting = 2;
break;
case 2:
// Got frame after connection was closed, delete hook, don't emit.
delete _window[WPrefix][id];
break;
}
};
var close_script = constructReceiver(url_id, callback);
_window[WPrefix][id] = close_script;
var stop = function() {
if (_window[WPrefix][id]) {
aborting = 1;
_window[WPrefix][id](utils.closeFrame(1000, "JSONP user aborted read"));
}
};
return stop;
};
// [*] End of lib/trans-jsonp-polling.js
// [*] Including lib/trans-xhr.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var AjaxBasedTransport = function() {};
AjaxBasedTransport.prototype = new BufferedSender();
AjaxBasedTransport.prototype.run = function(ri, trans_url,
url_suffix, Receiver, AjaxObject) {
var that = this;
that.ri = ri;
that.trans_url = trans_url;
that.send_constructor(createAjaxSender(AjaxObject));
that.poll = new Polling(ri, Receiver,
trans_url + url_suffix, AjaxObject);
};
AjaxBasedTransport.prototype.doCleanup = function() {
var that = this;
if (that.poll) {
that.poll.abort();
that.poll = null;
}
};
// xhr-streaming
var XhrStreamingTransport = SockJS['xhr-streaming'] = function(ri, trans_url) {
this.run(ri, trans_url, '/xhr_streaming', XhrReceiver, utils.XHRCorsObject);
};
XhrStreamingTransport.prototype = new AjaxBasedTransport();
XhrStreamingTransport.enabled = function() {
// Support for CORS Ajax aka Ajax2? Opera 12 claims CORS but
// doesn't do streaming.
return (_window.XMLHttpRequest &&
'withCredentials' in new XMLHttpRequest() &&
(!/opera/i.test(navigator.userAgent)));
};
XhrStreamingTransport.roundTrips = 2; // preflight, ajax
// Safari gets confused when a streaming ajax request is started
// before onload. This causes the load indicator to spin indefinetely.
XhrStreamingTransport.need_body = true;
// According to:
// http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests
// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
// xdr-streaming
var XdrStreamingTransport = SockJS['xdr-streaming'] = function(ri, trans_url) {
this.run(ri, trans_url, '/xhr_streaming', XhrReceiver, utils.XDRObject);
};
XdrStreamingTransport.prototype = new AjaxBasedTransport();
XdrStreamingTransport.enabled = function() {
return !!_window.XDomainRequest;
};
XdrStreamingTransport.roundTrips = 2; // preflight, ajax
// xhr-polling
var XhrPollingTransport = SockJS['xhr-polling'] = function(ri, trans_url) {
this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XHRCorsObject);
};
XhrPollingTransport.prototype = new AjaxBasedTransport();
XhrPollingTransport.enabled = XhrStreamingTransport.enabled;
XhrPollingTransport.roundTrips = 2; // preflight, ajax
// xdr-polling
var XdrPollingTransport = SockJS['xdr-polling'] = function(ri, trans_url) {
this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XDRObject);
};
XdrPollingTransport.prototype = new AjaxBasedTransport();
XdrPollingTransport.enabled = XdrStreamingTransport.enabled;
XdrPollingTransport.roundTrips = 2; // preflight, ajax
// [*] End of lib/trans-xhr.js
// [*] Including lib/trans-iframe.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// Few cool transports do work only for same-origin. In order to make
// them working cross-domain we shall use iframe, served form the
// remote domain. New browsers, have capabilities to communicate with
// cross domain iframe, using postMessage(). In IE it was implemented
// from IE 8+, but of course, IE got some details wrong:
// http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx
// http://stevesouders.com/misc/test-postmessage.php
var IframeTransport = function() {};
IframeTransport.prototype.i_constructor = function(ri, trans_url, base_url) {
var that = this;
that.ri = ri;
that.origin = utils.getOrigin(base_url);
that.base_url = base_url;
that.trans_url = trans_url;
var iframe_url = base_url + '/iframe.html';
if (that.ri._options.devel) {
iframe_url += '?t=' + (+new Date);
}
that.window_id = utils.random_string(8);
iframe_url += '#' + that.window_id;
that.iframeObj = utils.createIframe(iframe_url, function(r) {
that.ri._didClose(1006, "Unable to load an iframe (" + r + ")");
});
that.onmessage_cb = utils.bind(that.onmessage, that);
utils.attachMessage(that.onmessage_cb);
};
IframeTransport.prototype.doCleanup = function() {
var that = this;
if (that.iframeObj) {
utils.detachMessage(that.onmessage_cb);
try {
// When the iframe is not loaded, IE raises an exception
// on 'contentWindow'.
if (that.iframeObj.iframe.contentWindow) {
that.postMessage('c');
}
} catch (x) {}
that.iframeObj.cleanup();
that.iframeObj = null;
that.onmessage_cb = that.iframeObj = null;
}
};
IframeTransport.prototype.onmessage = function(e) {
var that = this;
if (e.origin !== that.origin) return;
var window_id = e.data.slice(0, 8);
var type = e.data.slice(8, 9);
var data = e.data.slice(9);
if (window_id !== that.window_id) return;
switch(type) {
case 's':
that.iframeObj.loaded();
that.postMessage('s', JSON.stringify([SockJS.version, that.protocol, that.trans_url, that.base_url]));
break;
case 't':
that.ri._didMessage(data);
break;
}
};
IframeTransport.prototype.postMessage = function(type, data) {
var that = this;
that.iframeObj.post(that.window_id + type + (data || ''), that.origin);
};
IframeTransport.prototype.doSend = function (message) {
this.postMessage('m', message);
};
IframeTransport.enabled = function() {
// postMessage misbehaves in konqueror 4.6.5 - the messages are delivered with
// huge delay, or not at all.
var konqueror = navigator && navigator.userAgent && navigator.userAgent.indexOf('Konqueror') !== -1;
return ((typeof _window.postMessage === 'function' ||
typeof _window.postMessage === 'object') && (!konqueror));
};
// [*] End of lib/trans-iframe.js
// [*] Including lib/trans-iframe-within.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var curr_window_id;
var postMessage = function (type, data) {
if(parent !== _window) {
parent.postMessage(curr_window_id + type + (data || ''), '*');
} else {
utils.log("Can't postMessage, no parent window.", type, data);
}
};
var FacadeJS = function() {};
FacadeJS.prototype._didClose = function (code, reason) {
postMessage('t', utils.closeFrame(code, reason));
};
FacadeJS.prototype._didMessage = function (frame) {
postMessage('t', frame);
};
FacadeJS.prototype._doSend = function (data) {
this._transport.doSend(data);
};
FacadeJS.prototype._doCleanup = function () {
this._transport.doCleanup();
};
utils.parent_origin = undefined;
SockJS.bootstrap_iframe = function() {
var facade;
curr_window_id = _document.location.hash.slice(1);
var onMessage = function(e) {
if(e.source !== parent) return;
if(typeof utils.parent_origin === 'undefined')
utils.parent_origin = e.origin;
if (e.origin !== utils.parent_origin) return;
var window_id = e.data.slice(0, 8);
var type = e.data.slice(8, 9);
var data = e.data.slice(9);
if (window_id !== curr_window_id) return;
switch(type) {
case 's':
var p = JSON.parse(data);
var version = p[0];
var protocol = p[1];
var trans_url = p[2];
var base_url = p[3];
if (version !== SockJS.version) {
utils.log("Incompatibile SockJS! Main site uses:" +
" \"" + version + "\", the iframe:" +
" \"" + SockJS.version + "\".");
}
if (!utils.flatUrl(trans_url) || !utils.flatUrl(base_url)) {
utils.log("Only basic urls are supported in SockJS");
return;
}
if (!utils.isSameOriginUrl(trans_url) ||
!utils.isSameOriginUrl(base_url)) {
utils.log("Can't connect to different domain from within an " +
"iframe. (" + JSON.stringify([_window.location.href, trans_url, base_url]) +
")");
return;
}
facade = new FacadeJS();
facade._transport = new FacadeJS[protocol](facade, trans_url, base_url);
break;
case 'm':
facade._doSend(data);
break;
case 'c':
if (facade)
facade._doCleanup();
facade = null;
break;
}
};
// alert('test ticker');
// facade = new FacadeJS();
// facade._transport = new FacadeJS['w-iframe-xhr-polling'](facade, 'http://host.com:9999/ticker/12/basd');
utils.attachMessage(onMessage);
// Start
postMessage('s');
};
// [*] End of lib/trans-iframe-within.js
// [*] Including lib/info.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var InfoReceiver = function(base_url, AjaxObject) {
var that = this;
utils.delay(function(){that.doXhr(base_url, AjaxObject);});
};
InfoReceiver.prototype = new EventEmitter(['finish']);
InfoReceiver.prototype.doXhr = function(base_url, AjaxObject) {
var that = this;
var t0 = (new Date()).getTime();
var xo = new AjaxObject('GET', base_url + '/info');
var tref = utils.delay(8000,
function(){xo.ontimeout();});
xo.onfinish = function(status, text) {
clearTimeout(tref);
tref = null;
if (status === 200) {
var rtt = (new Date()).getTime() - t0;
var info = JSON.parse(text);
if (typeof info !== 'object') info = {};
that.emit('finish', info, rtt);
} else {
that.emit('finish');
}
};
xo.ontimeout = function() {
xo.close();
that.emit('finish');
};
};
var InfoReceiverIframe = function(base_url) {
var that = this;
var go = function() {
var ifr = new IframeTransport();
ifr.protocol = 'w-iframe-info-receiver';
var fun = function(r) {
if (typeof r === 'string' && r.substr(0,1) === 'm') {
var d = JSON.parse(r.substr(1));
var info = d[0], rtt = d[1];
that.emit('finish', info, rtt);
} else {
that.emit('finish');
}
ifr.doCleanup();
ifr = null;
};
var mock_ri = {
_options: {},
_didClose: fun,
_didMessage: fun
};
ifr.i_constructor(mock_ri, base_url, base_url);
}
if(!_document.body) {
utils.attachEvent('load', go);
} else {
go();
}
};
InfoReceiverIframe.prototype = new EventEmitter(['finish']);
var InfoReceiverFake = function() {
// It may not be possible to do cross domain AJAX to get the info
// data, for example for IE7. But we want to run JSONP, so let's
// fake the response, with rtt=2s (rto=6s).
var that = this;
utils.delay(function() {
that.emit('finish', {}, 2000);
});
};
InfoReceiverFake.prototype = new EventEmitter(['finish']);
var createInfoReceiver = function(base_url) {
if (utils.isSameOriginUrl(base_url)) {
// If, for some reason, we have SockJS locally - there's no
// need to start up the complex machinery. Just use ajax.
return new InfoReceiver(base_url, utils.XHRLocalObject);
}
switch (utils.isXHRCorsCapable()) {
case 1:
// XHRLocalObject -> no_credentials=true
return new InfoReceiver(base_url, utils.XHRLocalObject);
case 2:
return new InfoReceiver(base_url, utils.XDRObject);
case 3:
// Opera
return new InfoReceiverIframe(base_url);
default:
// IE 7
return new InfoReceiverFake();
};
};
var WInfoReceiverIframe = FacadeJS['w-iframe-info-receiver'] = function(ri, _trans_url, base_url) {
var ir = new InfoReceiver(base_url, utils.XHRLocalObject);
ir.onfinish = function(info, rtt) {
ri._didMessage('m'+JSON.stringify([info, rtt]));
ri._didClose();
}
};
WInfoReceiverIframe.prototype.doCleanup = function() {};
// [*] End of lib/info.js
// [*] Including lib/trans-iframe-eventsource.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventSourceIframeTransport = SockJS['iframe-eventsource'] = function () {
var that = this;
that.protocol = 'w-iframe-eventsource';
that.i_constructor.apply(that, arguments);
};
EventSourceIframeTransport.prototype = new IframeTransport();
EventSourceIframeTransport.enabled = function () {
return ('EventSource' in _window) && IframeTransport.enabled();
};
EventSourceIframeTransport.need_body = true;
EventSourceIframeTransport.roundTrips = 3; // html, javascript, eventsource
// w-iframe-eventsource
var EventSourceTransport = FacadeJS['w-iframe-eventsource'] = function(ri, trans_url) {
this.run(ri, trans_url, '/eventsource', EventSourceReceiver, utils.XHRLocalObject);
}
EventSourceTransport.prototype = new AjaxBasedTransport();
// [*] End of lib/trans-iframe-eventsource.js
// [*] Including lib/trans-iframe-xhr-polling.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var XhrPollingIframeTransport = SockJS['iframe-xhr-polling'] = function () {
var that = this;
that.protocol = 'w-iframe-xhr-polling';
that.i_constructor.apply(that, arguments);
};
XhrPollingIframeTransport.prototype = new IframeTransport();
XhrPollingIframeTransport.enabled = function () {
return _window.XMLHttpRequest && IframeTransport.enabled();
};
XhrPollingIframeTransport.need_body = true;
XhrPollingIframeTransport.roundTrips = 3; // html, javascript, xhr
// w-iframe-xhr-polling
var XhrPollingITransport = FacadeJS['w-iframe-xhr-polling'] = function(ri, trans_url) {
this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XHRLocalObject);
};
XhrPollingITransport.prototype = new AjaxBasedTransport();
// [*] End of lib/trans-iframe-xhr-polling.js
// [*] Including lib/trans-iframe-htmlfile.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// This transport generally works in any browser, but will cause a
// spinning cursor to appear in any browser other than IE.
// We may test this transport in all browsers - why not, but in
// production it should be only run in IE.
var HtmlFileIframeTransport = SockJS['iframe-htmlfile'] = function () {
var that = this;
that.protocol = 'w-iframe-htmlfile';
that.i_constructor.apply(that, arguments);
};
// Inheritance.
HtmlFileIframeTransport.prototype = new IframeTransport();
HtmlFileIframeTransport.enabled = function() {
return IframeTransport.enabled();
};
HtmlFileIframeTransport.need_body = true;
HtmlFileIframeTransport.roundTrips = 3; // html, javascript, htmlfile
// w-iframe-htmlfile
var HtmlFileTransport = FacadeJS['w-iframe-htmlfile'] = function(ri, trans_url) {
this.run(ri, trans_url, '/htmlfile', HtmlfileReceiver, utils.XHRLocalObject);
};
HtmlFileTransport.prototype = new AjaxBasedTransport();
// [*] End of lib/trans-iframe-htmlfile.js
// [*] Including lib/trans-polling.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var Polling = function(ri, Receiver, recv_url, AjaxObject) {
var that = this;
that.ri = ri;
that.Receiver = Receiver;
that.recv_url = recv_url;
that.AjaxObject = AjaxObject;
that._scheduleRecv();
};
Polling.prototype._scheduleRecv = function() {
var that = this;
var poll = that.poll = new that.Receiver(that.recv_url, that.AjaxObject);
var msg_counter = 0;
poll.onmessage = function(e) {
msg_counter += 1;
that.ri._didMessage(e.data);
};
poll.onclose = function(e) {
that.poll = poll = poll.onmessage = poll.onclose = null;
if (!that.poll_is_closing) {
if (e.reason === 'permanent') {
that.ri._didClose(1006, 'Polling error (' + e.reason + ')');
} else {
that._scheduleRecv();
}
}
};
};
Polling.prototype.abort = function() {
var that = this;
that.poll_is_closing = true;
if (that.poll) {
that.poll.abort();
}
};
// [*] End of lib/trans-polling.js
// [*] Including lib/trans-receiver-eventsource.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventSourceReceiver = function(url) {
var that = this;
var es = new EventSource(url);
es.onmessage = function(e) {
that.dispatchEvent(new SimpleEvent('message',
{'data': unescape(e.data)}));
};
that.es_close = es.onerror = function(e, abort_reason) {
// ES on reconnection has readyState = 0 or 1.
// on network error it's CLOSED = 2
var reason = abort_reason ? 'user' :
(es.readyState !== 2 ? 'network' : 'permanent');
that.es_close = es.onmessage = es.onerror = null;
// EventSource reconnects automatically.
es.close();
es = null;
// Safari and chrome < 15 crash if we close window before
// waiting for ES cleanup. See:
// https://code.google.com/p/chromium/issues/detail?id=89155
utils.delay(200, function() {
that.dispatchEvent(new SimpleEvent('close', {reason: reason}));
});
};
};
EventSourceReceiver.prototype = new REventTarget();
EventSourceReceiver.prototype.abort = function() {
var that = this;
if (that.es_close) {
that.es_close({}, true);
}
};
// [*] End of lib/trans-receiver-eventsource.js
// [*] Including lib/trans-receiver-htmlfile.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var _is_ie_htmlfile_capable;
var isIeHtmlfileCapable = function() {
if (_is_ie_htmlfile_capable === undefined) {
if ('ActiveXObject' in _window) {
try {
_is_ie_htmlfile_capable = !!new ActiveXObject('htmlfile');
} catch (x) {}
} else {
_is_ie_htmlfile_capable = false;
}
}
return _is_ie_htmlfile_capable;
};
var HtmlfileReceiver = function(url) {
var that = this;
utils.polluteGlobalNamespace();
that.id = 'a' + utils.random_string(6, 26);
url += ((url.indexOf('?') === -1) ? '?' : '&') +
'c=' + escape(WPrefix + '.' + that.id);
var constructor = isIeHtmlfileCapable() ?
utils.createHtmlfile : utils.createIframe;
var iframeObj;
_window[WPrefix][that.id] = {
start: function () {
iframeObj.loaded();
},
message: function (data) {
that.dispatchEvent(new SimpleEvent('message', {'data': data}));
},
stop: function () {
that.iframe_close({}, 'network');
}
};
that.iframe_close = function(e, abort_reason) {
iframeObj.cleanup();
that.iframe_close = iframeObj = null;
delete _window[WPrefix][that.id];
that.dispatchEvent(new SimpleEvent('close', {reason: abort_reason}));
};
iframeObj = constructor(url, function(e) {
that.iframe_close({}, 'permanent');
});
};
HtmlfileReceiver.prototype = new REventTarget();
HtmlfileReceiver.prototype.abort = function() {
var that = this;
if (that.iframe_close) {
that.iframe_close({}, 'user');
}
};
// [*] End of lib/trans-receiver-htmlfile.js
// [*] Including lib/trans-receiver-xhr.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var XhrReceiver = function(url, AjaxObject) {
var that = this;
var buf_pos = 0;
that.xo = new AjaxObject('POST', url, null);
that.xo.onchunk = function(status, text) {
if (status !== 200) return;
while (1) {
var buf = text.slice(buf_pos);
var p = buf.indexOf('\n');
if (p === -1) break;
buf_pos += p+1;
var msg = buf.slice(0, p);
that.dispatchEvent(new SimpleEvent('message', {data: msg}));
}
};
that.xo.onfinish = function(status, text) {
that.xo.onchunk(status, text);
that.xo = null;
var reason = status === 200 ? 'network' : 'permanent';
that.dispatchEvent(new SimpleEvent('close', {reason: reason}));
}
};
XhrReceiver.prototype = new REventTarget();
XhrReceiver.prototype.abort = function() {
var that = this;
if (that.xo) {
that.xo.close();
that.dispatchEvent(new SimpleEvent('close', {reason: 'user'}));
that.xo = null;
}
};
// [*] End of lib/trans-receiver-xhr.js
// [*] Including lib/test-hooks.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// For testing
SockJS.getUtils = function(){
return utils;
};
SockJS.getIframeTransport = function(){
return IframeTransport;
};
// [*] End of lib/test-hooks.js
return SockJS;
})();
if ('_sockjs_onload' in window) setTimeout(_sockjs_onload, 1);
// AMD compliance
if (typeof define === 'function' && define.amd) {
define('sockjs', [], function(){return SockJS;});
}
// [*] End of lib/index.js
// [*] End of lib/all.js
; browserify_shim__define__module__export__(typeof SockJS != "undefined" ? SockJS : window.SockJS);
}).call(global, undefined, undefined, undefined, function defineExport(ex) { module.exports = ex; });
},{}],"sockjs":[function(require,module,exports){
module.exports=require('+z1VBF');
},{}],7:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
throw TypeError('Uncaught, unspecified "error" event.');
}
return false;
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],8:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],9:[function(require,module,exports){
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"PcZj9L":[function(require,module,exports){
var TA = require('typedarray')
var xDataView = typeof DataView === 'undefined'
? TA.DataView : DataView
var xArrayBuffer = typeof ArrayBuffer === 'undefined'
? TA.ArrayBuffer : ArrayBuffer
var xUint8Array = typeof Uint8Array === 'undefined'
? TA.Uint8Array : Uint8Array
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192
var browserSupport
/**
* 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.
*
* Firefox is a special case because it doesn't allow augmenting "native" object
* instances. See `ProxyBuffer` below for more details.
*/
function Buffer (subject, encoding) {
var type = typeof subject
// Work-around: 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 + '='
}
}
// 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 = augment(new xUint8Array(length))
if (Buffer.isBuffer(subject)) {
// 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 (var 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)
}
return buf
}
// STATIC METHODS
// ==============
Buffer.isEncoding = function(encoding) {
switch ((encoding + '').toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
case 'raw':
return true
default:
return false
}
}
Buffer.isBuffer = function isBuffer (b) {
return b && b._isBuffer
}
Buffer.byteLength = function (str, encoding) {
switch (encoding || 'utf8') {
case 'hex':
return str.length / 2
case 'utf8':
case 'utf-8':
return utf8ToBytes(str).length
case 'ascii':
case 'binary':
return str.length
case 'base64':
return base64ToBytes(str).length
default:
throw new Error('Unknown encoding')
}
}
Buffer.concat = function (list, totalLength) {
if (!Array.isArray(list)) {
throw new Error('Usage: Buffer.concat(list, [totalLength])\n' +
'list should be an Array.')
}
var i
var buf
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
if (typeof totalLength !== 'number') {
totalLength = 0
for (i = 0; i < list.length; i++) {
buf = list[i]
totalLength += buf.length
}
}
var buffer = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
buf = list[i]
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
// INSTANCE METHODS
// ================
function _hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) {
throw new Error('Invalid hex string')
}
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(byte)) throw new Error('Invalid hex string')
buf[offset + i] = byte
}
Buffer._charsWritten = i * 2
return i
}
function _utf8Write (buf, string, offset, length) {
var bytes, pos
return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
}
function _asciiWrite (buf, string, offset, length) {
var bytes, pos
return Buffer._charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
}
function _binaryWrite (buf, string, offset, length) {
return _asciiWrite(buf, string, offset, length)
}
function _base64Write (buf, string, offset, length) {
var bytes, pos
return Buffer._charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
}
function BufferWrite (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
switch (encoding) {
case 'hex':
return _hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return _utf8Write(this, string, offset, length)
case 'ascii':
return _asciiWrite(this, string, offset, length)
case 'binary':
return _binaryWrite(this, string, offset, length)
case 'base64':
return _base64Write(this, string, offset, length)
default:
throw new Error('Unknown encoding')
}
}
function BufferToString (encoding, start, end) {
var self = (this instanceof ProxyBuffer)
? this._proxy
: 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':
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 BufferToJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this, 0)
}
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
function BufferCopy (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
if (end < start)
throw new Error('sourceEnd < sourceStart')
if (target_start < 0 || target_start >= target.length)
throw new Error('targetStart out of bounds')
if (start < 0 || start >= source.length)
throw new Error('sourceStart out of bounds')
if (end < 0 || end > source.length)
throw new Error('sourceEnd out of bounds')
// Are we oob?
if (end > this.length)
end = this.length
if (target.length - target_start < end - start)
end = target.length - target_start + start
// copy!
for (var i = 0; i < end - start; i++)
target[i + target_start] = this[i + start]
}
function _base64Slice (buf, start, end) {
var bytes = buf.slice(start, end)
return require('base64-js').fromByteArray(bytes)
}
function _utf8Slice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
var tmp = ''
var i = 0
while (i < bytes.length) {
if (bytes[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i])
tmp = ''
} else {
tmp += '%' + bytes[i].toString(16)
}
i++
}
return res + decodeUtf8Char(tmp)
}
function _asciiSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var ret = ''
for (var i = 0; i < bytes.length; i++)
ret += String.fromCharCode(bytes[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
}
// TODO: add test that modifying the new buffer slice will modify memory in the
// original buffer! Use code from:
// http://nodejs.org/api/buffer.html#buffer_buf_slice_start_end
function BufferSlice (start, end) {
var len = this.length
start = clamp(start, len, 0)
end = clamp(end, len, len)
return augment(this.subarray(start, end)) // Uint8Array built-in method
}
function BufferReadUInt8 (offset, noAssert) {
var buf = this
if (!noAssert) {
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < buf.length, 'Trying to read beyond buffer length')
}
if (offset >= buf.length)
return
return buf[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
} else if (offset + 1 === len) {
var dv = new xDataView(new xArrayBuffer(2))
dv.setUint8(0, buf[len - 1])
return dv.getUint16(0, littleEndian)
} else {
return buf._dataview.getUint16(offset, littleEndian)
}
}
function BufferReadUInt16LE (offset, noAssert) {
return _readUInt16(this, offset, true, noAssert)
}
function BufferReadUInt16BE (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
} else if (offset + 3 >= len) {
var dv = new xDataView(new xArrayBuffer(4))
for (var i = 0; i + offset < len; i++) {
dv.setUint8(i, buf[i + offset])
}
return dv.getUint32(0, littleEndian)
} else {
return buf._dataview.getUint32(offset, littleEndian)
}
}
function BufferReadUInt32LE (offset, noAssert) {
return _readUInt32(this, offset, true, noAssert)
}
function BufferReadUInt32BE (offset, noAssert) {
return _readUInt32(this, offset, false, noAssert)
}
function BufferReadInt8 (offset, noAssert) {
var buf = this
if (!noAssert) {
assert(offset !== undefined && offset !== null,
'missing offset')
assert(offset < buf.length, 'Trying to read beyond buffer length')
}
if (offset >= buf.length)
return
return buf._dataview.getInt8(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
} else if (offset + 1 === len) {
var dv = new xDataView(new xArrayBuffer(2))
dv.setUint8(0, buf[len - 1])
return dv.getInt16(0, littleEndian)
} else {
return buf._dataview.getInt16(offset, littleEndian)
}
}
function BufferReadInt16LE (offset, noAssert) {
return _readInt16(this, offset, true, noAssert)
}
function BufferReadInt16BE (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
} else if (offset + 3 >= len) {
var dv = new xDataView(new xArrayBuffer(4))
for (var i = 0; i + offset < len; i++) {
dv.setUint8(i, buf[i + offset])
}
return dv.getInt32(0, littleEndian)
} else {
return buf._dataview.getInt32(offset, littleEndian)
}
}
function BufferReadInt32LE (offset, noAssert) {
return _readInt32(this, offset, true, noAssert)
}
function BufferReadInt32BE (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 buf._dataview.getFloat32(offset, littleEndian)
}
function BufferReadFloatLE (offset, noAssert) {
return _readFloat(this, offset, true, noAssert)
}
function BufferReadFloatBE (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 buf._dataview.getFloat64(offset, littleEndian)
}
function BufferReadDoubleLE (offset, noAssert) {
return _readDouble(this, offset, true, noAssert)
}
function BufferReadDoubleBE (offset, noAssert) {
return _readDouble(this, offset, false, noAssert)
}
function BufferWriteUInt8 (value, offset, noAssert) {
var buf = this
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < buf.length, 'trying to write beyond buffer length')
verifuint(value, 0xff)
}
if (offset >= buf.length) return
buf[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
} else if (offset + 1 === len) {
var dv = new xDataView(new xArrayBuffer(2))
dv.setUint16(0, value, littleEndian)
buf[offset] = dv.getUint8(0)
} else {
buf._dataview.setUint16(offset, value, littleEndian)
}
}
function BufferWriteUInt16LE (value, offset, noAssert) {
_writeUInt16(this, value, offset, true, noAssert)
}
function BufferWriteUInt16BE (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
} else if (offset + 3 >= len) {
var dv = new xDataView(new xArrayBuffer(4))
dv.setUint32(0, value, littleEndian)
for (var i = 0; i + offset < len; i++) {
buf[i + offset] = dv.getUint8(i)
}
} else {
buf._dataview.setUint32(offset, value, littleEndian)
}
}
function BufferWriteUInt32LE (value, offset, noAssert) {
_writeUInt32(this, value, offset, true, noAssert)
}
function BufferWriteUInt32BE (value, offset, noAssert) {
_writeUInt32(this, value, offset, false, noAssert)
}
function BufferWriteInt8 (value, offset, noAssert) {
var buf = this
if (!noAssert) {
assert(value !== undefined && value !== null, 'missing value')
assert(offset !== undefined && offset !== null, 'missing offset')
assert(offset < buf.length, 'Trying to write beyond buffer length')
verifsint(value, 0x7f, -0x80)
}
if (offset >= buf.length) return
buf._dataview.setInt8(offset, value)
}
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
} else if (offset + 1 === len) {
var dv = new xDataView(new xArrayBuffer(2))
dv.setInt16(0, value, littleEndian)
buf[offset] = dv.getUint8(0)
} else {
buf._dataview.setInt16(offset, value, littleEndian)
}
}
function BufferWriteInt16LE (value, offset, noAssert) {
_writeInt16(this, value, offset, true, noAssert)
}
function BufferWriteInt16BE (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
} else if (offset + 3 >= len) {
var dv = new xDataView(new xArrayBuffer(4))
dv.setInt32(0, value, littleEndian)
for (var i = 0; i + offset < len; i++) {
buf[i + offset] = dv.getUint8(i)
}
} else {
buf._dataview.setInt32(offset, value, littleEndian)
}
}
function BufferWriteInt32LE (value, offset, noAssert) {
_writeInt32(this, value, offset, true, noAssert)
}
function BufferWriteInt32BE (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
} else if (offset + 3 >= len) {
var dv = new xDataView(new xArrayBuffer(4))
dv.setFloat32(0, value, littleEndian)
for (var i = 0; i + offset < len; i++) {
buf[i + offset] = dv.getUint8(i)
}
} else {
buf._dataview.setFloat32(offset, value, littleEndian)
}
}
function BufferWriteFloatLE (value, offset, noAssert) {
_writeFloat(this, value, offset, true, noAssert)
}
function BufferWriteFloatBE (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
} else if (offset + 7 >= len) {
var dv = new xDataView(new xArrayBuffer(8))
dv.setFloat64(0, value, littleEndian)
for (var i = 0; i + offset < len; i++) {
buf[i + offset] = dv.getUint8(i)
}
} else {
buf._dataview.setFloat64(offset, value, littleEndian)
}
}
function BufferWriteDoubleLE (value, offset, noAssert) {
_writeDouble(this, value, offset, true, noAssert)
}
function BufferWriteDoubleBE (value, offset, noAssert) {
_writeDouble(this, value, offset, false, noAssert)
}
// fill(value, start=0, end=buffer.length)
function BufferFill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (typeof value === 'string') {
value = value.charCodeAt(0)
}
if (typeof value !== 'number' || isNaN(value)) {
throw new Error('value is not a number')
}
if (end < start) throw new Error('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) {
throw new Error('start out of bounds')
}
if (end < 0 || end > this.length) {
throw new Error('end out of bounds')
}
for (var i = start; i < end; i++) {
this[i] = value
}
}
function BufferInspect () {
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 '<Buffer ' + out.join(' ') + '>'
}
// Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
// Added in Node 0.12.
function BufferToArrayBuffer () {
return (new Buffer(this)).buffer
}
// HELPER FUNCTIONS
// ================
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
/**
* Check to see if the browser supports augmenting a `Uint8Array` instance.
* @return {boolean}
*/
function _browserSupport () {
var arr = new xUint8Array(0)
arr.foo = function () { return 42 }
try {
return (42 === arr.foo())
} catch (e) {
return false
}
}
/**
* Class: ProxyBuffer
* ==================
*
* Only used in Firefox, since Firefox does not allow augmenting "native"
* objects (like Uint8Array instances) with new properties for some unknown
* (probably silly) reason. So we'll use an ES6 Proxy (supported since
* Firefox 18) to wrap the Uint8Array instance without actually adding any
* properties to it.
*
* Instances of this "fake" Buffer class are the "target" of the
* ES6 Proxy (see `augment` function).
*
* We couldn't just use the `Uint8Array` as the target of the `Proxy` because
* Proxies have an important limitation on trapping the `toString` method.
* `Object.prototype.toString.call(proxy)` gets called whenever something is
* implicitly cast to a String. Unfortunately, with a `Proxy` this
* unconditionally returns `Object.prototype.toString.call(target)` which would
* always return "[object Uint8Array]" if we used the `Uint8Array` instance as
* the target. And, remember, in Firefox we cannot redefine the `Uint8Array`
* instance's `toString` method.
*
* So, we use this `ProxyBuffer` class as the proxy's "target". Since this class
* has its own custom `toString` method, it will get called whenever `toString`
* gets called, implicitly or explicitly, on the `Proxy` instance.
*
* We also have to define the Uint8Array methods `subarray` and `set` on
* `ProxyBuffer` because if we didn't then `proxy.subarray(0)` would have its
* `this` set to `proxy` (a `Proxy` instance) which throws an exception in
* Firefox which expects it to be a `TypedArray` instance.
*/
function ProxyBuffer (arr) {
this._arr = arr
if (arr.byteLength !== 0)
this._dataview = new xDataView(arr.buffer, arr.byteOffset, arr.byteLength)
}
ProxyBuffer.prototype.write = BufferWrite
ProxyBuffer.prototype.toString = BufferToString
ProxyBuffer.prototype.toLocaleString = BufferToString
ProxyBuffer.prototype.toJSON = BufferToJSON
ProxyBuffer.prototype.copy = BufferCopy
ProxyBuffer.prototype.slice = BufferSlice
ProxyBuffer.prototype.readUInt8 = BufferReadUInt8
ProxyBuffer.prototype.readUInt16LE = BufferReadUInt16LE
ProxyBuffer.prototype.readUInt16BE = BufferReadUInt16BE
ProxyBuffer.prototype.readUInt32LE = BufferReadUInt32LE
ProxyBuffer.prototype.readUInt32BE = BufferReadUInt32BE
ProxyBuffer.prototype.readInt8 = BufferReadInt8
ProxyBuffer.prototype.readInt16LE = BufferReadInt16LE
ProxyBuffer.prototype.readInt16BE = BufferReadInt16BE
ProxyBuffer.prototype.readInt32LE = BufferReadInt32LE
ProxyBuffer.prototype.readInt32BE = BufferReadInt32BE
ProxyBuffer.prototype.readFloatLE = BufferReadFloatLE
ProxyBuffer.prototype.readFloatBE = BufferReadFloatBE
ProxyBuffer.prototype.readDoubleLE = BufferReadDoubleLE
ProxyBuffer.prototype.readDoubleBE = BufferReadDoubleBE
ProxyBuffer.prototype.writeUInt8 = BufferWriteUInt8
ProxyBuffer.prototype.writeUInt16LE = BufferWriteUInt16LE
ProxyBuffer.prototype.writeUInt16BE = BufferWriteUInt16BE
ProxyBuffer.prototype.writeUInt32LE = BufferWriteUInt32LE
ProxyBuffer.prototype.writeUInt32BE = BufferWriteUInt32BE
ProxyBuffer.prototype.writeInt8 = BufferWriteInt8
ProxyBuffer.prototype.writeInt16LE = BufferWriteInt16LE
ProxyBuffer.prototype.writeInt16BE = BufferWriteInt16BE
ProxyBuffer.prototype.writeInt32LE = BufferWriteInt32LE
ProxyBuffer.prototype.writeInt32BE = BufferWriteInt32BE
ProxyBuffer.prototype.writeFloatLE = BufferWriteFloatLE
ProxyBuffer.prototype.writeFloatBE = BufferWriteFloatBE
ProxyBuffer.prototype.writeDoubleLE = BufferWriteDoubleLE
ProxyBuffer.prototype.writeDoubleBE = BufferWriteDoubleBE
ProxyBuffer.prototype.fill = BufferFill
ProxyBuffer.prototype.inspect = BufferInspect
ProxyBuffer.prototype.toArrayBuffer = BufferToArrayBuffer
ProxyBuffer.prototype._isBuffer = true
ProxyBuffer.prototype.subarray = function () {
return this._arr.subarray.apply(this._arr, arguments)
}
ProxyBuffer.prototype.set = function () {
return this._arr.set.apply(this._arr, arguments)
}
var ProxyHandler = {
get: function (target, name) {
if (name in target) return target[name]
else return target._arr[name]
},
set: function (target, name, value) {
target._arr[name] = value
}
}
function augment (arr) {
if (browserSupport === undefined) {
browserSupport = _browserSupport()
}
if (browserSupport) {
// Augment the Uint8Array *instance* (not the class!) with Buffer methods
arr.write = BufferWrite
arr.toString = BufferToString
arr.toLocaleString = BufferToString
arr.toJSON = BufferToJSON
arr.copy = BufferCopy
arr.slice = BufferSlice
arr.readUInt8 = BufferReadUInt8
arr.readUInt16LE = BufferReadUInt16LE
arr.readUInt16BE = BufferReadUInt16BE
arr.readUInt32LE = BufferReadUInt32LE
arr.readUInt32BE = BufferReadUInt32BE
arr.readInt8 = BufferReadInt8
arr.readInt16LE = BufferReadInt16LE
arr.readInt16BE = BufferReadInt16BE
arr.readInt32LE = BufferReadInt32LE
arr.readInt32BE = BufferReadInt32BE
arr.readFloatLE = BufferReadFloatLE
arr.readFloatBE = BufferReadFloatBE
arr.readDoubleLE = BufferReadDoubleLE
arr.readDoubleBE = BufferReadDoubleBE
arr.writeUInt8 = BufferWriteUInt8
arr.writeUInt16LE = BufferWriteUInt16LE
arr.writeUInt16BE = BufferWriteUInt16BE
arr.writeUInt32LE = BufferWriteUInt32LE
arr.writeUInt32BE = BufferWriteUInt32BE
arr.writeInt8 = BufferWriteInt8
arr.writeInt16LE = BufferWriteInt16LE
arr.writeInt16BE = BufferWriteInt16BE
arr.writeInt32LE = BufferWriteInt32LE
arr.writeInt32BE = BufferWriteInt32BE
arr.writeFloatLE = BufferWriteFloatLE
arr.writeFloatBE = BufferWriteFloatBE
arr.writeDoubleLE = BufferWriteDoubleLE
arr.writeDoubleBE = BufferWriteDoubleBE
arr.fill = BufferFill
arr.inspect = BufferInspect
arr.toArrayBuffer = BufferToArrayBuffer
arr._isBuffer = true
if (arr.byteLength !== 0)
arr._dataview = new xDataView(arr.buffer, arr.byteOffset, arr.byteLength)
return arr
} else {
// This is a browser that doesn't support augmenting the `Uint8Array`
// instance (*ahem* Firefox) so use an ES6 `Proxy`.
var proxyBuffer = new ProxyBuffer(arr)
var proxy = new Proxy(proxyBuffer, ProxyHandler)
proxyBuffer._proxy = proxy
return proxy
}
}
// 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 isArrayIsh (subject) {
return Array.isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++)
if (str.charCodeAt(i) <= 0x7F)
byteArray.push(str.charCodeAt(i))
else {
var h = encodeURIComponent(str.charAt(i)).substr(1).split('%')
for (var j = 0; j < h.length; j++)
byteArray.push(parseInt(h[j], 16))
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function base64ToBytes (str) {
return require('base64-js').toByteArray(str)
}
function blitBuffer (src, dst, offset, length) {
var pos, i = 0
while (i < length) {
if ((i + offset >= dst.length) || (i >= src.length))
break
dst[i + offset] = src[i]
i++
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
/*
* We have to make sure that the value is a valid integer. This means that it
* is non-negative. It has no fractional component and that it does not
* exceed the maximum allowed value.
*
* value The number to check for validity
*
* max The maximum value
*/
function verifuint (value, max) {
assert(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')
}
/*
* A series of checks to make sure we actually have a signed 32-bit number
*/
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,"typedarray":4}],"native-buffer-browserify":[function(require,module,exports){
module.exports=require('PcZj9L');
},{}],3:[function(require,module,exports){
(function (exports) {
'use strict';
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function b64ToByteArray(b64) {
var i, j, l, tmp, placeHolders, arr;
if (b64.length % 4 > 0) {
throw 'Invalid string. Length must be a multiple of 4';
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
placeHolders = b64.indexOf('=');
placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;
// base64 is 4/3 + up to two characters of the original data
arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length;
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]);
arr.push((tmp & 0xFF0000) >> 16);
arr.push((tmp & 0xFF00) >> 8);
arr.push(tmp & 0xFF);
}
if (placeHolders === 2) {
tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4);
arr.push(tmp & 0xFF);
} else if (placeHolders === 1) {
tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2);
arr.push((tmp >> 8) & 0xFF);
arr.push(tmp & 0xFF);
}
return arr;
}
function uint8ToBase64(uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length;
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
};
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
output += tripletToBase64(temp);
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1];
output += lookup[temp >> 2];
output += lookup[(temp << 4) & 0x3F];
output += '==';
break;
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
output += lookup[temp >> 10];
output += lookup[(temp >> 4) & 0x3F];
output += lookup[(temp << 2) & 0x3F];
output += '=';
break;
}
return output;
}
module.exports.toByteArray = b64ToByteArray;
module.exports.fromByteArray = uint8ToBase64;
}());
},{}],4:[function(require,module,exports){
var undefined = (void 0); // Paranoia
// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
// create, and consume so much memory, that the browser appears frozen.
var MAX_ARRAY_LENGTH = 1e5;
// Approximations of internal ECMAScript conversion functions
var ECMAScript = (function() {
// Stash a copy in case other scripts modify these
var opts = Object.prototype.toString,
ophop = Object.prototype.hasOwnProperty;
return {
// Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
HasProperty: function(o, p) { return p in o; },
HasOwnProperty: function(o, p) { return ophop.call(o, p); },
IsCallable: function(o) { return typeof o === 'function'; },
ToInt32: function(v) { return v >> 0; },
ToUint32: function(v) { return v >>> 0; }
};
}());
// Snapshot intrinsics
var LN2 = Math.LN2,
abs = Math.abs,
floor = Math.floor,
log = Math.log,
min = Math.min,
pow = Math.pow,
round = Math.round;
// ES5: lock down object properties
function configureProperties(obj) {
if (getOwnPropertyNames && defineProperty) {
var props = getOwnPropertyNames(obj), i;
for (i = 0; i < props.length; i += 1) {
defineProperty(obj, props[i], {
value: obj[props[i]],
writable: false,
enumerable: false,
configurable: false
});
}
}
}
// emulate ES5 getter/setter API using legacy APIs
// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
var defineProperty = Object.defineProperty || function(o, p, desc) {
if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
return o;
};
var getOwnPropertyNames = Object.getOwnPropertyNames || function getOwnPropertyNames(o) {
if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
var props = [], p;
for (p in o) {
if (ECMAScript.HasOwnProperty(o, p)) {
props.push(p);
}
}
return props;
};
// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
// for index in 0 ... obj.length
function makeArrayAccessors(obj) {
if (!defineProperty) { return; }
if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");
function makeArrayAccessor(index) {
defineProperty(obj, index, {
'get': function() { return obj._getter(index); },
'set': function(v) { obj._setter(index, v); },
enumerable: true,
configurable: false
});
}
var i;
for (i = 0; i < obj.length; i += 1) {
makeArrayAccessor(i);
}
}
// Internal conversion functions:
// pack<Type>() - take a number (interpreted as Type), output a byte array
// unpack<Type>() - take a byte array, output a Type-like number
function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }
function packI8(n) { return [n & 0xff]; }
function unpackI8(bytes) { return as_signed(bytes[0], 8); }
function packU8(n) { return [n & 0xff]; }
function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }
function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }
function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }
function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
function packIEEE754(v, ebits, fbits) {
var bias = (1 << (ebits - 1)) - 1,
s, e, f, ln,
i, bits, str, bytes;
function roundToEven(n) {
var w = floor(n), f = n - w;
if (f < 0.5)
return w;
if (f > 0.5)
return w + 1;
return w % 2 ? w + 1 : w;
}
// Compute sign, exponent, fraction
if (v !== v) {
// NaN
// http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
} else if (v === Infinity || v === -Infinity) {
e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
} else if (v === 0) {
e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
} else {
s = v < 0;
v = abs(v);
if (v >= pow(2, 1 - bias)) {
e = min(floor(log(v) / LN2), 1023);
f = roundToEven(v / pow(2, e) * pow(2, fbits));
if (f / pow(2, fbits) >= 2) {
e = e + 1;
f = 1;
}
if (e > bias) {
// Overflow
e = (1 << ebits) - 1;
f = 0;
} else {
// Normalized
e = e + bias;
f = f - pow(2, fbits);
}
} else {
// Denormalized
e = 0;
f = roundToEven(v / pow(2, 1 - bias - fbits));
}
}
// Pack sign, exponent, fraction
bits = [];
for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
bits.push(s ? 1 : 0);
bits.reverse();
str = bits.join('');
// Bits to bytes
bytes = [];
while (str.length) {
bytes.push(parseInt(str.substring(0, 8), 2));
str = str.substring(8);
}
return bytes;
}
function unpackIEEE754(bytes, ebits, fbits) {
// Bytes to bits
var bits = [], i, j, b, str,
bias, s, e, f;
for (i = bytes.length; i; i -= 1) {
b = bytes[i - 1];
for (j = 8; j; j -= 1) {
bits.push(b % 2 ? 1 : 0); b = b >> 1;
}
}
bits.reverse();
str = bits.join('');
// Unpack sign, exponent, fraction
bias = (1 << (ebits - 1)) - 1;
s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
e = parseInt(str.substring(1, 1 + ebits), 2);
f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
} else if (e > 0) {
// Normalized
return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
} else if (f !== 0) {
// Denormalized
return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
} else {
return s < 0 ? -0 : 0;
}
}
function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
function packF64(v) { return packIEEE754(v, 11, 52); }
function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
function packF32(v) { return packIEEE754(v, 8, 23); }
//
// 3 The ArrayBuffer Type
//
(function() {
/** @constructor */
var ArrayBuffer = function ArrayBuffer(length) {
length = ECMAScript.ToInt32(length);
if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');
this.byteLength = length;
this._bytes = [];
this._bytes.length = length;
var i;
for (i = 0; i < this.byteLength; i += 1) {
this._bytes[i] = 0;
}
configureProperties(this);
};
exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer;
//
// 4 The ArrayBufferView Type
//
// NOTE: this constructor is not exported
/** @constructor */
var ArrayBufferView = function ArrayBufferView() {
//this.buffer = null;
//this.byteOffset = 0;
//this.byteLength = 0;
};
//
// 5 The Typed Array View Types
//
function makeConstructor(bytesPerElement, pack, unpack) {
// Each TypedArray type requires a distinct constructor instance with
// identical logic, which this produces.
var ctor;
ctor = function(buffer, byteOffset, length) {
var array, sequence, i, s;
if (!arguments.length || typeof arguments[0] === 'number') {
// Constructor(unsigned long length)
this.length = ECMAScript.ToInt32(arguments[0]);
if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');
this.byteLength = this.length * this.BYTES_PER_ELEMENT;
this.buffer = new ArrayBuffer(this.byteLength);
this.byteOffset = 0;
} else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
// Constructor(TypedArray array)
array = arguments[0];
this.length = array.length;
this.byteLength = this.length * this.BYTES_PER_ELEMENT;
this.buffer = new ArrayBuffer(this.byteLength);
this.byteOffset = 0;
for (i = 0; i < this.length; i += 1) {
this._setter(i, array._getter(i));
}
} else if (typeof arguments[0] === 'object' &&
!(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
// Constructor(sequence<type> array)
sequence = arguments[0];
this.length = ECMAScript.ToUint32(sequence.length);
this.byteLength = this.length * this.BYTES_PER_ELEMENT;
this.buffer = new ArrayBuffer(this.byteLength);
this.byteOffset = 0;
for (i = 0; i < this.length; i += 1) {
s = sequence[i];
this._setter(i, Number(s));
}
} else if (typeof arguments[0] === 'object' &&
(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
// Constructor(ArrayBuffer buffer,
// optional unsigned long byteOffset, optional unsigned long length)
this.buffer = buffer;
this.byteOffset = ECMAScript.ToUint32(byteOffset);
if (this.byteOffset > this.buffer.byteLength) {
throw new RangeError("byteOffset out of range");
}
if (this.byteOffset % this.BYTES_PER_ELEMENT) {
// The given byteOffset must be a multiple of the element
// size of the specific type, otherwise an exception is raised.
throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
}
if (arguments.length < 3) {
this.byteLength = this.buffer.byteLength - this.byteOffset;
if (this.byteLength % this.BYTES_PER_ELEMENT) {
throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
}
this.length = this.byteLength / this.BYTES_PER_ELEMENT;
} else {
this.length = ECMAScript.ToUint32(length);
this.byteLength = this.length * this.BYTES_PER_ELEMENT;
}
if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
}
} else {
throw new TypeError("Unexpected argument type(s)");
}
this.constructor = ctor;
configureProperties(this);
makeArrayAccessors(this);
};
ctor.prototype = new ArrayBufferView();
ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
ctor.prototype._pack = pack;
ctor.prototype._unpack = unpack;
ctor.BYTES_PER_ELEMENT = bytesPerElement;
// getter type (unsigned long index);
ctor.prototype._getter = function(index) {
if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
index = ECMAScript.ToUint32(index);
if (index >= this.length) {
return undefined;
}
var bytes = [], i, o;
for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
i < this.BYTES_PER_ELEMENT;
i += 1, o += 1) {
bytes.push(this.buffer._bytes[o]);
}
return this._unpack(bytes);
};
// NONSTANDARD: convenience alias for getter: type get(unsigned long index);
ctor.prototype.get = ctor.prototype._getter;
// setter void (unsigned long index, type value);
ctor.prototype._setter = function(index, value) {
if (arguments.length < 2) throw new SyntaxError("Not enough arguments");
index = ECMAScript.ToUint32(index);
if (index >= this.length) {
return undefined;
}
var bytes = this._pack(value), i, o;
for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
i < this.BYTES_PER_ELEMENT;
i += 1, o += 1) {
this.buffer._bytes[o] = bytes[i];
}
};
// void set(TypedArray array, optional unsigned long offset);
// void set(sequence<type> array, optional unsigned long offset);
ctor.prototype.set = function(index, value) {
if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
var array, sequence, offset, len,
i, s, d,
byteOffset, byteLength, tmp;
if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
// void set(TypedArray array, optional unsigned long offset);
array = arguments[0];
offset = ECMAScript.ToUint32(arguments[1]);
if (offset + array.length > this.length) {
throw new RangeError("Offset plus length of array is out of range");
}
byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
byteLength = array.length * this.BYTES_PER_ELEMENT;
if (array.buffer === this.buffer) {
tmp = [];
for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
tmp[i] = array.buffer._bytes[s];
}
for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
this.buffer._bytes[d] = tmp[i];
}
} else {
for (i = 0, s = array.byteOffset, d = byteOffset;
i < byteLength; i += 1, s += 1, d += 1) {
this.buffer._bytes[d] = array.buffer._bytes[s];
}
}
} else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
// void set(sequence<type> array, optional unsigned long offset);
sequence = arguments[0];
len = ECMAScript.ToUint32(sequence.length);
offset = ECMAScript.ToUint32(arguments[1]);
if (offset + len > this.length) {
throw new RangeError("Offset plus length of array is out of range");
}
for (i = 0; i < len; i += 1) {
s = sequence[i];
this._setter(offset + i, Number(s));
}
} else {
throw new TypeError("Unexpected argument type(s)");
}
};
// TypedArray subarray(long begin, optional long end);
ctor.prototype.subarray = function(start, end) {
function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }
start = ECMAScript.ToInt32(start);
end = ECMAScript.ToInt32(end);
if (arguments.length < 1) { start = 0; }
if (arguments.length < 2) { end = this.length; }
if (start < 0) { start = this.length + start; }
if (end < 0) { end = this.length + end; }
start = clamp(start, 0, this.length);
end = clamp(end, 0, this.length);
var len = end - start;
if (len < 0) {
len = 0;
}
return new this.constructor(
this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
};
return ctor;
}
var Int8Array = makeConstructor(1, packI8, unpackI8);
var Uint8Array = makeConstructor(1, packU8, unpackU8);
var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
var Int16Array = makeConstructor(2, packI16, unpackI16);
var Uint16Array = makeConstructor(2, packU16, unpackU16);
var Int32Array = makeConstructor(4, packI32, unpackI32);
var Uint32Array = makeConstructor(4, packU32, unpackU32);
var Float32Array = makeConstructor(4, packF32, unpackF32);
var Float64Array = makeConstructor(8, packF64, unpackF64);
exports.Int8Array = exports.Int8Array || Int8Array;
exports.Uint8Array = exports.Uint8Array || Uint8Array;
exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray;
exports.Int16Array = exports.Int16Array || Int16Array;
exports.Uint16Array = exports.Uint16Array || Uint16Array;
exports.Int32Array = exports.Int32Array || Int32Array;
exports.Uint32Array = exports.Uint32Array || Uint32Array;
exports.Float32Array = exports.Float32Array || Float32Array;
exports.Float64Array = exports.Float64Array || Float64Array;
}());
//
// 6 The DataView View Type
//
(function() {
function r(array, index) {
return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
}
var IS_BIG_ENDIAN = (function() {
var u16array = new(exports.Uint16Array)([0x1234]),
u8array = new(exports.Uint8Array)(u16array.buffer);
return r(u8array, 0) === 0x12;
}());
// Constructor(ArrayBuffer buffer,
// optional unsigned long byteOffset,
// optional unsigned long byteLength)
/** @constructor */
var DataView = function DataView(buffer, byteOffset, byteLength) {
if (arguments.length === 0) {
buffer = new ArrayBuffer(0);
} else if (!(buffer instanceof ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) {
throw new TypeError("TypeError");
}
this.buffer = buffer || new ArrayBuffer(0);
this.byteOffset = ECMAScript.ToUint32(byteOffset);
if (this.byteOffset > this.buffer.byteLength) {
throw new RangeError("byteOffset out of range");
}
if (arguments.length < 3) {
this.byteLength = this.buffer.byteLength - this.byteOffset;
} else {
this.byteLength = ECMAScript.ToUint32(byteLength);
}
if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
}
configureProperties(this);
};
function makeGetter(arrayType) {
return function(byteOffset, littleEndian) {
byteOffset = ECMAScript.ToUint32(byteOffset);
if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
throw new RangeError("Array index out of range");
}
byteOffset += this.byteOffset;
var uint8Array = new Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
bytes = [], i;
for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
bytes.push(r(uint8Array, i));
}
if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
bytes.reverse();
}
return r(new arrayType(new Uint8Array(bytes).buffer), 0);
};
}
DataView.prototype.getUint8 = makeGetter(exports.Uint8Array);
DataView.prototype.getInt8 = makeGetter(exports.Int8Array);
DataView.prototype.getUint16 = makeGetter(exports.Uint16Array);
DataView.prototype.getInt16 = makeGetter(exports.Int16Array);
DataView.prototype.getUint32 = makeGetter(exports.Uint32Array);
DataView.prototype.getInt32 = makeGetter(exports.Int32Array);
DataView.prototype.getFloat32 = makeGetter(exports.Float32Array);
DataView.prototype.getFloat64 = makeGetter(exports.Float64Array);
function makeSetter(arrayType) {
return function(byteOffset, value, littleEndian) {
byteOffset = ECMAScript.ToUint32(byteOffset);
if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
throw new RangeError("Array index out of range");
}
// Get bytes
var typeArray = new arrayType([value]),
byteArray = new Uint8Array(typeArray.buffer),
bytes = [], i, byteView;
for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
bytes.push(r(byteArray, i));
}
// Flip if necessary
if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
bytes.reverse();
}
// Write them
byteView = new Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
byteView.set(bytes);
};
}
DataView.prototype.setUint8 = makeSetter(exports.Uint8Array);
DataView.prototype.setInt8 = makeSetter(exports.Int8Array);
DataView.prototype.setUint16 = makeSetter(exports.Uint16Array);
DataView.prototype.setInt16 = makeSetter(exports.Int16Array);
DataView.prototype.setUint32 = makeSetter(exports.Uint32Array);
DataView.prototype.setInt32 = makeSetter(exports.Int32Array);
DataView.prototype.setFloat32 = makeSetter(exports.Float32Array);
DataView.prototype.setFloat64 = makeSetter(exports.Float64Array);
exports.DataView = exports.DataView || DataView;
}());
},{}]},{},[])
;;module.exports=require("native-buffer-browserify").Buffer
},{}],10:[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');
};
},{}],11:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.binarySlice === 'function'
;
}
},{}],12:[function(require,module,exports){
var process=require("__browserify_process"),global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
},{"./support/isBuffer":11,"__browserify_process":10,"inherits":8}],13:[function(require,module,exports){
/**
* Module dependencies.
*/
var Emitter = require('emitter');
var reduce = require('reduce');
/**
* Root reference for iframes.
*/
var root = 'undefined' == typeof window
? this
: window;
/**
* Noop.
*/
function noop(){};
/**
* Check if `obj` is a host object,
* we don't want to serialize these :)
*
* TODO: future proof, move to compoent land
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isHost(obj) {
var str = {}.toString.call(obj);
switch (str) {
case '[object File]':
case '[object Blob]':
case '[object FormData]':
return true;
default:
return false;
}
}
/**
* Determine XHR.
*/
function getXHR() {
if (root.XMLHttpRequest
&& ('file:' != root.location.protocol || !root.ActiveXObject)) {
return new XMLHttpRequest;
} else {
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}
return false;
}
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim
? function(s) { return s.trim(); }
: function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(obj) {
return obj === Object(obj);
}
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(obj) {
if (!isObject(obj)) return obj;
var pairs = [];
for (var key in obj) {
if (null != obj[key]) {
pairs.push(encodeURIComponent(key)
+ '=' + encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
}
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(str) {
var obj = {};
var pairs = str.split('&');
var parts;
var pair;
for (var i = 0, len = pairs.length; i < len; ++i) {
pair = pairs[i];
parts = pair.split('=');
obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return obj;
}
/**
* Expose parser.
*/
request.parseString = parseString;
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
xml: 'application/xml',
urlencoded: 'application/x-www-form-urlencoded',
'form': 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/json': JSON.stringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseHeader(str) {
var lines = str.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var val;
lines.pop(); // trailing CRLF
for (var i = 0, len = lines.length; i < len; ++i) {
line = lines[i];
index = line.indexOf(':');
field = line.slice(0, index).toLowerCase();
val = trim(line.slice(index + 1));
fields[field] = val;
}
return fields;
}
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
function type(str){
return str.split(/ *; */).shift();
};
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
function params(str){
return reduce(str.split(/ *; */), function(obj, str){
var parts = str.split(/ *= */)
, key = parts.shift()
, val = parts.shift();
if (key && val) obj[key] = val;
return obj;
}, {});
};
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
function Response(req, options) {
options = options || {};
this.req = req;
this.xhr = this.req.xhr;
this.text = this.xhr.responseText;
this.setStatusProperties(this.xhr.status);
this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
// getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
// getResponseHeader still works. so we get content-type even if getting
// other headers fails.
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
this.setHeaderProperties(this.header);
this.body = this.req.method != 'HEAD'
? this.parseBody(this.text)
: null;
}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
Response.prototype.get = function(field){
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
Response.prototype.setHeaderProperties = function(header){
// content-type
var ct = this.header['content-type'] || '';
this.type = type(ct);
// params
var obj = params(ct);
for (var key in obj) this[key] = obj[key];
};
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
Response.prototype.parseBody = function(str){
var parse = request.parse[this.type];
return parse
? parse(str)
: null;
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
Response.prototype.setStatusProperties = function(status){
var type = status / 100 | 0;
// status / class
this.status = status;
this.statusType = type;
// basics
this.info = 1 == type;
this.ok = 2 == type;
this.clientError = 4 == type;
this.serverError = 5 == type;
this.error = (4 == type || 5 == type)
? this.toError()
: false;
// sugar
this.accepted = 202 == status;
this.noContent = 204 == status || 1223 == status;
this.badRequest = 400 == status;
this.unauthorized = 401 == status;
this.notAcceptable = 406 == status;
this.notFound = 404 == status;
this.forbidden = 403 == status;
};
/**
* Return an `Error` representative of this response.
*
* @return {Error}
* @api public
*/
Response.prototype.toError = function(){
var req = this.req;
var method = req.method;
var path = req.path;
var msg = 'cannot ' + method + ' ' + path + ' (' + this.status + ')';
var err = new Error(msg);
err.status = this.status;
err.method = method;
err.path = path;
return err;
};
/**
* Expose `Response`.
*/
request.Response = Response;
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
Emitter.call(this);
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {};
this._header = {};
this.on('end', function(){
var res = new Response(self);
if ('HEAD' == method) res.text = null;
self.callback(null, res);
});
}
/**
* Mixin `Emitter`.
*/
Emitter(Request.prototype);
/**
* Set timeout to `ms`.
*
* @param {Number} ms
* @return {Request} for chaining
* @api public
*/
Request.prototype.timeout = function(ms){
this._timeout = ms;
return this;
};
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
Request.prototype.clearTimeout = function(){
this._timeout = 0;
clearTimeout(this._timer);
return this;
};
/**
* Abort the request, and clear potential timeout.
*
* @return {Request}
* @api public
*/
Request.prototype.abort = function(){
if (this.aborted) return;
this.aborted = true;
this.xhr.abort();
this.clearTimeout();
this.emit('abort');
return this;
};
/**
* Set header `field` to `val`, or multiple fields with one object.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.set = function(field, val){
if (isObject(field)) {
for (var key in field) {
this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = val;
this.header[field] = val;
return this;
};
/**
* Get case-insensitive header `field` value.
*
* @param {String} field
* @return {String}
* @api private
*/
Request.prototype.getHeader = function(field){
return this._header[field.toLowerCase()];
};
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function(type){
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Set Accept to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function(type){
this.set('Accept', request.types[type] || type);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} pass
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function(user, pass){
var str = btoa(user + ':' + pass);
this.set('Authorization', 'Basic ' + str);
return this;
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function(val){
if ('string' != typeof val) val = serialize(val);
if (val) this._query.push(val);
return this;
};
/**
* Send `data`, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // querystring
* request.get('/search')
* .end(callback)
*
* // multiple data "writes"
* request.get('/search')
* .send({ search: 'query' })
* .send({ range: '1..5' })
* .send({ order: 'desc' })
* .end(callback)
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"})
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
Request.prototype.send = function(data){
var obj = isObject(data);
var type = this.getHeader('Content-Type');
// merge
if (obj && isObject(this._data)) {
for (var key in data) {
this._data[key] = data[key];
}
} else if ('string' == typeof data) {
if (!type) this.type('form');
type = this.getHeader('Content-Type');
if ('application/x-www-form-urlencoded' == type) {
this._data = this._data
? this._data + '&' + data
: data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!obj) return this;
if (!type) this.type('json');
return this;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function(err, res){
var fn = this._callback;
if (2 == fn.length) return fn(err, res);
if (err) return this.emit('error', err);
fn(res);
};
/**
* Invoke callback with x-domain error.
*
* @api private
*/
Request.prototype.crossDomainError = function(){
var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
err.crossDomain = true;
this.callback(err);
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
Request.prototype.timeoutError = function(){
var timeout = this._timeout;
var err = new Error('timeout of ' + timeout + 'ms exceeded');
err.timeout = timeout;
this.callback(err);
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
*
* @api public
*/
Request.prototype.withCredentials = function(){
this._withCredentials = true;
return this;
};
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function(fn){
var self = this;
var xhr = this.xhr = getXHR();
var query = this._query.join('&');
var timeout = this._timeout;
var data = this._data;
// store callback
this._callback = fn || noop;
// state change
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
if (0 == xhr.status) {
if (self.aborted) return self.timeoutError();
return self.crossDomainError();
}
self.emit('end');
};
// progress
if (xhr.upload) {
xhr.upload.onprogress = function(e){
e.percent = e.loaded / e.total * 100;
self.emit('progress', e);
};
}
// timeout
if (timeout && !this._timer) {
this._timer = setTimeout(function(){
self.abort();
}, timeout);
}
// querystring
if (query) {
query = request.serializeObject(query);
this.url += ~this.url.indexOf('?')
? '&' + query
: '?' + query;
}
// initiate request
xhr.open(this.method, this.url, true);
// CORS
if (this._withCredentials) xhr.withCredentials = true;
// body
if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
// serialize stuff
var serialize = request.serialize[this.getHeader('Content-Type')];
if (serialize) data = serialize(data);
}
// set header fields
for (var field in this.header) {
if (null == this.header[field]) continue;
xhr.setRequestHeader(field, this.header[field]);
}
// send stuff
xhr.send(data);
return this;
};
/**
* Expose `Request`.
*/
request.Request = Request;
/**
* Issue a request:
*
* Examples:
*
* request('GET', '/users').end(callback)
* request('/users').end(callback)
* request('/users', callback)
*
* @param {String} method
* @param {String|Function} url or callback
* @return {Request}
* @api public
*/
function request(method, url) {
// callback
if ('function' == typeof url) {
return new Request('GET', method).end(url);
}
// url first
if (1 == arguments.length) {
return new Request('GET', method);
}
return new Request(method, url);
}
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.get = function(url, data, fn){
var req = request('GET', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.query(data);
if (fn) req.end(fn);
return req;
};
/**
* HEAD `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.head = function(url, data, fn){
var req = request('HEAD', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* DELETE `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Function} fn
* @return {Request}
* @api public
*/
request.del = function(url, fn){
var req = request('DELETE', url);
if (fn) req.end(fn);
return req;
};
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.patch = function(url, data, fn){
var req = request('PATCH', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} data
* @param {Function} fn
* @return {Request}
* @api public
*/
request.post = function(url, data, fn){
var req = request('POST', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} data or fn
* @param {Function} fn
* @return {Request}
* @api public
*/
request.put = function(url, data, fn){
var req = request('PUT', url);
if ('function' == typeof data) fn = data, data = null;
if (data) req.send(data);
if (fn) req.end(fn);
return req;
};
/**
* Expose `request`.
*/
module.exports = request;
},{"emitter":14,"reduce":15}],14:[function(require,module,exports){
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
fn._off = on;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var i = callbacks.indexOf(fn._off || fn);
if (~i) callbacks.splice(i, 1);
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],15:[function(require,module,exports){
/**
* Reduce `arr` with `fn`.
*
* @param {Array} arr
* @param {Function} fn
* @param {Mixed} initial
*
* TODO: combatible error handling?
*/
module.exports = function(arr, fn, initial){
var idx = 0;
var len = arr.length;
var curr = arguments.length == 3
? initial
: arr[idx++];
while (idx < len) {
curr = fn.call(null, curr, arr[idx], ++idx, arr);
}
return curr;
};
},{}],16:[function(require,module,exports){
var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
var rng;
if (global.crypto && crypto.getRandomValues) {
// WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
// Moderately fast, high quality
var _rnds8 = new Uint8Array(16);
rng = function whatwgRNG() {
crypto.getRandomValues(_rnds8);
return _rnds8;
};
}
if (!rng) {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var _rnds = new Array(16);
rng = function() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
_rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return _rnds;
};
}
module.exports = rng;
},{}],17:[function(require,module,exports){
var Buffer=require("__browserify_Buffer");// uuid.js
//
// Copyright (c) 2010-2012 Robert Kieffer
// MIT License - http://opensource.org/licenses/mit-license.php
// Unique ID creation requires a high quality random # generator. We feature
// detect to determine the best RNG source, normalizing to a function that
// returns 128-bits of randomness, since that's what's usually required
var _rng = require('./rng');
// Buffer class to use
var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;
// Maps for number <-> hex string conversion
var _byteToHex = [];
var _hexToByte = {};
for (var i = 0; i < 256; i++) {
_byteToHex[i] = (i + 0x100).toString(16).substr(1);
_hexToByte[_byteToHex[i]] = i;
}
// **`parse()` - Parse a UUID into it's component bytes**
function parse(s, buf, offset) {
var i = (buf && offset) || 0, ii = 0;
buf = buf || [];
s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
if (ii < 16) { // Don't overflow!
buf[i + ii++] = _hexToByte[oct];
}
});
// Zero out remaining bytes if string was short
while (ii < 16) {
buf[i + ii++] = 0;
}
return buf;
}
// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
function unparse(buf, offset) {
var i = offset || 0, bth = _byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html
// random #'s we need to init node and clockseq
var _seedBytes = _rng();
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
var _nodeId = [
_seedBytes[0] | 0x01,
_seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
];
// Per 4.2.2, randomize (14 bit) clockseq
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
// Previous uuid creation time
var _lastMSecs = 0, _lastNSecs = 0;
// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
var i = buf && offset || 0;
var b = buf || [];
options = options || {};
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
// Per 4.2.1.2, use count of uuid's generated during the current clock
// cycle to simulate higher resolution clock
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
// Time since last uuid creation (in msecs)
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
// Per 4.2.1.2, Bump clockseq on clock regression
if (dt < 0 && options.clockseq === undefined) {
clockseq = clockseq + 1 & 0x3fff;
}
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
// time interval
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
nsecs = 0;
}
// Per 4.2.1.2 Throw error if too many uuids are requested
if (nsecs >= 10000) {
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
msecs += 12219292800000;
// `time_low`
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
b[i++] = tl >>> 24 & 0xff;
b[i++] = tl >>> 16 & 0xff;
b[i++] = tl >>> 8 & 0xff;
b[i++] = tl & 0xff;
// `time_mid`
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
b[i++] = tmh >>> 8 & 0xff;
b[i++] = tmh & 0xff;
// `time_high_and_version`
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
b[i++] = tmh >>> 16 & 0xff;
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
b[i++] = clockseq >>> 8 | 0x80;
// `clock_seq_low`
b[i++] = clockseq & 0xff;
// `node`
var node = options.node || _nodeId;
for (var n = 0; n < 6; n++) {
b[i + n] = node[n];
}
return buf ? buf : unparse(b);
}
// **`v4()` - Generate random UUID**
// See https://github.com/broofa/node-uuid for API details
function v4(options, buf, offset) {
// Deprecated - 'format' argument, as supported in v1.2
var i = buf && offset || 0;
if (typeof(options) == 'string') {
buf = options == 'binary' ? new BufferClass(16) : null;
options = null;
}
options = options || {};
var rnds = options.random || (options.rng || _rng)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
for (var ii = 0; ii < 16; ii++) {
buf[i + ii] = rnds[ii];
}
}
return buf || unparse(rnds);
}
// Export public API
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
uuid.parse = parse;
uuid.unparse = unparse;
uuid.BufferClass = BufferClass;
module.exports = uuid;
},{"./rng":16,"__browserify_Buffer":9}],18:[function(require,module,exports){
module.exports={
"name": "Simperium",
"version": "0.0.0",
"build": "20131216.32",
"description": "Simperium client library for Javascript",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "GPL2+",
"dependencies": {
"uuid": "~1.4.1",
"superagent": "git://github.com/Simperium/superagent.git#binary-test"
},
"devDependencies": {
"grunt": "~0.4.2",
"grunt-browserify": "~1.3.0",
"moment": "~2.4.0",
"grunt-jsbeautifier": "~0.2.6",
"grunt-jscs-checker": "~0.2.6",
"grunt-esformatter": "~0.2.0",
"rocambole": "~0.3.1",
"esindent": "~0.4.2",
"grunt-contrib-watch": "~0.5.3"
}
}
},{}],19:[function(require,module,exports){
var Buffer=require("__browserify_Buffer");var util = require( "util" );
var request = require( "superagent" );
function Binary( bucket, document_id, document_key, source, meta, callback ) {
this.bucket = bucket;
this.document_id = document_id;
this.document_key = document_key;
this.source = source || undefined;
if ( "string" === typeof meta ) {
this.contentType = meta;
this.meta = undefined;
} else {
this.contentType = meta["content-type"] || "application/octet-stream";
this.meta = meta;
}
this.callback = callback;
}
function toJSON() {
return this.meta;
}
function url( callback ) {
request
.get( util.format( "https://api.simperium.com/1/%s/%s/i/%s/b/%s", this.bucket.options.app_id, this.bucket.name, this.document_id, this.document_key ) )
.set( "X-Simperium-Token", this.bucket.options.token )
.set( "X-Do-Redirect", "no" )
.end( function(res) {
if ( res.error ) {
callback( res.error, null, res );
return;
}
if ( res.status < 200 || res.status > 299 ) {
callback( res.status, null, res );
return;
}
callback( null, res.text )
} );
}
function get( callback ) {
this.url( function( error, url ) {
if ( error ) {
callback( error, null )
}
request
.get( url )
.responseType( "blob" )
.end( function( res ) {
if ( res.error ) {
callback( res.error, null, res );
return;
}
if ( res.status < 200 || res.status > 299 ) {
callback( res.status, null, res );
return;
}
callback( null, res.body, res );
});
});
}
function put( callback ) {
var _this = this;
callback = callback || this.callback || function() {};
this.getBytes( function( data ) {
request
.put( util.format(
"https://api.simperium.com/1/%s/%s/i/%s/b/%s",
_this.bucket.options.app_id,
_this.bucket.name,
_this.document_id,
_this.document_key ) )
.set( "Content-Type", _this.contentType )
.set( "X-Simperium-Token", bucket.options.token )
.send( data )
.end( function( res ) {
if ( res.error ) {
callback( res.error, null, res );
return;
}
if ( res.status < 200 || res.status > 299 ) {
callback( res.status, null, res );
return;
}
callback( null, res.text, res )
} );
} );
}
function getBytes( source, callback ) {
var reader;
if ( "string" === typeof source ) {
callback( new Buffer( source, "utf8" ) );
return;
}
if ( source instanceof ArrayBuffer ) {
source = new Uint8Array( source );
}
if ( source instanceof Uint8Array ) {
callback( new Buffer( source ) );
return;
}
if ( source instanceof Blob ) {
reader = new FileReader();
reader.onload = function( event ) {
// recurse to normalize ArrayBuffer
getBytes( event.target.result, callback );
};
reader.readAsArrayBuffer( source );
return;
}
callback( new Uint8Array( 0 ) );
}
var binaryMeta = [ "content-length", "hash", "signature", "mtime", "path", "jsmtime", "content-type", "backend" ];
function parse( object, id, bucket ) {
var i, j, newObject = {};
for ( i in object ) {
if ( ! object.hasOwnProperty( i ) ) {
continue;
}
for ( j = 0; j < binaryMeta.length; j++ ) {
if ( "object" !== typeof object[i] || ! ( binaryMeta[j] in object[i] ) ) {
newObject[i] = object[i];
break;
}
}
if ( ! ( i in newObject ) ) {
newObject[i] = new Binary( bucket, id, i, undefined, object[i] );
}
}
return newObject;
}
function mapBinary( object, func_or_object ) {
var i, newObject = {};
for ( i in object ) {
if ( ! object.hasOwnProperty( i ) ) {
continue;
}
if ( object[i] instanceof Binary ) {
object[i].document_key = i;
if ( func_or_object ) {
if ( "function" === typeof func_or_object ) {
// weird: a map function that acts on `this` instead of its first parameter...
newObject[i] = func_or_object.call( object[i] );
} else if ( "undefined" !== typeof func_or_object[i] ) {
newObject[i] = func_or_object[i];
}
} else {
newObject[i] = object[i].meta;
}
} else {
// Should be ok to reference istead of deepCopy...
newObject[i] = object[i];
}
}
return newObject;
}
function haser( func ) {
return function( object ) {
// try/catch is slow, but allows us to break out of the loop
try {
mapBinary( object, func );
} catch ( e ) {
if ( e === func ) {
return true;
}
throw e;
}
return false;
}
}
function throwSomething() {
throw throwSomething;
}
function throwSomethingIfSource() {
if ( this.source ) {
throw throwSomethingIfSource;
}
}
Binary.prototype.url = url;
Binary.prototype.get = get;
Binary.prototype.put = put;
Binary.prototype.toJSON = toJSON;
Binary.prototype.getBytes = function( callback ) {
getBytes( this.source, callback );
};
Binary.parse = parse;
Binary.mapBinary = mapBinary;
Binary.hasBinary = haser( throwSomething );
Binary.hasBinaryWithSource = haser( throwSomethingIfSource );
module.exports = Binary;
},{"__browserify_Buffer":9,"superagent":13,"util":12}],20:[function(require,module,exports){
var util = require( "util" );
var events = require( "events" );
var uuid = require( "uuid" );
var Store = require( "./store" );
var LocalStorage = require( "./localStorage" );
var Message = require( "./message" );
var Cursor = require( "./cursor" );
var Binary = require( "./binary" );
var config = require( "../package.json" );
var format = util.format;
var bound_methods = [
"log",
"on",
"start",
"send",
"on_open",
"on_close",
"load_versions",
"get_version",
"retrieve_changes",
"update",
"pending",
"on_data",
"on_index_page",
"on_entity_version",
"on_changes",
"_entity_id",
"_send_changes",
"_remote_index",
];
function Bucket( name, options, jsondiff ) {
events.EventEmitter.call( this );
// bound methods
bound_methods.forEach( function( bound_method ) {
this[bound_method] = this[bound_method].bind( this );
}, this );
this.name = name;
this.jd = jsondiff;
this.options = options || {};
this.server_options = {};
this.chan = this.options.n;
this.space = format( "%s/%s", this.options.app_id, this.name );
this.username = this.options.username;
this.namespace = format( "%s:%s", this.username, this.space );
this.store = {
meta : new Store(),
data : new Store(),
};
if ( LocalStorage ) {
this.persist = {
meta : new LocalStorage( format( "%s/m/", this.namespace ) ),
data : new LocalStorage( format( "%s/e/", this.namespace ) ),
}
this.store.meta.pipe( this.persist.meta );
this.store.data.pipe( this.persist.data );
} else {
this.persist = null;
}
Object.defineProperty( this, "clientid", {
get : function() {
return this.store.meta.get( "clientid" );
},
set : function( value ) {
return this.store.meta.set( "clientid", value );
},
} );
if ( ! ( "persist_clientid" in this.options ) || ! this.options.persist_clientid ) {
this.clientid = null;
}
if ( ! this.clientid || 0 !== this.clientid.indexOf( "sjs" ) ) {
this.clientid = format( "sjs-%s-%s", config.build, uuid() );
}
this.cb_l = null;
this.connected = false;
this.initialized = false;
this.authorized = false;
if ( LocalStorage && ( ! ( "nostore" in this.options ) || ! this.options.nostore ) ) {
this.store.meta.fillOnceFrom( this.persist.meta );
this.loaded = this.store.data.fillOnceFrom( this.persist.data, this._filter_stored_data.bind( this ) );
this.log( "localstorage loaded %d entities", this.loaded );
} else {
this.loaded = 0;
this.log( "not loading from localstorage" );
}
this.store.meta.add( "last_cv", "0" );
this.store.meta.add( "ccid", uuid() );
this.data = {
send_queue : [],
send_queue_timer : null,
};
this.started = false;
this._last_pending = null;
this._send_backoff = 15000;
this._backoff_max = 120000;
this._backoff_min = 15000;
this.log( "bucket created: username=%s, options=%j", this.username, this.options );
}
util.inherits( Bucket, events.EventEmitter );
Bucket.prototype.log = function( message_format ) {
var args = Array.prototype.slice.call( arguments );
args.unshift( "log" )
// this.emit( "log", ... );
this.emit.apply( this, args );
}
Bucket.prototype._on = Bucket.prototype.on;
Bucket.prototype.on = function( event, callback ) {
if ( "local" === event || "get" === event ) {
this.cb_l = callback;
return this;
}
return this._on.apply( this, arguments );
};
Bucket.prototype._filter_stored_data = function( data ) {
if ( ! this._verify( data ) ) {
this.log( "ignoring CORRUPT data=%j", data );
return;
}
data.check = null;
return data;
}
Bucket.prototype._verify = function( data ) {
if ( "object" !== typeof data || ! ( "object" in data ) || ! ( "version" in data ) ) {
return false;
}
if ( ! this.jd.entries( data.object ) ) {
if ( "last" in data && this.jd.entries( data.last ) > 0 ) {
return true;
} else {
return false;
}
} else {
if ( "undefined" === typeof data.version || null === data.version ) {
return false;
}
}
return true;
};
Bucket.prototype._entity_id = function( id ) {
if ( "undefined" === typeof id || null === id ) {
return id;
}
if ( ! ( "expose_namespace" in this.server_options ) || ! this.server_options.expose_namespace ) {
return id;
}
if ( id.split( "/" ).length > 1 ) {
return id;
}
return format( "%s/%s", this.server_options.namespace, id );
};
Bucket.prototype.start = function() {
var init;
this.log( "started initialized=%d, authorized=%d", this.initialized, this.authorized );
this.namespace = format( "%s:%s", this.username, this.space );
this.started = true;
this.first = false;
if ( ! this.authorized ) {
if ( this.connected ) {
this.first = true;
this.irequest_time = Date.now();
this.index_request = true;
this.notify_index = {};
init = {
app_id : this.options.app_id,
token : this.options.token,
name : this.name,
clientid : this.clientid,
build : config.build,
};
if ( "undefined" !== this.options.presence_debounce && this.options.presence_debounce ) {
init.presence_debounce = this.options.presence_debounce;
}
if ( "undefined" !== this.options.presence_session && this.options.presence_session ) {
init.presence_session = this.options.presence_session;
}
if ( ! this.initialized ) {
init.cmd = new Message.INDEX( { data: 1, limit: ( "limit" in this.options ) ? parseInt( this.options.limit, 10 ) : 40 } );
}
this.send( new Message.INIT( init ) );
this.log( "sent init=%j waiting for auth", init );
} else {
this.log( "waiting for connect" );
}
return;
}
if ( ! this.initialized ) {
if ( ! this.first ) {
this.notify_index = {};
this._refresh_store();
}
} else {
this.log( "retrieve changes from start" );
this.retrieve_changes();
}
};
Bucket.prototype.on_open = function() {
this.connected = true;
if ( this.started ) {
this.start();
}
};
Bucket.prototype.on_close = function() {
this.connected = false;
this.authorized = false
};
Bucket.prototype.on_data = function( data ) {
var _this = this;
if ( data instanceof Message.AUTH ) {
if ( ! data.username ) {
this.log( "auth error: %j", data );
this.started = false;
this.emit( "error", "auth" );
} else {
this.username = data.username;
this.authorized = true;
if ( this.initialized ) {
return this.start();
}
this.emit( "auth", this.username );
}
} else if ( data instanceof Message.CHANGE_VERSION && ! data.version ) {
this.log( "cv out of sync, refreshing index" );
return setTimeout( function() {
return _this._refresh_store();
} );
} else if ( data instanceof Message.CHANGES && data.changes ) {
if ( "0" === this.store.meta.get( "last_cv" ) && 0 === data.changes.length && ! this.cv_check ) {
this.cv_check = true;
this._refresh_store();
}
return this.on_changes( this.jd.deepCopy( data.changes ) );
} else if ( data instanceof Message.INDEX ) {
this.log( "index msg received: time_delta=%d", Date.now() - this.irequest_time );
return this.on_index_page( this.jd.deepCopy( data ) );
} else if ( data instanceof Message.ENTITY ) {
if ( null === data.data ) {
return this.on_entity_version( null, data.id, data.version );
} else {
return this.on_entity_version( this.jd.deepCopy( data.data.data ), data.id, data.version ); // :)
}
} else if ( data instanceof Message.OPTIONS ) {
this.server_options = this.jd.deepCopy( data );
this.log( "options_received=%j", this.server_options );
if ( "schema" in this.server_options && this.server_options.schema ) {
this.schema = this.server_options.schema;
this.log( "schema=%j", this.schema );
}
this.emit( "server_options", this.server_options );
} else if ( data instanceof Message.REMOTE_INDEX ) {
return this._remote_index();
} else {
return this.log( "unknown message: %s", data );
}
};
Bucket.prototype.send = function( message ) {
this.log( "sending: %d:%s", this.chan, message );
this.emit( "message", message, this.chan );
}
Bucket.prototype._refresh_store = function() {
this.log( "_refresh_store(): loading index" );
this.send( new Message.INDEX( { data: 1, limit: ( "limit" in this.options ) ? parseInt( this.options.limit, 10 ) : 40 } ) );
this.irequest_time = Date.now();
this.index_request = true;
};
Bucket.prototype.on_index_page = function( response ) {
var item, loaded, now, page_req, _i, _len, _this = this;
now = Date.now();
this.log( "index response time: %d", now - this.irequest_time );
this.log( "on_index_page(): index page received, current=%s, response=%j", response["current"], response );
loaded = 0;
for ( _i = 0, _len = response.index.length; _i < _len; _i++ ) {
item = response.index[_i];
item["id"] = this._entity_id( item["id"] );
this.notify_index[item["id"]] = false;
loaded++;
setTimeout( ( function( item ) {
return function() {
return _this.on_entity_version( item['d'], item['id'], item['v'] );
};
} )( item ) );
}
if ( ! ( "mark" in response ) || ! response.mark || "limit" in this.options ) {
this.index_request = false;
this.store.meta.set( "last_cv", "current" in response && response.current ? response.current : "0" );
if ( 0 === loaded ) {
return this._index_loaded();
}
} else {
this.index_request = true;
this.log( "index last process time=%d, page_delay=%d", Date.now() - now, this.options["page_delay"] );
page_req = function( mark ) {
_this.send( new Message.INDEX( { data: 1, mark: mark, limit: 100 } ) );
return _this.irequest_time = Date.now();
};
return setTimeout( ( function( mark ) {
return function() {
return page_req( mark );
};
} )( response.mark ), this.options.page_delay );
}
};
Bucket.prototype.load_versions = function( id, versions ) {
var entity, min, max, version;
id = this._entity_id( id );
entity = this.store.data.get( id );
if ( ! entity ) {
return false;
}
min = Math.max( entity.version - ( versions + 1 ), 1 );
max = entity.version - 1;
for ( version = min; version <= max; version++ ) {
this.log( "loading version %s.%d", id, version );
this.send( new Message.ENTITY( { id: id, version: version } ) );
}
};
Bucket.prototype.get_version = function( id, version ) {
id = this._entity_id( id )
this.send( new Message.ENTITY( { id: id, version: version } ) );
};
Bucket.prototype.on_entity_version = function( data, id, version ) {
var entity, data_copy, nid, notify_event, hasBinary, to_load;
id = this._entity_id( id );
this.log( "on_entity_version( %j, %s, %s )", data, id, version );
if ( null != data ) {
data_copy = this.jd.deepCopy( data );
} else {
data_copy = null;
}
if ( ! this.initialized && this.listeners( "notify_init" ).length ) {
notify_event = "notify_init";
} else {
notify_event = "notify";
}
hasBinary = "binary_backend" in this.server_options && this.server_options.binary_backend;
entity = this.store.data.get( id );
if ( entity && "last" in entity && this.jd.entries( entity.last ) ) {
data_copy = this.jd.deepCopy( entity.last );
this.emit( notify_event, id, hasBinary ? Binary.parse( data_copy, id, this ) : data_copy, null );
this.notify_index[id] = true;
return this._check_update( id );
} else if ( entity && version < entity.version ) {
this.emit( "notify_version", id, hasBinary ? Binary.parse( data_copy, id, this ) : data_copy, version );
return;
} else {
if ( ! entity ) {
entity = {};
}
entity.id = id;
entity.object = data;
entity.version = parseInt( version, 10 );
this.store.data.set( id, entity );
this.emit( notify_event, id, hasBinary ? Binary.parse( data_copy, id, this ) : data_copy, version );
this.notify_index[id] = true;
to_load = 0;
for ( nid in this.notify_index ) {
if ( ! this.notify_index.hasOwnProperty( nid ) ) {
continue;
}
if ( false === this.notify_index[nid] ) {
to_load++;
}
}
if ( ! to_load && false === this.index_request ) {
return this._index_loaded();
}
}
};
Bucket.prototype._index_loaded = function() {
this.log( "index loaded: initialized=%d", this.initialized );
if ( ! this.initialized ) {
this.emit( "ready" );
}
this.initialized = true;
this.log( "retrieve changes from index loaded" );
this.retrieve_changes()
};
/**
* key: id of object
* new_object: latest server version of object (includes latest diff)
* orig_object: the previous server version of object that the client had
* diff: the newly received incoming diff (orig_object + diff = new_object)
*/
Bucket.prototype._notify_client = function( key, new_object, orig_object, diff, version ) {
var c_object, cursor, captured, element, fieldname, new_data, o_diff, offsets, t_diff, t_object, hasBinary;
key = this._entity_id( key );
this.log( "_notify_client( %s, %j, %j, %j )", key, new_object, orig_object, diff );
hasBinary = "binary_backend" in this.server_options && this.server_options.binary_backend;
if ( null == this.cb_l ) {
this.log( "no get callback, notifying without transform" );
if ( hasBinary ) {
this.emit( "notify", key, Binary.parse( new_object, key, this ), version );
} else {
this.emit( "notify", key, new_object, version );
}
return;
}
c_object = this.cb_l( key );
if ( hasBinary && Binary.hasBinary( c_object ) ) {
// Replace any binary properties with metadata
c_object = Binary.mapBinary( c_object, orig_object ); // eventually, want to send metadata of new_object. That'll happen in the t_diff stuff below.
}
t_object = null;
t_diff = null;
cursor = null;
offsets = [];
captured = false;
if ( "array" === this.jd.typeOf( c_object ) ) {
element = c_object[2];
fieldname = c_object[1];
c_object = c_object[0];
cursor = new Cursor( element, this.jd.dmp );
captured = cursor.capture();
if ( captured ) {
offsets[0] = cursor.startOffset;
if ( "endOffset" in cursor ) {
offsets[1] = cursor.endOffset;
}
}
}
if ( ( null != c_object ) && ( null != orig_object ) ) {
this.log( "going to do object diff new diff=%j", diff );
o_diff = this.jd.object_diff( orig_object, c_object, this.schema );
this.log( "client/server version diff=%j", o_diff );
if ( 0 === this.jd.entries( o_diff ) ) {
this.log( "local diff 0 entries" );
t_diff = diff;
t_object = orig_object;
} else {
this.log( "client modified doing transform o_diff=%j, orig_object=%j, c_object=%j", o_diff, orig_object, c_object );
t_diff = this.jd.transform_object_diff( o_diff, diff, orig_object, this.schema );
t_object = new_object;
}
if ( captured ) {
new_data = this.jd.apply_object_diff_with_offsets( t_object, t_diff, fieldname, offsets );
if ( null != element && "value" in element ) {
element["value"] = new_data[ fieldname ];
}
cursor.startOffset = offsets[0];
if ( offsets.length > 1 ) {
cursor.endOffset = offsets[1];
if ( cursor.startOffset >= cursor.endOffset ) {
cursor.collapsed = true;
}
}
cursor.restore();
} else {
this.log( "in regular apply_object_diff t_object=%j, t_diff=%j", t_object, t_diff );
new_data = this.jd.apply_object_diff( t_object, t_diff );
}
this.log( "notifying client of new data for [%s]=%j", key, new_data );
} else if ( new_object ) {
new_data = new_object;
} else {
new_data = null;
version = null;
}
if ( hasBinary ) {
return this.emit( "notify", key, Binary.parse( new_data, key, this ), version );
} else {
return this.emit( "notify", key, new_data, version );
}
};
Bucket.prototype._check_update = function( id ) {
var entity, change, found, _i, _len;
id = this._entity_id( id );
entity = this.store.data.get( id );
this.log( "_check_update( %s )", id );
if ( ! entity ) {
return false;
}
if ( entity.change ) {
found = false;
for ( _i = 0, _len = this.data.send_queue.length; _i < _len; _i++ ) {
change = this.data.send_queue[_i];
if ( change["id"] === entity.change["id"] && change["ccid"] === entity.change["ccid"] ) {
found = true;
break;
}
}
if ( ! found ) {
this._queue_change( [ entity.change, null ] );
return true;
}
return false;
}
if ( null != entity.check ) {
return false;
}
if ( "last" in entity && this.jd.equals( entity.object, entity.last ) ) {
delete entity.last;
this.store.data.set( id, entity );
if ( this.persist ) {
this.persist.data.delete( id );
}
return false;
}
change = this._make_change( id );
if ( null != change ) {
entity.change = change;
this.store.data.set( id, entity );
this._queue_change( change );
} else if ( this.persist ) {
this.persist.data.delete( id );
}
return true;
};
Bucket.prototype.update = function( id, object ) {
var entity, allowed_slashes, change, slashes, hasBinary, _i, _len, _this = this;
id = this._entity_id( id );
if ( 1 === arguments.length ) {
if ( null == this.cb_l ) {
throw new Error( "missing 'local' callback" );
} else {
object = this.cb_l( id );
if ( "array" === this.jd.typeOf( object ) ) {
object = object[0];
}
}
}
this.log( "update( %s )", id );
if ( null == id && null == object ) {
return false;
}
if ( "expose_namespace" in this.server_options && this.server_options.expose_namespace ) {
allowed_slashes = 1;
} else {
allowed_slashes = 0;
}
hasBinary = "binary_backend" in this.server_options && this.server_options.binary_backend;
if ( null != id ) {
slashes = id.split( "/" ).length - 1;
if ( id.length === 0 || slashes > allowed_slashes ) {
return false;
}
} else {
id = uuid();
id = this._entity_id( id );
}
entity = this.store.data.get( id );
if ( ! entity ) {
entity = {
id : id,
object : {},
version : null,
change : null,
check : null
};
this.store.data.set( id, entity );
}
if ( hasBinary && Binary.hasBinaryWithSource( object ) ) {
// Replace binary properties with metadata
entity.last = this.jd.deepCopy( Binary.mapBinary( object ) );
entity.binary = object;
} else {
entity.last = this.jd.deepCopy( object );
}
// entity.modified = Date.now() / 1000;
this.store.data.set( id, entity );
for ( _i = 0, _len = this.data.send_queue.length; _i < _len; _i++ ) {
change = this.data.send_queue[_i];
if ( String( id ) === change["id"] ) {
this.log( "update( %s ) found pending change, aborting", id );
return null;
}
}
if ( null != entity.check ) {
clearTimeout( entity.check );
}
entity.check = setTimeout( ( function( id, entity ) {
return function() {
var change;
entity.check = null;
change = _this._make_change( id );
entity.change = change[0];
delete entity.last;
_this.store.data.set( id, entity );
return _this._queue_change( change );
};
} )( id, entity ), this.options["update_delay"] );
return id;
};
/**
* create change objects
*/
Bucket.prototype._make_change = function( id ) {
var entity, c_object, b_object, change, hasBinary;
id = this._entity_id( id );
this.log( "_make_change( %s )", id );
entity = this.store.data.get( id );
change = {
id : String( id ),
ccid : uuid()
};
hasBinary = "binary_backend" in this.server_options && this.server_options.binary_backend;
if ( ! this.initialized ) {
if ( 'last' in entity ) {
c_object = entity.last;
b_object = entity.binary || null;
} else {
return null;
}
} else {
if ( null == this.cb_l ) {
if ( 'last' in entity ) {
c_object = entity.last;
b_object = entity.binary || null;
} else {
return null;
}
} else {
c_object = this.cb_l( id );
if ( "array" === this.jd.typeOf( c_object ) ) {
c_object = c_object[0];
}
if ( hasBinary && Binary.hasBinary( c_object ) ) {
if ( Binary.hasBinaryWithSource( c_object ) ) {
b_object = c_object;
} else {
b_object = null;
}
// Replace binary properties with metadata
c_object = Binary.mapBinary( c_object );
}
}
}
if ( null != entity.version ) {
change["sv"] = entity.version;
}
if ( null === c_object && null != entity.version ) {
change["o"] = "-";
this.log( "deletion requested for %s", id );
} else if ( null != c_object && null != entity.object ) {
change["o"] = "M";
if ( "sendfull" in entity ) {
change["d"] = this.jd.deepCopy( c_object );
delete entity.sendfull;
this.store.data.set( id, entity );
} else {
this.log( "object_diff ghost=%j, client=%j, schema=%d", entity.object, c_object, this.schema );
change["v"] = this.jd.object_diff( entity.object, c_object, this.schema );
if ( 0 === this.jd.entries( change["v"] ) ) {
change = null;
}
}
} else {
change = null;
b_object = null;
}
this.log( "_make_change( %s ) returning: %j, binary? %d", id, change, !! b_object );
return [ change, b_object ];
};
Bucket.prototype._queue_change = function( change ) {
var _this = this;
var b_object = change[1];
change = change[0];
if ( null == change ) {
return;
}
this.log( "_queue_change( %s:%s ): sending", change["id"], change["ccid"] );
this.data.send_queue.push( change );
this.send( new Message.CHANGES( change ) );
if ( b_object ) {
Binary.mapBinary( b_object, function() {
this.put();
} );
}
this._check_pending();
if ( null != this.data.send_queue_timer ) {
clearTimeout( this.data.send_queue_timer );
}
return this.data.send_queue_timer = setTimeout( this._send_changes, this._send_backoff );
};
Bucket.prototype._send_changes = function() {
var change, _i, _len;
if ( 0 === this.data.send_queue.length ) {
this.log( "send_queue empty, done" );
this.data.send_queue_timer = null;
return;
}
if ( ! this.connected ) {
this.log( "_send_changes: not connected" );
} else {
for ( _i = 0, _len = this.data.send_queue; _i < _len; _i++ ) {
change = this.data.send_queue[_i];
this.log( "sending change=%j", change );
this.send( new Message.CHANGES( change ) );
}
}
this._send_backoff = this._send_backoff * 2;
if ( this._send_backoff > this._backoff_max ) {
this._send_backoff = this._backoff_max;
}
return this.data.send_queue_timer = setTimeout( this._send_changes, this._send_backoff );
};
Bucket.prototype.retrieve_changes = function() {
this.log( "requesting changes since cv=%s", this.store.meta.get( "last_cv" ) );
this.send( new Message.CHANGE_VERSION( { version: this.store.meta.get( "last_cv" ) } ) );
};
Bucket.prototype.on_changes = function( response ) {
var entity, change, check_updates, id, idx, new_object, op, orig_object, pd, pending, pending_to_delete, reload_needed, _fn, _i, _j, _ilen, _jlen, _this = this;
check_updates = [];
reload_needed = false;
this._send_backoff = this._backoff_min;
this.log( "on_changes(): response=%j", response );
for ( _i = 0, _ilen = response.length; _i < _ilen; _i++ ) {
change = response[_i];
id = change["id"];
id = this._entity_id( id );
this.log( "on_changes(): processing id=%s", id );
pending_to_delete = [];
for ( _j = 0, _jlen = this.data.send_queue.length; _j < _jlen; _j++ ) {
pending = this.data.send_queue[_j];
if ( change["clientid"] === this.clientid && id === this._entity_id( pending["id"] ) ) {
this.log( "deleting change for id=%s", id );
change["local"] = true;
pending_to_delete.push( pending );
check_updates.push( id );
}
}
for ( _j = 0, _jlen = pending_to_delete.length; _j < _jlen; _j++ ) {
pd = pending_to_delete[_j];
entity = this.store.data.get( this._entity_id( pd["id"] ) );
entity.change = null;
this.store.data.set( id, entity );
this.data.send_queue = ( function() {
var _i, _ilen, p, _results;
_results = [];
for ( _i = 0, _ilen = this.data.send_queue.length; _i < _ilen; _i++ ) {
p = this.data.send_queue[_i];
if ( p !== pd ) {
_results.push( p );
}
}
return _results;
} ).call( this );
}
if ( pending_to_delete.length > 0 ) {
this._check_pending();
}
this.log( "send_queue=%j", this.data.send_queue );
if ( "error" in change && change.error ) {
switch ( change.error ) {
case 412:
this.log( "on_changes(): empty change, dont check" );
idx = check_updates.indexOf( id );
if ( idx > -1 ) {
check_updates.splice( idx, 1 );
}
break;
case 409:
this.log( "on_changes(): duplicate change, ignoring" );
break;
case 405:
this.log( "on_changes(): bad version" );
entity = this.store.data.get( id );
if ( entity ) {
entity.version = null;
this.store.data.set( id, entity );
}
reload_needed = true;
break;
case 440:
this.log( "on_changes(): bad diff, sending full object" );
entity = this.store.data.get( id );
entity.sendfull = true;
this.store.data.set( id, entity );
break;
default:
this.log( "on_changes(): error for last change, reloading" );
entity = this.store.data.get( id );
if ( entity ) {
entity.version = null;
this.store.data.set( id, entity );
}
reload_needed = true;
}
} else {
op = change["o"];
if ( "-" === op ) {
this.store.data.delete( id );
if ( ! ( "local" in change ) ) {
this._notify_client( id, null, null, null, null );
}
} else if ( "M" === op ) {
entity = this.store.data.get( id );
if (
( "sv" in change && change.sv && null != entity && null != entity.version && entity.version === change["sv"] )
||
( ! ( "sv" in change ) || ! change.sv )
||
1 === change["ev"]
) {
if ( null == entity ) {
entity = {
id : id,
object : {},
version : null,
change : null,
check : null
};
}
this.log( "processing modify for %j", entity );
orig_object = this.jd.deepCopy( entity.object );
entity.object = this.jd.apply_object_diff( entity.object, change["v"] );
entity.version = change["ev"];
this.store.data.set( id, entity );
new_object = this.jd.deepCopy( entity.object );
if ( ! ( "local" in change ) ) {
this._notify_client( id, new_object, orig_object, change["v"], change["ev"] );
}
} else if ( null != entity && null != entity.version && change["ev"] <= entity.version ) {
this.log( "old or duplicate change received, ignoring, change.ev=%s, entity.version=%s", change["ev"], entity.version );
} else {
if ( null == entity ) {
this.log( "version mismatch couldnt apply change, change.ev=%s, entity=null", change["ev"] );
} else {
this.log( "version mismatch couldnt apply change, change.ev=%s, entity.version=%s", change["ev"], entity.version );
entity.version = null;
this.store.data.set( id, entity );
}
reload_needed = true;
}
} else {
this.log( "no operation found for change" );
}
if ( ! reload_needed ) {
this.store.meta.set( "last_cv", change["cv"] );
this.log( "checkpoint cv=%s, ccid=%s", this.store.meta.get( "last_cv" ), this.store.meta.get( "ccid" ) );
}
}
}
if ( reload_needed ) {
this.log( "reload needed, refreshing store" );
setTimeout( function() {
return _this._refresh_store();
} );
} else {
_fn = function( id ) {
return setTimeout( ( function() {
return _this._check_update( id );
} ), _this.options["update_delay"] );
};
for ( _i = 0, _ilen = check_updates.length; _i < _ilen; _i++ ) {
id = check_updates[_i];
_fn(id);
}
}
};
Bucket.prototype.pending = function() {
var pending_ids, _i, _len;
pending_ids = [];
for ( _i = 0, _len = this.data.send_queue.length; _i < _len; _i++ ) {
pending_ids.push( this._entity_id( this.data.send_queue[_i].id ) );
}
this.log( "pending=%j", pending_ids );
return pending_ids;
};
Bucket.prototype._check_pending = function() {
var curr_pending, diff, _i, _len;
if ( ! this.listeners( "notify_pending" ).length ) {
return;
}
curr_pending = this.pending();
diff = true;
if ( this._last_pending ) {
diff = false;
if ( this._last_pending.length === curr_pending.length ) {
for ( _i = 0, _len = this._last_pending.length; _i < _len; _i++ ) {
if ( -1 === curr_pending.indexOf( this._last_pending[_i] ) ) {
diff = true;
}
}
} else {
diff = true;
}
}
if ( diff ) {
this._last_pending = curr_pending;
this.emit( "notify_pending", curr_pending );
}
};
Bucket.prototype._remote_index = function() {
var remote_index, _i, _len;
remote_index = {
current : this.store.meta.get( "last_cv" ),
index : [],
pending : []
};
this.store.data.keys().forEach( function( key ) {
remote_index["index"].push( {
id : key,
v : this.store.data.get( key ).version,
} );
}, this );
for ( _i = 0, _len = this.data.send_queue.length; _i < _len; _i++ ) {
remote_index["pending"].push( this.jd.deepCopy(
this.data.send_queue[_i]
) );
}
return this.send( new Message.REMOTE_INDEX( remote_index ) );
};
Bucket.prototype.binary = function( id, key, source, meta, callback ) {
return new Binary( this, id, key, source, meta, callback );
};
module.exports = Bucket;
},{"../package.json":18,"./binary":19,"./cursor":22,"./localStorage":24,"./message":25,"./store":27,"events":7,"util":12,"uuid":17}],21:[function(require,module,exports){
var util = require( "util" );
var events = require( "events" );
var SockJS = require( "sockjs" );
var Message = require( "./message" );
function Connection( options ) {
events.EventEmitter.call( this );
this.options = {};
Object.getOwnPropertyNames( this.defaults ).concat( Object.getOwnPropertyNames( options ) ).forEach( function( property ) {
if ( property in this.options ) {
return;
}
if ( property in options ) {
this.options[property] = options[property];
} else {
this.options[property] = this.defaults[property];
}
}, this );
if ( ! ( "port" in this.options ) ) {
this.options.port = -1 === this.options.host.indexOf( "api.simperium.com" ) ? 80 : 443;
}
if ( ( ! ( "scheme" in this.options ) ) || ( "http" !== this.options.scheme && "https" !== this.options.scheme ) ) {
this.options.scheme = 443 === this.options.port ? "https" : "http";
}
if (
( 80 === this.options.port && "http" === this.options.scheme )
||
( 443 === this.options.port && "https" === this.options.scheme )
) {
this.url = util.format( "%s://%s/%s", this.options.scheme, this.options.host, this.options.path );
} else {
this.url = util.format( "%s://%s:%d/%s", this.options.scheme, this.options.host, this.options.port, this.options.path );
}
this.stopped = false;
this.backoff = this.options.backoff;
this.hb = this.options.hb;
this.hb_check = this.hb_check.bind( this );
this.connect = this.connect.bind( this );
this.connect();
}
util.inherits( Connection, events.EventEmitter );
Connection.prototype.defaults = {
debug: false,
backoff: 3000,
hb: 1,
host: "api.simperium.com",
};
Connection.prototype.connect = function() {
this.hb_timer = null;
this.last_message_time = 0;
this.sock = new SockJS( this.url, undefined, this.options );
this.sock.onopen = this._on_open.bind( this );
this.sock.onerror = this._on_error.bind( this );
this.sock.onmessage = this._on_message.bind( this );
this.sock.onclose = this._on_close.bind( this );
};
Connection.prototype.start = function() {
this.stopped = false;
};
Connection.prototype.stop = function() {
this.stopped = true;
if ( "undefined" !== typeof this.sock && this.sock ) {
try {
this.sock.close();
} catch ( error ) {}
}
};
Connection.prototype.send = function( message ) {
this.sock.send( message.toString() );
};
Connection.prototype._on_open = function() {
this.backoff = this.options.backoff;
this.hb_timer = setTimeout( this.hb_check, 20000 );
this.emit( "open" );
};
Connection.prototype._on_close = function() {
if ( this.backoff < 4000 ) {
this.backoff = this.backoff + 1;
} else {
this.backoff = 15000;
}
if ( this.hb_timer ) {
clearTimeout( this.hb_timer );
this.hb_timer = null
}
if ( ! this.stopped ) {
setTimeout( this.connect, this.backoff );
}
};
Connection.prototype._on_error = function( error ) {
this.emit( "error", error );
this.stop();
};
Connection.prototype._on_message = function( event ) {
var data, colon, channel, message;
this.last_message_time = Date.now();
data = event.data;
colon = data.indexOf(":");
channel = parseInt( data.substr( 0, colon ), 10 );
try {
if ( isNaN( channel ) ) {
channel = null;
message = Message.parse( data );
} else {
message = Message.parse( data.substr( colon + 1 ) );
}
} catch ( error ) {
return;
}
if ( message instanceof Message.HEARTBEAT ) {
this.hb = parseInt( data.substr( 2 ), 10 );
return;
}
this.emit( "message", message, channel );
};
Connection.prototype.hb_check = function() {
var delay;
if ( this.sock.readyState !== this.sock.OPEN ) {
return;
}
delay = Date.now() - this.last_message_time;
if ( delay > 40000 ) {
this.sock.close();
} else if ( delay > 15000 ) {
this.sock.send( util.format( "h:%d", this.hb ) );
}
this.hb_timer = setTimeout( this.hb_check, 20000 );
};
module.exports = Connection;
},{"./message":25,"events":7,"sockjs":"+z1VBF","util":12}],22:[function(require,module,exports){
function Cursor( element, diffMatchPatch ) {
this.element = element;
this.dmp = diffMatchPatch;
};
Cursor.prototype.capture = function() {
var text, selectionStart, selectionEnd, doc, range, newRange;
if ( "activeElement" in this.element && ! this.element.activeElement ) {
// Safari specific code.
// Restoring a cursor in an unfocused element causes the focus to jump.
return false;
}
this.padLength = this.dmp.Match_MaxBits / 2; // Normally 16.
text = this.element.value;
if ( "selectionStart" in this.element ) { // W3
try {
selectionStart = this.element.selectionStart;
selectionEnd = this.element.selectionEnd;
} catch ( error ) {
// No cursor; the element may be "display:none".
return false;
}
this.startPrefix = text.substring( selectionStart - this.padLength, selectionStart );
this.startSuffix = text.substring( selectionStart, selectionStart + this.padLength );
this.startOffset = selectionStart;
this.collapsed = selectionStart == selectionEnd;
if ( ! this.collapsed ) {
this.endPrefix = text.substring( selectionEnd - this.padLength, selectionEnd );
this.endSuffix = text.substring( selectionEnd, selectionEnd + this.padLength );
this.endOffset = selectionEnd;
}
} else { // IE
// Walk up the tree looking for this textarea's document node.
doc = this.element;
while ( doc.parentNode ) {
doc = doc.parentNode;
}
if ( ! doc.selection || ! doc.selection.createRange ) {
// Not IE?
return false;
}
range = doc.selection.createRange();
if ( range.parentElement() !== this.element ) {
// Cursor not in this textarea.
return false;
}
newRange = doc.body.createTextRange();
this.collapsed = "" === range.text;
newRange.moveToElementText( this.element );
if ( ! this.collapsed ) {
newRange.setEndPoint( "EndToEnd", range );
this.endPrefix = newRange.text;
this.endOffset = this.endPrefix.length;
this.endPrefix = this.endPrefix.substring(this.endPrefix.length - this.padLength );
}
newRange.setEndPoint( "EndToStart", range );
this.startPrefix = newRange.text;
this.startOffset = this.startPrefix.length;
this.startPrefix = this.startPrefix.substring( this.startPrefix.length - this.padLength );
newRange.moveToElementText( this.element );
newRange.setEndPoint( "StartToStart", range );
this.startSuffix = newRange.text.substring( 0, this.padLength );
if ( ! this.collapsed ) {
newRange.setEndPoint( "StartToEnd", range );
this.endSuffix = newRange.text.substring( 0, this.padLength );
}
}
// Record scrollbar locations
if ( "scrollTop" in this.element ) {
this.scrollTop = this.element.scrollTop / this.element.scrollHeight;
this.scrollLeft = this.element.scrollLeft / this.element.scrollWidth;
}
return true;
};
Cursor.prototype.restore = function() {
var newText, pattern1, pattern2, diff, cursorStartPoint, cursorEndPoint, doc, snippet, ieStartPoint, newRange;
// Set some settings which tweak the matching behaviour.
var dmpSettings = [ this.dmp.Match_Distance, this.dmp.Match_Threshold ];
// Maximum distance to search from expected location.
this.dmp.Match_Distance = 1000;
// At what point is no match declared (0.0 = perfection, 1.0 = very loose)
this.dmp.Match_Threshold = 0.9;
newText = this.element.value;
// Find the start of the selection in the new text.
pattern1 = this.startPrefix + this.startSuffix;
cursorStartPoint = this.dmp.match_main( newText, pattern1, this.startOffset - this.padLength );
if ( null !== cursorStartPoint ) {
pattern2 = newText.substring( cursorStartPoint, cursorStartPoint + pattern1.length );
// Run a diff to get a framework of equivalent indicies.
diff = this.dmp.diff_main( pattern1, pattern2, false );
cursorStartPoint += this.dmp.diff_xIndex( diff, this.startPrefix.length );
}
cursorEndPoint = null;
if ( ! this.collapsed ) {
// Find the end of the selection in the new text.
pattern1 = this.endPrefix + this.endSuffix;
cursorEndPoint = this.dmp.match_main( newText, pattern1, this.endOffset - this.padLength );
if ( null !== cursorEndPoint ) {
pattern2 = newText.substring( cursorEndPoint, cursorEndPoint + pattern1.length );
// Run a diff to get a framework of equivalent indicies.
diff = this.dmp.diff_main( pattern1, pattern2, false );
cursorEndPoint += this.dmp.diff_xIndex( diff, this.endPrefix.length );
}
}
// Reset the dmp settings
this.dmp.Match_Distance = dmpSettings[0];
this.dmp.Match_Threshold = dmpSettings[1];
// Deal with loose ends
if ( null === cursorStartPoint && null !== cursorEndPoint ) {
// Lost the start point of the selection, but we have the end point.
// Collapse to end point.
cursorStartPoint = cursorEndPoint;
} else if ( null === cursorStartPoint && null === cursorEndPoint ) {
// Lost both start and end points.
// Jump to the offset of start.
cursorStartPoint = this.startOffset;
}
if ( null === cursorEndPoint ) {
// End not known, collapse to start.
cursorEndPoint = cursorStartPoint;
}
// Restore selection.
if ( "selectionStart" in this.element ) { // W3
this.element.selectionStart = cursorStartPoint;
this.element.selectionEnd = cursorEndPoint;
} else { // IE
// Walk up the tree looking for this textarea's document node.
doc = this.element;
while ( doc.parentNode ) {
doc = doc.parentNode;
}
if ( ! doc.selection || ! doc.selection.createRange ) {
// Not IE?
return;
}
// IE's TextRange.move functions treat '\r\n' as one character.
snippet = this.element.value.substring( 0, cursorStartPoint );
ieStartPoint = snippet.replace( /\r\n/g, "\n" ).length;
newRange = doc.body.createTextRange();
newRange.moveToElementText( this.element );
newRange.collapse( true );
newRange.moveStart( "character", ieStartPoint );
if ( ! this.collapsed ) {
snippet = this.element.value.substring( cursorStartPoint, cursorEndPoint );
var ieMidLength = snippet.replace( /\r\n/g, "\n" ).length;
newRange.moveEnd( "character", ieMidLength );
}
newRange.select();
}
// Restore scrollbar locations
if ( "scrollTop" in this ) {
this.element.scrollTop = this.scrollTop * this.element.scrollHeight;
this.element.scrollLeft = this.scrollLeft * this.element.scrollWidth;
}
};
module.exports = Cursor;
},{}],23:[function(require,module,exports){
diff_match_patch = require( "dmp" ).diff_match_patch;
jsondiff = require( "jsondiff" );
message = require( "./message" );
Simperium = require( "./simperium" );
},{"./message":25,"./simperium":26,"dmp":"0+/Abx","jsondiff":"oUUvvc"}],24:[function(require,module,exports){
(function() {
var Store, Binary, util;
if ( ! ( "localStorage" in window ) || null === window.localStorage === null ) {
module.exports = false;
return;
}
Store = require( "./store" );
Binary = require( "./binary" );
util = require( "util" );
function LStore( prefix ) {
this.prefix = prefix;
this.prefix_length = prefix.length;
Store.call( this );
};
util.inherits( LStore, Store );
function keys() {
var i, key, keys;
keys = [];
for ( i = 0; i < window.localStorage.length; i++ ) {
key = window.localStorage.key( i );
if ( 0 === key.indexOf( this.prefix ) ) {
keys.push( key.substr( this.prefix_length ) );
}
}
return keys;
}
LStore.prototype.keys = keys;
function get( key ) {
var value;
value = window.localStorage.getItem( this.prefix + key );
if ( null === value ) {
return;
}
try {
return JSON.parse( value );
} catch ( error ) {
this.delete( key );
return;
}
}
LStore.prototype.get = get;
function set( key, value ) {
var string, newValue, i;
if ( value && undefined !== typeof value.binary && Binary.hasBinary( value.binary ) ) {
newValue = {};
for ( i in value ) {
if ( ! value.hasOwnProperty( i ) ) {
continue;
}
if ( "binary" === i ) {
newValue.binary = Binary.mapBinary( function() { return true; }, value.binary );
} else {
newValue[i] = value[i];
}
}
string = JSON.stringify( newValue );
} else {
string = JSON.stringify( value );
}
window.localStorage.setItem( this.prefix + key, string );
// @todo - JSON.parse( window.localStorage.getItem( this.prefix + key ) ) and check that it equals value
this.emit( 'set', key, value );
}
LStore.prototype.set = set;
function deleteItem( key ) {
window.localStorage.removeItem( this.prefix + key );
this.emit( 'delete', key );
}
LStore.prototype.delete = deleteItem;
module.exports = LStore;
})();
},{"./binary":19,"./store":27,"util":12}],25:[function(require,module,exports){
/**
* Parse any message (stripped of its channel) that comes from Simperium:
* `message = Message.parse( string );`
*
* Create a Message object:
* `init = new Message.INIT( { clientid: "abc", token: "def", app_id: "ghi", name: "jkl", cmd: new Message.INDEX( { data: 1, limit: 200 } ) } );`
*
* Serialize a Message object for use on the wire:
* `init.toString()`
*/
var config = require( "../package.json" );
var uuid = require( "uuid" );
function Message( type ) {
this.type = type;
}
Message.types = {
auth : AUTH,
init : INIT,
i : INDEX,
e : ENTITY,
cv : CHANGE_VERSION,
c : CHANGES,
h : HEARTBEAT,
o : OPTIONS,
index : REMOTE_INDEX,
log : LOG
};
Message.parse = function( string ) {
var type;
var colon = string.indexOf( ":" );
if ( -1 === colon ) {
type = string;
string = '';
} else {
type = string.slice( 0, colon );
string = string.slice( colon + 1 );
}
if ( ! ( type in Message.types ) ) {
throw new Error( "Unknown message type" );
}
return new Message.types[type]( string );
};
Message.prototype.parse = function( args ) {
if ( "string" === typeof args ) {
if ( args ) {
try {
return JSON.parse( args );
} catch ( e ) {
return false;
}
}
}
return args;
}
Message.prototype.toString = function() {
return this.type + ":" + JSON.stringify( this );
}
/**
* Handles both forms:
*
* new AUTH( { username: "foo@example.com" } )
* auth:foo@example.com
*
* new AUTH( { msg: "Token invalid", code: 401 } )
* auth:{"msg":"Token invalid","code":401}
*/
function AUTH( args ) {
args = this.parse( args ) || {};
this.msg = args.msg || undefined;
this.code = args.code || undefined;
this.username = args.username || undefined;
}
AUTH.prototype = new Message( "auth" );
AUTH.prototype.parse = function( args ) {
if ( "string" === typeof args ) {
if ( -1 !== args.indexOf( "{" ) ) {
return Message.prototype.parse( args );
}
args = {
username: args,
};
}
return args || {};
};
AUTH.prototype.toString = function() {
if ( this.username ) {
return this.type + ":" + this.username;
}
return Message.prototype.toString.call( this );
};
/**
* Can pass cmd as a Message object or as a string
*
* new INIT( { ..., cmd: new INDEX( { data: 1, limit: 200 } ) } )
* init:{...,"cmd":"i:1:::200"}
*
* new INIT( { ..., cmd: "i:1:::200" } )
* init:{...,"cmd":"i:1:::200"}
*/
function INIT( args ) {
args = this.parse( args ) || {};
this.clientid = args.clientid || ( "sjs-" + config.build + "-" + uuid() );
this.api = args.api || "1.1";
this.token = args.token || "";
this.app_id = args.app_id || "";
this.name = args.name || "";
this.library = args.library || "simperium-js-air";
this.version = args.version || config.version;
this.build = args.build || undefined;
this.cmd = args.cmd || undefined; // ? args.cmd.toString() : undefined;
this.presence_session = args.presence_session || undefined;
this.presence_debounce = args.presence_debounce || undefined;
}
INIT.prototype = new Message( "init" );
INIT.prototype.toString = function() {
return this.type + ":" + JSON.stringify( this, function( key, value ) {
if ( "cmd" === key && value instanceof Message ) {
return value.toString();
}
return value;
} );
}
/**
* Handles both forms:
*
* new INDEX( { data: 1, limit: 100 } )
* i:1:::100
*
* new INDEX( { current: "abc", index: [ ... ] } )
* i:{"current":"abc","index":[...]}
*/
function INDEX( args ) {
args = this.parse( args ) || {};
this.data = args.data || undefined;
this.mark = args.mark || undefined;
this.since = args.since || undefined;
this.limit = args.limit || undefined;
this.current = args.current || undefined;
this.index = args.index || undefined;
}
INDEX.prototype = new Message( "i" );
INDEX.prototype.parse = function( args ) {
var pieces;
if ( "string" === typeof args ) {
if ( -1 !== args.indexOf( "{" ) ) {
return Message.prototype.parse( args );
}
pieces = args.split( ":" );
return {
data : pieces[0] || undefined,
mark : pieces[1] || undefined,
since : pieces[2] || undefined,
limit : pieces[3] || undefined
};
}
return args || {};
};
INDEX.prototype.toString = function() {
if ( this.current ) {
return this.type + ":" + JSON.stringify( this );
}
return this.type + ":" + [ this.data, this.mark, this.since, this.limit ].join( ":" );
};
/**
* data === undefined => entity request
* new ENTITY( { id: "abc", version: 1 } )
* e:abc.1
*
* data === null => 404 response
* new ENTITY( { id: "abc", version: 1, data: null } )
* e:abc.1
* ?
*
* data === {} => 200 response
* new ENTITY( { id: "abc", version: 1, data: { foo: "bar" } } )
* e:abc.1
* {"data":{"foo":"bar"}}
*/
function ENTITY( args ) {
args = this.parse( args ) || {};
this.id = args.id || undefined;
this.version = args.version || undefined;
this.data = null === args.data ? null : ( args.data || undefined );
}
ENTITY.prototype = new Message( "e" );
ENTITY.prototype.parse = function( args ) {
var newline;
var data;
var period;
var ret = {};
if ( "string" === typeof args ) {
newline = args.indexOf( "\n" );
if ( 0 < newline ) {
ret.id = args.slice( 0, newline );
data = args.slice( newline + 1 );
if ( "?" === data ) {
ret.data = null;
} else {
ret.data = JSON.parse( args.slice( newline + 1 ) );
}
} else {
ret.id = args;
}
period = ret.id.lastIndexOf( "." );
if ( 0 < period ) {
ret.version = parseInt( ret.id.slice( period + 1 ), 10 );
ret.id = ret.id.slice( 0, period );
}
return ret;
}
return args || {};
};
ENTITY.prototype.toString = function() {
var ret = this.id;
if ( undefined !== this.version ) {
ret += "." + this.version;
}
ret = this.type + ":" + ret;
if ( null === this.data ) {
ret = [ ret, "?" ];
} else if ( undefined === this.data ) {
ret = [ ret ];
} else {
ret = [ ret, JSON.stringify( this.data ) ];
}
return ret.join( "\n" );
};
/**
* version === null => error response
* new CHANGE_VERSION( { version: null } )
* cv:?
*
* version === "abc" => cv request
* new CHANGE_VERSION( { version: "abc" } )
* cv:abc
*/
function CHANGE_VERSION( args ) {
args = this.parse( args ) || {};
this.version = null === args.version ? args.version : ( args.version || undefined );
}
CHANGE_VERSION.prototype = new Message( "cv" );
CHANGE_VERSION.prototype.parse = function( args ) {
var version;
if ( "string" === typeof args ) {
if ( '?' === args ) {
version = null;
} else {
version = args;
}
return { version: version };
}
return args || {};
};
CHANGE_VERSION.prototype.toString = function() {
return this.type + ":" + ( null === this.version ? "?" : this.version );
};
/**
* Handles array of changes (as in response) and single change (as in request):
*
* new CHANGES( [ { ev: "abc", ... }, ... ] )
* c:[{"ev":"abc",...},...]
*
* new CHANGES( { ev: "abc", ... } )
* c:{"ev":"abc",...}
*/
function CHANGES( args ) {
args = this.parse( args );
if ( "[object Array]" === Object.prototype.toString.call( args ) ) {
this.changes = [];
args.forEach( function( change ) {
this.changes.push( new CHANGES( change ) );
}, this );
} else {
this.clientid = args.clientid || undefined;
this.cv = args.cv || undefined;
this.ev = args.ev || undefined;
this.sv = args.sv || undefined;
this.id = args.id || undefined;
this.o = args.o || undefined;
this.v = args.v || undefined;
this.ccid = args.ccid || undefined;
this.d = args.d || undefined;
this.ccids = args.ccids || undefined;
this.error = args.error || undefined;
}
}
CHANGES.prototype = new Message( "c" );
CHANGES.prototype.toString = function() {
if ( this.changes ) {
return this.type + ":" + JSON.stringify( this.changes );
}
return Message.prototype.toString.call( this );
}
/**
* hb = new HEARTBEAT( 3 )
* hb.beat === 3
* hb.toString() === "h:3"
*/
function HEARTBEAT( args ) {
this.beat = parseInt( args, 10 );
}
HEARTBEAT.prototype = new Message( "h" );
HEARTBEAT.prototype.toString = function() {
return this.type + ":" + this.beat;
}
function OPTIONS( args ) {
args = this.parse( args );
this.expose_namespace = args.expose_namespace || undefined;
this.schema = args.schema || undefined;
this.namespace = args.namespace || undefined;
this.presence = args.presence || undefined;
this.shared = args.shared || undefined;
this.binary_backend = args.binary_backend || undefined;
}
OPTIONS.prototype = new Message( "o" );
/**
* Handles both forms:
*
* new REMOTE_INDEX()
* index
*
* new REMOTE_INDEX( { current: "abc", index: [ ... ], pending: [] } )
* index:{"current":"abc","index":[...],"pending":[]}
*/
function REMOTE_INDEX( args ) {
args = this.parse( args ) || {};
this.current = args.current || undefined;
this.index = args.index || undefined;
this.pending = args.pending || undefined;
this.extra = args.extra || undefined;
}
REMOTE_INDEX.prototype = new Message( "index" );
REMOTE_INDEX.prototype.toString = function() {
if ( this.current === undefined && this.index === undefined ) {
return this.type;
}
return Message.prototype.toString.call( this );
}
/**
* Handles both forms:
*
* log = new LOG( 2 )
* log.level === 2
* log.toString() === "log:2"
*
* new LOG( { log: "foo" } )
* log:{"log":"foo"}
*/
function LOG( args ) {
this.level = parseInt( args, 10 );
if ( isNaN( this.level ) ) {
args = this.parse( args ) || {};
this.log = args.log || undefined;
this.level = undefined;
}
}
LOG.prototype = new Message( "log" );
LOG.prototype.toString = function() {
if ( undefined === this.level ) {
return Message.prototype.toString.call( this );
}
return this.type + ":" + this.level;
}
Message.AUTH = AUTH;
Message.INIT = INIT;
Message.INDEX = INDEX;
Message.ENTITY = ENTITY;
Message.CHANGE_VERSION = CHANGE_VERSION;
Message.CHANGES = CHANGES;
Message.HEARTBEAT = HEARTBEAT;
Message.OPTIONS = OPTIONS;
Message.REMOTE_INDEX = REMOTE_INDEX;
Message.LOG = LOG;
module.exports = Message;
},{"../package.json":18,"uuid":17}],26:[function(require,module,exports){
var util = require( "util" );
var events = require( "events" );
var jsondiff = require( "jsondiff" );
var Bucket = require( "./bucket" );
var Connection = require( "./connection" );
var Message = require( "./message" );
var Binary = require( "./binary" );
var format = util.format;
var bound_methods = [
"bucket",
"on",
"start",
"stop",
"send",
"synced",
];
function Simperium( app_id, options ) {
var key, connection_options;
this.app_id = app_id;
this.options = options || {};
events.EventEmitter.call( this );
// bound methods
bound_methods.forEach( function( bound_method ) {
this[bound_method] = this[bound_method].bind( this );
}, this );
this.buckets = {};
this.channels = 0;
this.logging = 0;
this.jsondiff = new jsondiff();
this.options["app_id"] = this.app_id;
if ( "sockjs" in this.options ) {
connection_options = this.options.sockjs;
} else {
connection_options = {};
}
if ( "path" in this.options ) {
connection_options.path = this.options.path;
} else {
connection_options.path = format( "sock/1/%s", this.app_id );
}
if ( "host" in this.options ) {
connection_options.host = this.options.host;
}
if ( "port" in this.options ) {
connection_options.port = parseInt( this.options.port, 10 );
}
if ( "update_delay" in this.options ) {
this.options.update_delay = parseInt( this.options.update_delay, 10 );
} else {
this.options.update_delay = 0;
}
if ( "page_delay" in this.options ) {
this.options.page_delay = parseInt( this.options.page_delay, 10 );
} else {
this.options.page_delay = 0;
}
this.connected = false;
this.authorized = false;
this.connection = new Connection( connection_options );
this.connection.
on( "open", this._on_open.bind( this ) ).
on( "error", this._on_error.bind( this ) ).
on( "message", this._on_message.bind( this ) ).
on( "close", this._on_close.bind( this ) );
}
util.inherits( Simperium, events.EventEmitter );
Simperium.prototype._log = function( log ) {
if ( this.connected ) {
if ( this.logging > 0 ) {
this.connection.send( format( "log:%j", { log: log } ) );
}
}
console.log( log );
};
Simperium.prototype.bucket = function( name, bucket_options ) {
var bucket, options, _this = this;
name = name.toLowerCase().trim();
bucket_options = bucket_options || {};
bucket_options.n = this.channels++;
options = this.jsondiff.deepCopy( this.options );
for ( key in bucket_options ) {
if ( bucket_options.hasOwnProperty( key ) ) {
options[key] = bucket_options[key];
}
}
bucket = new Bucket( name, options, this.jsondiff );
this.buckets[bucket_options.n] = bucket;
this.
on_event( "start", bucket.start ).
on_event( "open", bucket.on_open ).
on_event( "close", bucket.on_close ).
on_event( format( "message_%d", bucket_options.n ), bucket.on_data );
return bucket
.on( "log", function( message_format ) {
var args = Array.prototype.slice.call( arguments );
args[0] = format( "%s:%s", bucket.space, args[0] );
_this._log( format.apply( null, args ) );
} ).
on( "message", function( message, channel ) {
_this.send( format( "%d:%s", channel, message ) );
} );
};
Simperium.prototype.on_event = Simperium.prototype.on;
Simperium.prototype.on = function( bucket, event, callback ) {
this.buckets[bucket].on( event, callback );
};
Simperium.prototype.start = function() {
this.connection.start();
this.emit( "start" );
};
Simperium.prototype.stop = function() {
this.connection.stop();
};
Simperium.prototype.send = function( data ) {
this.connection.send( data );
};
Simperium.prototype.synced = function() {
var channel;
for ( channel in this.buckets ) {
if ( ! this.buckets.hasOwnProperty( channel ) ) {
continue;
}
if ( this.buckets[channel].pending().length > 0 ) {
return false;
}
}
return true;
};
Simperium.prototype._on_open = function() {
this._log( "simperium: connection opened" );
this.connected = true;
this.emit( "open" );
};
Simperium.prototype._on_close = function() {
this.connected = false;
this.emit( "close" );
this._log( "simperium: connection closed" );
};
Simperium.prototype._on_error = function( error ) {
this._log( "simperium: connection error: " + error.toString() );
};
Simperium.prototype._on_message = function( message, channel ) {
if ( message instanceof Message.LOG ) {
this._log( format( "simperium: got logging command: %s", message.level ) );
this.logging = message.level || 0;
return;
}
if ( null === channel ) {
return;
}
if ( ! ( channel in this.buckets ) ) {
return;
}
this.emit( format( "message_%d", channel ), message );
};
Simperium.Binary = Binary;
module.exports = Simperium;
},{"./binary":19,"./bucket":20,"./connection":21,"./message":25,"events":7,"jsondiff":"oUUvvc","util":12}],27:[function(require,module,exports){
var events = require( "events" );
var util = require( "util" );
function Store() {
this.data = {};
events.EventEmitter.call( this );
Object.defineProperty( this, "length", {
get : length.bind( this ),
} );
};
util.inherits( Store, events.EventEmitter );
function keys() {
return Object.keys( this.data );
}
Store.prototype.keys = keys;
function length() {
return this.keys().length;
}
Store.prototype.lengthFunc = length;
function get( key ) {
return this.data[key] || undefined;
}
Store.prototype.get = get;
function set( key, value ) {
this.data[key] = value;
this.emit( 'set', key, value );
}
Store.prototype.set = set;
function add( key, value ) {
if ( "undefined" !== typeof this.get( key ) ) {
return false;
}
this.set( key, value );
return true;
}
Store.prototype.add = add;
function deleteItem( key ) {
delete this.data[key];
this.emit( 'delete', key );
}
Store.prototype.delete = deleteItem;
function pipe( store ) {
this.on( 'set', function( key, value ) {
store.set( key, value );
} );
this.on( 'delete', function( key ) {
store.delete( key );
} );
}
Store.prototype.pipe = pipe;
function fillOnceFrom( store, filter ) {
var did = 0;
store.keys().forEach( function( key ) {
var value = store.get( key );
if ( filter ) {
value = filter( value );
if ( "undefined" === typeof value ) {
store.delete( key );
return;
}
}
did++;
this.set( key, value );
}, this );
return did;
}
Store.prototype.fillOnceFrom = fillOnceFrom;
module.exports = Store;
},{"events":7,"util":12}]},{},[23])
;
(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){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
throw TypeError('Uncaught, unspecified "error" event.');
}
return false;
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],2:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],3:[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) {
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');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],4:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],5:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require("/Users/fred/dev/simperium/presence-room/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":4,"/Users/fred/dev/simperium/presence-room/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":3,"inherits":2}],6:[function(require,module,exports){
Presence = require( './presence' );
},{"./presence":8}],7:[function(require,module,exports){
var events = require( "events" );
var util = require( "util" );
var Session = require( "./session" );
/*
* Events: leave
*/
function Person( id, data, sessions, is_me ) {
events.EventEmitter.call( this );
this.id = id;
this.data = data || {};
this.sessions = sessions || {};
this.is_me = !! is_me;
};
util.inherits( Person, events.EventEmitter );
Person.prototype.session = function( session_id, data, is_me ) {
this.sessions[session_id] = new Session( session_id, this.is, data, !! is_me );
};
Person.prototype.leave = function( data ) {
};
Person.prototype.quit = function() {
};
module.exports = Person;
},{"./session":10,"events":1,"util":5}],8:[function(require,module,exports){
var Room = require( "./room" );
function Presence( simperium ) {
this.simperium = simperium;
}
Presence.prototype.room = function( bucket_name, options ) {
var bucket, session_bucket;
bucket = this.simperium.bucket( bucket_name, options );
session_bucket = this.simperium.bucket( "__" + bucket_name + "__" );
return new Room( bucket, session_bucket );
};
module.exports = Presence;
},{"./room":9}],9:[function(require,module,exports){
var events = require( "events" );
var util = require( "util" );
var Person = require( "./person" );
/*
* Events: people, join, leave, update
*/
function Room( bucket, session_bucket ) {
events.EventEmitter.call( this );
this.bucket = bucket;
this.session_bucket = session_bucket;
this.is_session_ready = false;
this.session_bucket.on( "notify", this.onSessionChange.bind( this ) );
this.session_bucket.on( "ready", this.onSessionReady.bind( this ) );
this.session_bucket.start();
this.is_ready = false;
this.username = "";
this.namespace = "";
this.bucket.on( "auth", this.onAuth.bind( this ) );
this.bucket.on( "server_options", this.onServerOptions.bind( this ) );
this.bucket.on( "notify", this.onChange.bind( this ) );
this.bucket.on( "ready", this.onReady.bind( this ) );
this.people = {};
this.sessions = {};
this.start_buffer = [];
this.join_buffer = [];
[ "leave", "update" ].forEach( function( event ) {
this.on( event, function( id, person ) {
person.emit( event );
} );
}, this );
// username, clientid
this._me = [ null, this.bucket.clientid ];
}
util.inherits( Room, events.EventEmitter );
Room.prototype.join = function( data, session_data, callback ) {
var start_later;
if ( "function" === session_data ) {
session_data = undefined;
callback = session_data;
}
this.bucket.options.presence_session = session_data;
start_later = function() {
var join_later;
this.bucket.start();
join_later = function() {
this._join_now( data, callback );
}.bind( this );
if ( this.is_ready ) {
join_later();
} else {
this.join_buffer.push( join_later );
}
}.bind( this );
if ( this.is_session_ready ) {
start_later();
} else {
this.start_buffer.push( start_later );
}
};
Room.prototype._join_now = function( data, callback ) {
var event;
if ( this.people[this._me[0]] ) {
event = "update";
} else {
event = "join";
}
this.bucket.update( this._me[0], data );
// Let's just be optimistic. Need a flag in the Simperium library to notify on local changes to do this correctly.
if ( callback ) {
this.once( event, callback );
}
this.onChange( this._me[0], data );
};
Room.prototype.person = function( id, data ) {
if ( ! this.sessions[id] ) {
return false;
}
return new Person( id, data, this.sessions[id], this._me[0] === id );
};
Room.prototype.onAuth = function( username ) {
this.username = username;
if ( this.namespace ) {
this.setMe();
}
};
Room.prototype.onServerOptions = function( server_options ) {
this.namespace = server_options.namespace;
if ( this.username ) {
this.setMe();
}
};
Room.prototype.setMe = function() {
this._me[0] = this.namespace + "/" + this.username;
};
Room.prototype.onReady = function() {
this.is_ready = true;
this.emit( "people", Object.keys( this.people ).map( function( person_id ) {
return this.people[person_id];
}, this ) );
while ( this.join_buffer.length ) {
this.join_buffer.pop()();
}
};
Room.prototype.onChange = function( id, data ) {
var person, event;
if ( null === data ) {
person = this.people[id] || null;
delete this.people[id];
event = "leave";
} else {
if ( this.people[id] ) {
if ( deepEquals( data, this.people[id].data ) ) {
event = false;
} else {
event = "update";
}
this.people[id].data = data;
} else {
event = "join";
person = this.person( id, data );
if ( person ) {
this.people[id] = person;
} else {
return;
}
}
person = this.people[id];
}
if ( this.is_ready && event ) {
this.emit( event, id, person );
}
};
Room.prototype.onSessionChange = function( id, data ) {
var session_userid, session_id, event, now_sessions;
if ( null === data ) {
for ( session_userid in this.sessions ) {
if ( id === session_userid.split( '/' )[1] ) {
delete this.sessions[session_userid]
}
}
for ( person in this.people ) {
if ( id === person.split( '/' )[1] ) {
this.bucket.update( id, null );
}
}
return;
}
session_userid = data.userid + "/" + id;
this.sessions[session_userid] = data.sessions;
if ( ! this.people[session_userid] ) {
return;
}
now_sessions = [];
for ( session_id in data.sessions ) {
now_sessions.push( session_id );
if ( session_id in this.people[session_userid].sessions ) {
if ( deepEquals( data.sessions[session_id], this.people[session_userid].sessions[session_id] ) ) {
continue;
}
event = "session change";
} else {
event = "session add";
}
this.people[session_userid].session( session_id, data.sessions[session_id], session_id == this._me[1] );
this.people[session_userid].emit( event, this.people[session_userid].sessions[session_id] );
}
Object.keys( this.people[session_userid].sessions ).forEach( function( session_id ) {
var session;
if ( -1 != now_sessions.indexOf( session_id ) ) {
return;
}
session = this.people[session_userid].sessions[session_id];
delete this.people[session_userid].sessions[session_id];
this.people[session_userid].emit( "session remove", session );
}, this );
};
Room.prototype.onSessionReady = function() {
this.is_session_ready = true;
while ( this.start_buffer.length ) {
this.start_buffer.pop()();
}
};
function deepEquals( a, b ) {
var keys, i, key;
if ( typeof a !== typeof b ) {
return false;
}
if ( null === a && null === b ) {
return true;
} else if ( null === a || null === b ) {
return false;
}
if ( -1 !== [ "string", "number", "boolean" ].indexOf( typeof a ) ) {
return a === b;
}
if ( "object" !== typeof a ) {
return false;
}
keys = Object.keys( a ).concat( Object.keys( b ) );
for ( i in keys ) {
key = keys[i];
if ( ! ( key in a ) || ! ( key in b ) ) {
return false;
}
if ( ! deepEquals( a[key], b[key] ) ) {
return false;
}
}
return true;
}
module.exports = Room;
},{"./person":7,"events":1,"util":5}],10:[function(require,module,exports){
function Session( id, username, session, is_me ) {
this.id = id;
this.username = username;
this.is_me = !! is_me;
this.session = session;
};
module.exports = Session;
},{}]},{},[6])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment