<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

// An Algorithm for Automatically Fitting Digitized Curves
// by Philip J. Schneider
// from "Graphics Gems", Academic Press, 1990
var PathFitter = Base.extend({
	initialize: function(path, error) {
		this.points = [];
		var segments = path._segments,
			prev;
		for (var i = 0, l = segments.length; i < l; i++) {
			var point = segments[i].point.clone();
			if (!prev || !prev.equals(point)) {
				this.points[i] = point;
				prev = point;
			}
		}
		this.error = error;
		this.iterationError = error * error;
	},

	fit: function() {
		this.segments = [new Segment(this.points[0])];
		this.fitCubic(0, this.points.length - 1,
				// Left Tangent
				this.points[1].subtract(this.points[0]).normalize(),
				// Right Tangent
				this.points[this.points.length - 2].subtract(
					this.points[this.points.length - 1]).normalize());
		return this.segments;
	},

	// Fit a Bezier curve to a (sub)set of digitized points
	fitCubic: function(first, last, tan1, tan2) {
		//	Use heuristic if region only has two points in it
		if (last - first == 1) {
			var pt1 = this.points[first],
				pt2 = this.points[last],
				dist = pt1.getDistance(pt2) / 3;
			this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
					pt2.add(tan2.normalize(dist)), pt2]);
			return;
		}
		// Parameterize points, and attempt to fit curve
		var uPrime = this.chordLengthParameterize(first, last),
			prevMaxError = this.iterationError,
			error,
			split;
		// Try 4 iterations
		for (var i = 0; i < 4; i++) {
			var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
			//	Find max deviation of points to fitted curve
			var max = this.findMaxError(first, last, curve, uPrime);
			if (max.error < this.error) {
				this.addCurve(curve);
				return;
			}
			split = max.index;
			// If error not too large, try some reparameterization and iteration
			if (max.error >= this.iterationError || max.error >= prevMaxError)
				break;
			uPrime = this.reparameterize(first, last, uPrime, curve);
			prevMaxError = max.error;
		}
		// Fitting failed -- split at max error point and fit recursively
		var V1 = this.points[split - 1].subtract(this.points[split]),
			V2 = this.points[split].subtract(this.points[split + 1]),
			tanCenter = V1.add(V2).divide(2).normalize();
		this.fitCubic(first, split, tan1, tanCenter);
		this.fitCubic(split, last, tanCenter.negate(), tan2);
	},

	addCurve: function(curve) {
		var prev = this.segments[this.segments.length - 1];
		prev.setHandleOut(curve[1].subtract(curve[0]));
		this.segments.push(
				new Segment(curve[3], curve[2].subtract(curve[3])));
	},

	// Use least-squares method to find Bezier control points for region.
	generateBezier: function(first, last, uPrime, tan1, tan2) {
		var nPts = last - first + 1,
			pt1 = this.points[first],
			pt2 = this.points[last];

		// Create the C and X matrices
		var C = [[0, 0], [0, 0]],
			X = [0, 0];

		for (var i = 0; i < nPts; i++) {
			var u = uPrime[i],
				t = 1 - u,
				b = 3 * u * t,
				b0 = t * t * t,
				b1 = b * t,
				b2 = b * u,
				b3 = u * u * u,
				a1 = tan1.normalize(b1),
				a2 = tan2.normalize(b2),
				tmp = this.points[first + i]
					.subtract(pt1.multiply(b0 + b1))
					.subtract(pt2.multiply(b2 + b3));
			C[0][0] += a1.dot(a1);
			C[0][1] += a1.dot(a2);
			// C[1][0] += a1.dot(a2);
			C[1][0] = C[0][1];
			C[1][1] += a2.dot(a2);
			X[0] += a1.dot(tmp);
			X[1] += a2.dot(tmp);
		}

		// Compute the determinants of C and X
		var det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
			alpha_l, alpha_r;
		if (Math.abs(det_C0_C1) > Numerical.TOLERANCE) {
			// Kramer's rule
			var det_C0_X  = C[0][0] * X[1]    - C[1][0] * X[0],
				det_X_C1  = X[0]    * C[1][1] - X[1]    * C[0][1];
			// Derive alpha values
			alpha_l = det_X_C1 / det_C0_C1;
			alpha_r = det_C0_X / det_C0_C1;
		} else {
			// Matrix is under-determined, try assuming alpha_l == alpha_r
			var c0 = C[0][0] + C[0][1],
				c1 = C[1][0] + C[1][1];
			if (Math.abs(c0) > Numerical.TOLERANCE) {
				alpha_l = alpha_r = X[0] / c0;
			} else if (Math.abs(c0) > Numerical.TOLERANCE) {
				alpha_l = alpha_r = X[1] / c1;
			} else {
				// Handle below
				alpha_l = alpha_r = 0.;
			}
		}

		// If alpha negative, use the Wu/Barsky heuristic (see text)
		// (if alpha is 0, you get coincident control points that lead to
		// divide by zero in any subsequent NewtonRaphsonRootFind() call.
		var segLength = pt2.getDistance(pt1),
			epsilon = Numerical.TOLERANCE * segLength;
		if (alpha_l < epsilon || alpha_r < epsilon) {
			// fall back on standard (probably inaccurate) formula,
			// and subdivide further if needed.
			alpha_l = alpha_r = segLength / 3;
		}

		// First and last control points of the Bezier curve are
		// positioned exactly at the first and last data points
		// Control points 1 and 2 are positioned an alpha distance out
		// on the tangent vectors, left and right, respectively
		return [pt1, pt1.add(tan1.normalize(alpha_l)),
				pt2.add(tan2.normalize(alpha_r)), pt2];
	},

	// Given set of points and their parameterization, try to find
	// a better parameterization.
	reparameterize: function(first, last, u, curve) {
		var uPrime = [];
		for (var i = first; i <= last; i++) {
			uPrime[i - first] = this.findRoot(curve, this.points[i],
					u[i - first]);
		}
		return uPrime;
	},

	// Use Newton-Raphson iteration to find better root.
	findRoot: function(curve, point, u) {
		var curve1 = [],
			curve2 = [];
		// Generate control vertices for Q'
		for (var i = 0; i <= 2; i++) {
			curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
		}
		// Generate control vertices for Q''
		for (var i = 0; i <= 1; i++) {
			curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
		}
		// Compute Q(u), Q'(u) and Q''(u)
		var pt = this.evaluate(3, curve, u),
		 	pt1 = this.evaluate(2, curve1, u),
		 	pt2 = this.evaluate(1, curve2, u),
		 	diff = pt.subtract(point),
			df = pt1.dot(pt1) + diff.dot(pt2);
		// Compute f(u) / f'(u)
		if (Math.abs(df) < Numerical.TOLERANCE)
			return u;
		// u = u - f(u) / f'(u)
		return u - V.dot(Q1_u) / df;
	},

	// Evaluate a Bezier curve at a particular parameter value
	evaluate: function(degree, curve, t) {
		// Copy array
		var tmp = curve.slice();
		// Triangle computation
		for (var i = 1; i <= degree; i++) {
			for (var j = 0; j <= degree - i; j++) {
				tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
			}
		}
		return tmp[0];
	},

	// Assign parameter values to digitized points
	// using relative distances between points.
	chordLengthParameterize: function(first, last) {
		var u = [0];
		for (var i = first + 1; i <= last; i++) {
			u[i - first] = u[i - first - 1]
					+ this.points[i].getDistance(this.points[i - 1]);
		}
		for (var i = first + 1; i <= last; i++) {
			u[i - first] = u[i - first] / u[last - first];
		}
		return u;
	},

	// Find the maximum squared distance of digitized points to fitted curve.
	findMaxError: function(first, last, curve, u) {
		var index = Math.floor((last - first + 1) / 2),
			maxDist = 0;
		for (var i = first + 1; i < last; i++) {
			var P = this.evaluate(3, curve, u[i - first]);
			var v = P.subtract(this.points[i]);
			var dist = v.x * v.x + v.y * v.y; // squared
			if (dist >= maxDist) {
				maxDist = dist;
				index = i;
			}
		}
		return {
			error: maxDist,
			index: index
		};
	}
});
<commit_msg>Further clean ups.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

// An Algorithm for Automatically Fitting Digitized Curves
// by Philip J. Schneider
// from "Graphics Gems", Academic Press, 1990
var PathFitter = Base.extend({
	initialize: function(path, error) {
		this.points = [];
		var segments = path._segments,
			prev;
		for (var i = 0, l = segments.length; i < l; i++) {
			var point = segments[i].point.clone();
			if (!prev || !prev.equals(point)) {
				this.points[i] = point;
				prev = point;
			}
		}
		this.error = error;
		this.iterationError = error * error;
	},

	fit: function() {
		this.segments = [new Segment(this.points[0])];
		this.fitCubic(0, this.points.length - 1,
				// Left Tangent
				this.points[1].subtract(this.points[0]).normalize(),
				// Right Tangent
				this.points[this.points.length - 2].subtract(
					this.points[this.points.length - 1]).normalize());
		return this.segments;
	},

	// Fit a Bezier curve to a (sub)set of digitized points
	fitCubic: function(first, last, tan1, tan2) {
		//	Use heuristic if region only has two points in it
		if (last - first == 1) {
			var pt1 = this.points[first],
				pt2 = this.points[last],
				dist = pt1.getDistance(pt2) / 3;
			this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
					pt2.add(tan2.normalize(dist)), pt2]);
			return;
		}
		// Parameterize points, and attempt to fit curve
		var uPrime = this.chordLengthParameterize(first, last),
			prevMaxError = this.iterationError,
			error,
			split;
		// Try 4 iterations
		for (var i = 0; i < 4; i++) {
			var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
			//	Find max deviation of points to fitted curve
			var max = this.findMaxError(first, last, curve, uPrime);
			if (max.error < this.error) {
				this.addCurve(curve);
				return;
			}
			split = max.index;
			// If error not too large, try some reparameterization and iteration
			if (max.error >= this.iterationError || max.error >= prevMaxError)
				break;
			uPrime = this.reparameterize(first, last, uPrime, curve);
			prevMaxError = max.error;
		}
		// Fitting failed -- split at max error point and fit recursively
		var V1 = this.points[split - 1].subtract(this.points[split]),
			V2 = this.points[split].subtract(this.points[split + 1]),
			tanCenter = V1.add(V2).divide(2).normalize();
		this.fitCubic(first, split, tan1, tanCenter);
		this.fitCubic(split, last, tanCenter.negate(), tan2);
	},

	addCurve: function(curve) {
		var prev = this.segments[this.segments.length - 1];
		prev.setHandleOut(curve[1].subtract(curve[0]));
		this.segments.push(
				new Segment(curve[3], curve[2].subtract(curve[3])));
	},

	// Use least-squares method to find Bezier control points for region.
	generateBezier: function(first, last, uPrime, tan1, tan2) {
		var epsilon = Numerical.TOLERANCE,
			pt1 = this.points[first],
			pt2 = this.points[last],
			// Create the C and X matrices
		 	C = [[0, 0], [0, 0]],
			X = [0, 0];

		for (var i = 0, l = last - first + 1; i < l; i++) {
			var u = uPrime[i],
				t = 1 - u,
				b = 3 * u * t,
				b0 = t * t * t,
				b1 = b * t,
				b2 = b * u,
				b3 = u * u * u,
				a1 = tan1.normalize(b1),
				a2 = tan2.normalize(b2),
				tmp = this.points[first + i]
					.subtract(pt1.multiply(b0 + b1))
					.subtract(pt2.multiply(b2 + b3));
			C[0][0] += a1.dot(a1);
			C[0][1] += a1.dot(a2);
			// C[1][0] += a1.dot(a2);
			C[1][0] = C[0][1];
			C[1][1] += a2.dot(a2);
			X[0] += a1.dot(tmp);
			X[1] += a2.dot(tmp);
		}

		// Compute the determinants of C and X
		var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
			alpha1, alpha2;
		if (Math.abs(detC0C1) > epsilon) {
			// Kramer's rule
			var detC0X  = C[0][0] * X[1]    - C[1][0] * X[0],
				detXC1  = X[0]    * C[1][1] - X[1]    * C[0][1];
			// Derive alpha values
			alpha1 = detXC1 / detC0C1;
			alpha2 = detC0X / detC0C1;
		} else {
			// Matrix is under-determined, try assuming alpha1 == alpha2
			var c0 = C[0][0] + C[0][1],
				c1 = C[1][0] + C[1][1];
			if (Math.abs(c0) > epsilon) {
				alpha1 = alpha2 = X[0] / c0;
			} else if (Math.abs(c0) > epsilon) {
				alpha1 = alpha2 = X[1] / c1;
			} else {
				// Handle below
				alpha1 = alpha2 = 0.;
			}
		}

		// If alpha negative, use the Wu/Barsky heuristic (see text)
		// (if alpha is 0, you get coincident control points that lead to
		// divide by zero in any subsequent NewtonRaphsonRootFind() call.
		var segLength = pt2.getDistance(pt1);
		epsilon *= segLength;
		if (alpha1 < epsilon || alpha2 < epsilon) {
			// fall back on standard (probably inaccurate) formula,
			// and subdivide further if needed.
			alpha1 = alpha2 = segLength / 3;
		}

		// First and last control points of the Bezier curve are
		// positioned exactly at the first and last data points
		// Control points 1 and 2 are positioned an alpha distance out
		// on the tangent vectors, left and right, respectively
		return [pt1, pt1.add(tan1.normalize(alpha1)),
				pt2.add(tan2.normalize(alpha2)), pt2];
	},

	// Given set of points and their parameterization, try to find
	// a better parameterization.
	reparameterize: function(first, last, u, curve) {
		var uPrime = [];
		for (var i = first; i <= last; i++) {
			uPrime[i - first] = this.findRoot(curve, this.points[i],
					u[i - first]);
		}
		return uPrime;
	},

	// Use Newton-Raphson iteration to find better root.
	findRoot: function(curve, point, u) {
		var curve1 = [],
			curve2 = [];
		// Generate control vertices for Q'
		for (var i = 0; i <= 2; i++) {
			curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
		}
		// Generate control vertices for Q''
		for (var i = 0; i <= 1; i++) {
			curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
		}
		// Compute Q(u), Q'(u) and Q''(u)
		var pt = this.evaluate(3, curve, u),
		 	pt1 = this.evaluate(2, curve1, u),
		 	pt2 = this.evaluate(1, curve2, u),
		 	diff = pt.subtract(point),
			df = pt1.dot(pt1) + diff.dot(pt2);
		// Compute f(u) / f'(u)
		if (Math.abs(df) < Numerical.TOLERANCE)
			return u;
		// u = u - f(u) / f'(u)
		return u - V.dot(Q1_u) / df;
	},

	// Evaluate a Bezier curve at a particular parameter value
	evaluate: function(degree, curve, t) {
		// Copy array
		var tmp = curve.slice();
		// Triangle computation
		for (var i = 1; i <= degree; i++) {
			for (var j = 0; j <= degree - i; j++) {
				tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
			}
		}
		return tmp[0];
	},

	// Assign parameter values to digitized points
	// using relative distances between points.
	chordLengthParameterize: function(first, last) {
		var u = [0];
		for (var i = first + 1; i <= last; i++) {
			u[i - first] = u[i - first - 1]
					+ this.points[i].getDistance(this.points[i - 1]);
		}
		for (var i = first + 1; i <= last; i++) {
			u[i - first] = u[i - first] / u[last - first];
		}
		return u;
	},

	// Find the maximum squared distance of digitized points to fitted curve.
	findMaxError: function(first, last, curve, u) {
		var index = Math.floor((last - first + 1) / 2),
			maxDist = 0;
		for (var i = first + 1; i < last; i++) {
			var P = this.evaluate(3, curve, u[i - first]);
			var v = P.subtract(this.points[i]);
			var dist = v.x * v.x + v.y * v.y; // squared
			if (dist >= maxDist) {
				maxDist = dist;
				index = i;
			}
		}
		return {
			error: maxDist,
			index: index
		};
	}
});
<|endoftext|>


<commit_before>/*global phonegapStorage_msgs: false */
'use strict';

/**
 * error messages
 */
angular.module('phonegapStorage', []).constant('phonegapStorage_msgs', {
    'errors.phonegapStorage.notSupported': 'window.openDatabase is not supported on this device'
});

/**
 * Angular Phonegap Storage
 */
angular.module('phonegapStorage').factory('phonegapStorage', [
    '$q',
    '$rootScope',
    '$window',
    'phonegapStorage_msgs',
    function ($q, $rootScope, $window, phonegapStorage_msgs) {
        var storage = {};

        var extendSQLTransaction = function (tx, queryFn) {
            var exTx = {};
            angular.extend(exTx, tx);

            exTx.executeSql = function (queryString) {
                var deferred = $q.defer();
                //
                tx.executeSql(queryString, [], function (tx, results) {
                    $rootScope.$apply( deferred.resolve({tx: tx, resultSet: results}) );
                }, function (err) {
                    $rootScope.$apply( deferred.reject(err) );
                });

                return deferred.promise;
            };

            return queryFn(exTx);
        };

        var extendDatabase = function (db) {
            var exDb = {};
            angular.extend(exDb, db);

            exDb.transaction = function (query) {
                var deferred = $q.defer();
                //
                db.transaction(function (tx) {
                    return extendSQLTransaction(tx, query);
                }, function (err) {
                    $rootScope.$apply( deferred.reject(err) );
                }, function () {
                    $rootScope.$apply( deferred.resolve() );
                });

                return deferred.promise;
            };

            exDb.changeVersion = db.changeVersion;

            return exDb;
        };

        storage.openDatabase = function (database_name, database_version, database_displayname, database_size) {
            var deferred = $q.defer();

            if ($window && $window.openDatabase) {
                //
                var db = $window.openDatabase(database_name, database_version, database_displayname, database_size);
                return extendDatabase(db);
            } else {
                // storage api is not defined or permitted.
                $rootScope.$broadcast('error', phonegapStorage_msgs['errors.phonegapStorage.notSupported']);
                $rootScope.$apply( function () {
                    deferred.reject(phonegapStorage_msgs['errors.phonegapStorage.notSupported']);
                });
            }

            return deferred.promise;
        };

        return storage;
    }]);<commit_msg>fix a bug.<commit_after>/*global phonegapStorage_msgs: false */
'use strict';

/**
 * error messages
 */
angular.module('phonegapStorage', []).constant('phonegapStorage_msgs', {
    'errors.phonegapStorage.notSupported': 'window.openDatabase is not supported on this device'
});

/**
 * Angular Phonegap Storage
 */
angular.module('phonegapStorage').factory('phonegapStorage', [
    '$q',
    '$rootScope',
    '$window',
    'phonegapStorage_msgs',
    function ($q, $rootScope, $window, phonegapStorage_msgs) {
        var storage = {};

        var extendSQLTransaction = function (tx, queryFn) {
            var exTx = {};
            angular.extend(exTx, tx);

            exTx.executeSql = function (queryString) {
                var deferred = $q.defer();
                //
                tx.executeSql(queryString, [], function (tx, results) {
                    $rootScope.$apply( deferred.resolve({tx: tx, resultSet: results}) );
                }, function (err) {
                    $rootScope.$apply( deferred.reject(err) );
                });

                return deferred.promise;
            };

            return queryFn(exTx);
        };

        var extendDatabase = function (db) {
            var exDb = {};
            angular.extend(exDb, db);

            exDb.transaction = function (fn) {
                var deferred = $q.defer();
                //
                db.transaction(function (tx) {
                    extendSQLTransaction(tx, fn);
                }, function (err) {
                    // error callback
                    $rootScope.$apply( deferred.reject(err) );
                }, function () {
                    // success callback
                    $rootScope.$apply( deferred.resolve() );
                });

                return deferred.promise;
            };

            exDb.changeVersion = db.changeVersion;

            return exDb;
        };

        storage.openDatabase = function (database_name, database_version, database_displayname, database_size) {
            var deferred = $q.defer();

            if ($window && $window.openDatabase) {
                //
                var db = $window.openDatabase(database_name, database_version, database_displayname, database_size);
                return extendDatabase(db);
            } else {
                // storage api is not defined or permitted.
                $rootScope.$broadcast('error', phonegapStorage_msgs['errors.phonegapStorage.notSupported']);
                $rootScope.$apply( function () {
                    deferred.reject(phonegapStorage_msgs['errors.phonegapStorage.notSupported']);
                });
            }

            return deferred.promise;
        };

        return storage;
    }]);<|endoftext|>


<commit_before>/*!
 * php-unserialize-js JavaScript Library
 * https://github.com/bd808/php-unserialize-js
 *
 * Copyright 2013 Bryan Davis and contributors
 * Released under the MIT license
 * http://www.opensource.org/licenses/MIT
 */

/**
 * Parse php serialized data into js objects.
 *
 * @param {String} phpstr Php serialized string to parse
 * @return {mixed} Parsed result
 */
function phpUnserialize (phpstr) {
  var idx = 0
    , rstack = []
    , ridx = 0

    , readLength = function () {
        var del = phpstr.indexOf(':', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 2;
        return parseInt(val);
      } //end readLength

    , readInt = function () {
        var del = phpstr.indexOf(';', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 1;
        return parseInt(val);
      } //end readInt

    , parseAsInt = function () {
        var val = readInt();
        return val;
      } //end parseAsInt

    , parseAsFloat = function () {
        var del = phpstr.indexOf(';', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 1;
        val = parseFloat(val);
        return val;
      } //end parseAsFloat

    , parseAsBoolean = function () {
        var del = phpstr.indexOf(';', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 1;
        val = ("1" === val)? true: false;
        return val;
      } //end parseAsBoolean

    , readString = function () {
        var len = readLength()
          , utfLen = 0
          , bytes = 0
          , ch
          , val;
        while (bytes < len) {
          ch = phpstr.charCodeAt(idx + utfLen++);
          if (ch <= 0x007F) {
            bytes++;
          } else if (ch > 0x07FF) {
            bytes += 3;
          } else {
            bytes += 2;
          }
        }
        val = phpstr.substring(idx, idx + utfLen);
        idx += utfLen + 2;
        return val;
      } //end readString

    , parseAsString = function () {
        var val = readString();
        return val;
      } //end parseAsString

    , parseAsArray = function () {
        var len = readLength()
          , resultArray = []
          , resultHash = {}
          , keep = resultArray
          , lref = ridx++
          , key
          , val;

        rstack[lref] = keep;
        for (var i = 0; i < len; i++) {
          key = parseNext();
          val = parseNext();
          if (keep === resultArray && parseInt(key) == i) {
            // store in array version
            resultArray.push(val);
          } else {
            if (keep !== resultHash) {
              // found first non-sequential numeric key
              // convert existing data to hash
              for (var j = 0, alen = resultArray.length; j < alen; j++) {
                resultHash[j] = resultArray[j];
              }
              keep = resultHash;
              rstack[lref] = keep;
            }
            resultHash[key] = val;
          } //end if
        } //end for

        idx++;
        return keep;
      } //end parseAsArray

    , fixPropertyName = function (parsedName, baseClassName) {
        // <NUL>*<NUL>property
        // <NUL>class<NUL>property
        if ("\u0000" === parsedName.charAt(0)) {
          var pos = parsedName.indexOf("\u0000", 1);
          if (pos > 0) {
            var class_name = parsedName.substring(1, pos)
              , prop_name  = parsedName.substr(pos + 1)
            ;
            if ("*" === class_name) {
              // protected
              return prop_name;
            }
            else if (baseClassName === class_name) {
              // own private
              return prop_name;
            }
            else {
              // private of a descendant
              return class_name + "::" + prop_name;
              /* On the one hand, we need to prefix property name with
               * class name, because parent and child classes both may
               * have private property with same name. We don't want
               * just to overwrite it and lose something.
               *
               * On the other hand, property name can be "foo::bar"
               *
               *     $obj = new stdClass();
               *     $obj->{"foo::bar"} = 42;
               *     // any user-defined class can do this by default
               *
               * and such property also can overwrite something.
               *
               * So, we can to lose something in any way.
               */
            };
          };
        }
        // property
        else {
          return parsedName;
        };
      }

    , parseAsObject = function () {
        var len = readLength()
          , obj = {}
          , lref = ridx++
          , clazzname = phpstr.substring(idx, idx + len)
          , key
          , val;

        rstack[lref] = obj;
        idx += len + 2;
        len = readLength();
        for (var i = 0; i < len; i++) {
          key = parseNext();
          // private members start with "\u0000CLASSNAME\u0000"
          //   any class name can be catched for private properties of descendant classes
          // we will replace it with "CLASSNAME::"
          // protected members start with "\u0000*\u0000"
          // we will strip these prefixes
          key = fixPropertyName(key, clazzname);
          val = parseNext();
          obj[key] = val;
        }
        idx++;
        return obj;
      } //end parseAsObject

    , parseAsRef = function () {
        var ref = readInt();
        // php's ref counter is 1-based; our stack is 0-based.
        return rstack[ref - 1];
      } //end parseAsRef

    , parseAsNull = function () {
        var val = null;
        return val;
      } //end parseAsNull

    , readType = function () {
        var type = phpstr.charAt(idx);
        idx += 2;
        return type;
      } //end readType

    , parseNext = function () {
        var type = readType();
        switch (type) {
          case 'i': return parseAsInt();
          case 'd': return parseAsFloat();
          case 'b': return parseAsBoolean();
          case 's': return parseAsString();
          case 'a': return parseAsArray();
          case 'O': return parseAsObject();
          case 'r': return parseAsRef();
          case 'R': return parseAsRef();
          case 'N': return parseAsNull();
          default:
            throw {
              name: "Parse Error",
              message: "Unknown type '" + type + "' at postion " + (idx - 2)
            }
        } //end switch
    }; //end parseNext

    return parseNext();
} //end phpUnserialize
<commit_msg>Keys are not a values, which can be referenced<commit_after>/*!
 * php-unserialize-js JavaScript Library
 * https://github.com/bd808/php-unserialize-js
 *
 * Copyright 2013 Bryan Davis and contributors
 * Released under the MIT license
 * http://www.opensource.org/licenses/MIT
 */

/**
 * Parse php serialized data into js objects.
 *
 * @param {String} phpstr Php serialized string to parse
 * @return {mixed} Parsed result
 */
function phpUnserialize (phpstr) {
  var idx = 0
    , rstack = []
    , ridx = 0

    , readLength = function () {
        var del = phpstr.indexOf(':', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 2;
        return parseInt(val);
      } //end readLength

    , readInt = function () {
        var del = phpstr.indexOf(';', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 1;
        return parseInt(val);
      } //end readInt

    , parseAsInt = function () {
        var val = readInt();
        return val;
      } //end parseAsInt

    , parseAsFloat = function () {
        var del = phpstr.indexOf(';', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 1;
        val = parseFloat(val);
        return val;
      } //end parseAsFloat

    , parseAsBoolean = function () {
        var del = phpstr.indexOf(';', idx)
          , val = phpstr.substring(idx, del);
        idx = del + 1;
        val = ("1" === val)? true: false;
        return val;
      } //end parseAsBoolean

    , readString = function () {
        var len = readLength()
          , utfLen = 0
          , bytes = 0
          , ch
          , val;
        while (bytes < len) {
          ch = phpstr.charCodeAt(idx + utfLen++);
          if (ch <= 0x007F) {
            bytes++;
          } else if (ch > 0x07FF) {
            bytes += 3;
          } else {
            bytes += 2;
          }
        }
        val = phpstr.substring(idx, idx + utfLen);
        idx += utfLen + 2;
        return val;
      } //end readString

    , parseAsString = function () {
        var val = readString();
        return val;
      } //end parseAsString

    , readKey = function () {
        var type = readType();
        switch (type) {
          case 'i': return readInt();
          case 's': return readString();
          default:
            throw {
              name: "Parse Error",
              message: "Unknown key type '" + type + "' at postion " + (idx - 2)
            }
        } //end switch
      }

    , parseAsArray = function () {
        var len = readLength()
          , resultArray = []
          , resultHash = {}
          , keep = resultArray
          , lref = ridx++
          , key
          , val;

        rstack[lref] = keep;
        for (var i = 0; i < len; i++) {
          key = readKey();
          val = parseNext();
          if (keep === resultArray && parseInt(key) == i) {
            // store in array version
            resultArray.push(val);
          } else {
            if (keep !== resultHash) {
              // found first non-sequential numeric key
              // convert existing data to hash
              for (var j = 0, alen = resultArray.length; j < alen; j++) {
                resultHash[j] = resultArray[j];
              }
              keep = resultHash;
              rstack[lref] = keep;
            }
            resultHash[key] = val;
          } //end if
        } //end for

        idx++;
        return keep;
      } //end parseAsArray

    , fixPropertyName = function (parsedName, baseClassName) {
        // <NUL>*<NUL>property
        // <NUL>class<NUL>property
        if ("\u0000" === parsedName.charAt(0)) {
          var pos = parsedName.indexOf("\u0000", 1);
          if (pos > 0) {
            var class_name = parsedName.substring(1, pos)
              , prop_name  = parsedName.substr(pos + 1)
            ;
            if ("*" === class_name) {
              // protected
              return prop_name;
            }
            else if (baseClassName === class_name) {
              // own private
              return prop_name;
            }
            else {
              // private of a descendant
              return class_name + "::" + prop_name;
              /* On the one hand, we need to prefix property name with
               * class name, because parent and child classes both may
               * have private property with same name. We don't want
               * just to overwrite it and lose something.
               *
               * On the other hand, property name can be "foo::bar"
               *
               *     $obj = new stdClass();
               *     $obj->{"foo::bar"} = 42;
               *     // any user-defined class can do this by default
               *
               * and such property also can overwrite something.
               *
               * So, we can to lose something in any way.
               */
            };
          };
        }
        // property
        else {
          return parsedName;
        };
      }

    , parseAsObject = function () {
        var len = readLength()
          , obj = {}
          , lref = ridx++
          , clazzname = phpstr.substring(idx, idx + len)
          , key
          , val;

        rstack[lref] = obj;
        idx += len + 2;
        len = readLength();
        for (var i = 0; i < len; i++) {
          key = readKey();
          // private members start with "\u0000CLASSNAME\u0000"
          //   any class name can be catched for private properties of descendant classes
          // we will replace it with "CLASSNAME::"
          // protected members start with "\u0000*\u0000"
          // we will strip these prefixes
          key = fixPropertyName(key, clazzname);
          val = parseNext();
          obj[key] = val;
        }
        idx++;
        return obj;
      } //end parseAsObject

    , parseAsRef = function () {
        var ref = readInt();
        // php's ref counter is 1-based; our stack is 0-based.
        return rstack[ref - 1];
      } //end parseAsRef

    , parseAsNull = function () {
        var val = null;
        return val;
      } //end parseAsNull

    , readType = function () {
        var type = phpstr.charAt(idx);
        idx += 2;
        return type;
      } //end readType

    , parseNext = function () {
        var type = readType();
        switch (type) {
          case 'i': return parseAsInt();
          case 'd': return parseAsFloat();
          case 'b': return parseAsBoolean();
          case 's': return parseAsString();
          case 'a': return parseAsArray();
          case 'O': return parseAsObject();
          case 'r': return parseAsRef();
          case 'R': return parseAsRef();
          case 'N': return parseAsNull();
          default:
            throw {
              name: "Parse Error",
              message: "Unknown type '" + type + "' at postion " + (idx - 2)
            }
        } //end switch
    }; //end parseNext

    return parseNext();
} //end phpUnserialize
<|endoftext|>


<commit_before>/*globals __dirname*/

var path = require('path');

var module = QUnit.module;
var ok = QUnit.ok;
var equal = QUnit.equal;

var distPath = path.join(__dirname, '../../dist');

module('ember-template-compiler.js');

test('can be required', function() {
  var templateCompiler = require(path.join(distPath, 'ember-template-compiler'));

  ok(typeof templateCompiler.precompile === 'function', 'precompile function is present');
  ok(typeof templateCompiler.compile === 'function', 'compile function is present');
  ok(typeof templateCompiler.template === 'function', 'template function is present');
});

test('uses plugins with precompile', function() {
  var templateOutput;
  var templateCompiler = require(path.join(distPath, 'ember-template-compiler'));

  templateOutput = templateCompiler.precompile('{{#each foo in bar}}{{/each}}');
  ok(templateOutput.match(/{"keyword": "foo"}/), 'transform each in to block params');

  templateOutput = templateCompiler.precompile('{{#with foo as bar}}{{/with}}');
  ok(templateOutput.match(/set\(context, "bar", blockArguments\[0\]\);/), 'transform with as to block params');
});
<commit_msg>Add template-compiler tests for feature enabling in node-land.<commit_after>/*globals __dirname*/

var path = require('path');

var module = QUnit.module;
var ok = QUnit.ok;
var equal = QUnit.equal;

var distPath = path.join(__dirname, '../../dist');

module('ember-template-compiler.js');

test('can be required', function() {
  var templateCompiler = require(path.join(distPath, 'ember-template-compiler'));

  ok(typeof templateCompiler.precompile === 'function', 'precompile function is present');
  ok(typeof templateCompiler.compile === 'function', 'compile function is present');
  ok(typeof templateCompiler.template === 'function', 'template function is present');
});

test('uses plugins with precompile', function() {
  var templateOutput;
  var templateCompiler = require(path.join(distPath, 'ember-template-compiler'));

  templateOutput = templateCompiler.precompile('{{#each foo in bar}}{{/each}}');
  ok(templateOutput.match(/{"keyword": "foo"}/), 'transform each in to block params');

  templateOutput = templateCompiler.precompile('{{#with foo as bar}}{{/with}}');
  ok(templateOutput.match(/set\(context, "bar", blockArguments\[0\]\);/), 'transform with as to block params');
});

test('allows enabling of features', function() {
  var templateOutput;
  var templateCompiler = require(path.join(distPath, 'ember-template-compiler'));

  templateCompiler._Ember.FEATURES['ember-htmlbars-component-generation'] = true;

  templateOutput = templateCompiler.precompile('<some-thing></some-thing>');
  ok(templateOutput.match(/component\(morph0, "some-thing"/), 'component generation can be enabled');
});
<|endoftext|>


<commit_before>const _ = require('lodash')
const Promise = require('promised-io/promise')

const { intelInput, intelExtract } = require('./intelli')
const findCandidates = require('./find-candidates')
const findSuggestions = require('./find-suggestions')
const extractLines = require('./extract-lines')
const summary = require('./summary')
const techConfig = require('../config')

function run(reporterType, techType, dirPath, ...filePaths) {
  const runnerConfig = techConfig[techType]
  if (_.isEmpty(runnerConfig)) {
    throw new Error(`Unsupported techType: ${techType}`)
  }

  return Promise.allKeys({
    intelliByFile: Promise.seq([
      intelInput.bind(null, [dirPath], runnerConfig),
      (filesByDirectory) => intelExtract(filesByDirectory, runnerConfig),
    ]),
    candidatesByFile: Promise.seq([
      extractLines.bind(null, filePaths),
      ({ files: linesByFile }) => findCandidates(linesByFile),
    ]),
  }).then((data) => {
    return summary(reporterType, findSuggestions(_.extend(data, { config: runnerConfig })))
  })
}

module.exports = {
  run,
}
<commit_msg>Lint code.<commit_after>const _ = require('lodash')
const Promise = require('promised-io/promise')

const { intelInput, intelExtract } = require('./intelli')
const findCandidates = require('./find-candidates')
const findSuggestions = require('./find-suggestions')
const extractLines = require('./extract-lines')
const summary = require('./summary')
const techConfig = require('../config')

function run(reporterType, techType, dirPath, ...filePaths) {
  const runnerConfig = techConfig[techType]
  if (_.isEmpty(runnerConfig)) {
    throw new Error(`Unsupported techType: ${techType}`)
  }

  return Promise.allKeys({
    intelliByFile: Promise.seq([
      intelInput.bind(null, [dirPath], runnerConfig),
      (filesByDirectory) => intelExtract(filesByDirectory, runnerConfig),
    ]),
    candidatesByFile: Promise.seq([
      extractLines.bind(null, filePaths),
      ({ files: linesByFile }) => findCandidates(linesByFile),
    ]),
  }).then((data) => summary(
    reporterType,
    findSuggestions(_.extend(data, {
      config: runnerConfig,
    }))
  ))
}

module.exports = {
  run,
}
<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
const assert = require("assert");
const path = require("path");
const tryResolve = require("try-resolve");
const validateConfigConstructor = (ConfigConstructor) => {
    assert(ConfigConstructor.CONFIG_PACKAGE_PREFIX &&
        ConfigConstructor.FILTER_RULE_NAME_PREFIX &&
        ConfigConstructor.RULE_NAME_PREFIX &&
        ConfigConstructor.RULE_PRESET_NAME_PREFIX &&
        ConfigConstructor.PLUGIN_NAME_PREFIX);
};
/**
 * This class aim to resolve textlint's package name and get the module path.
 *
 * Define
 *
 * - `package` is npm package
 * - `module` is package's main module
 *
 * ## Support
 *
 * - textlint-rule-*
 * - textlint-preset-*
 * - textlint-plugin-*
 * - textlint-config-*
 */
export default class TextLintModuleResolver {
    /**
     *
     * @param {Config|*} ConfigConstructor config constructor like object
     * It has static property like CONFIG_PACKAGE_PREFIX etc...
     * @param {string} [baseDirectory]
     * @constructor
     */
    constructor(ConfigConstructor, baseDirectory = "") {
        validateConfigConstructor(ConfigConstructor);
        /**
         * @return {string} config package prefix
         */
        this.CONFIG_PACKAGE_PREFIX = ConfigConstructor.CONFIG_PACKAGE_PREFIX;
        /**
         * @return {string} rule package's name prefix
         */
        this.RULE_NAME_PREFIX = ConfigConstructor.RULE_NAME_PREFIX;
        /**
         * @return {string} filter rule package's name prefix
         */
        this.FILTER_RULE_NAME_PREFIX = ConfigConstructor.FILTER_RULE_NAME_PREFIX;
        /**
         * @return {string} rule preset package's name prefix
         */
        this.RULE_PRESET_NAME_PREFIX = ConfigConstructor.RULE_PRESET_NAME_PREFIX;
        /**
         * @return {string} plugins package's name prefix
         */
        this.PLUGIN_NAME_PREFIX = ConfigConstructor.PLUGIN_NAME_PREFIX;

        /**
         * @type {string} baseDirectory for resolving
         */
        this.baseDirectory = baseDirectory;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolveRulePackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.RULE_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <rule-name> or textlint-rule-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's rule module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolveFilterRulePackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.FILTER_RULE_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <rule-name> or textlint-filter-rule-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's filter rule module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolvePluginPackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.PLUGIN_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <plugin-name> or textlint-plugin-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's plugin module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolvePresetPackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.RULE_PRESET_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;

        /* Implementation Note

        preset name is defined in config file:
        In the case, `packageName` is "preset-gizmo"
        TextLintModuleResolver resolve "preset-gizmo" to "textlint-rule-preset-gizmo"

        {
            "rules": {
                "preset-gizmo": {
                    "ruleA": false
                }
            }
        }
         */
        // <preset-name> or textlint-rule-preset-<rule-name>
        const packageNameWithoutPreset = packageName.replace(/^preset\-/, "");
        const fullFullPackageName = `${PREFIX}${packageNameWithoutPreset}`;
        // preset-<preset-name> or textlint-rule-preset-<preset-name>
        const pkgPath = tryResolve(path.join(baseDir, fullFullPackageName)) ||
            tryResolve(path.join(baseDir, packageNameWithoutPreset)) ||
            // <preset-name> or textlint-rule-preset-<rule-name>
            tryResolve(path.join(baseDir, fullPackageName)) ||
            tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's preset module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take Config package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolveConfigPackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.CONFIG_PACKAGE_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <plugin-name> or textlint-config-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's config module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }
}

<commit_msg>chore(jsdoc): fix type<commit_after>// LICENSE : MIT
"use strict";
const assert = require("assert");
const path = require("path");
const tryResolve = require("try-resolve");
const validateConfigConstructor = (ConfigConstructor) => {
    assert(ConfigConstructor.CONFIG_PACKAGE_PREFIX &&
        ConfigConstructor.FILTER_RULE_NAME_PREFIX &&
        ConfigConstructor.RULE_NAME_PREFIX &&
        ConfigConstructor.RULE_PRESET_NAME_PREFIX &&
        ConfigConstructor.PLUGIN_NAME_PREFIX);
};
/**
 * This class aim to resolve textlint's package name and get the module path.
 *
 * Define
 *
 * - `package` is npm package
 * - `module` is package's main module
 *
 * ## Support
 *
 * - textlint-rule-*
 * - textlint-preset-*
 * - textlint-plugin-*
 * - textlint-config-*
 */
export default class TextLintModuleResolver {
    /**
     *
     * @param {Config|*} ConfigConstructor config constructor like object
     * It has static property like CONFIG_PACKAGE_PREFIX etc...
     * @param {string} [baseDirectory]
     * @constructor
     */
    constructor(ConfigConstructor, baseDirectory = "") {
        validateConfigConstructor(ConfigConstructor);
        /**
         * @type {string} config package prefix
         */
        this.CONFIG_PACKAGE_PREFIX = ConfigConstructor.CONFIG_PACKAGE_PREFIX;
        /**
         * @type {string} rule package's name prefix
         */
        this.RULE_NAME_PREFIX = ConfigConstructor.RULE_NAME_PREFIX;
        /**
         * @type {string} filter rule package's name prefix
         */
        this.FILTER_RULE_NAME_PREFIX = ConfigConstructor.FILTER_RULE_NAME_PREFIX;
        /**
         * @type {string} rule preset package's name prefix
         */
        this.RULE_PRESET_NAME_PREFIX = ConfigConstructor.RULE_PRESET_NAME_PREFIX;
        /**
         * @type {string} plugins package's name prefix
         */
        this.PLUGIN_NAME_PREFIX = ConfigConstructor.PLUGIN_NAME_PREFIX;

        /**
         * @type {string} baseDirectory for resolving
         */
        this.baseDirectory = baseDirectory;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolveRulePackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.RULE_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <rule-name> or textlint-rule-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's rule module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolveFilterRulePackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.FILTER_RULE_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <rule-name> or textlint-filter-rule-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's filter rule module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolvePluginPackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.PLUGIN_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <plugin-name> or textlint-plugin-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's plugin module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolvePresetPackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.RULE_PRESET_NAME_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;

        /* Implementation Note

        preset name is defined in config file:
        In the case, `packageName` is "preset-gizmo"
        TextLintModuleResolver resolve "preset-gizmo" to "textlint-rule-preset-gizmo"

        {
            "rules": {
                "preset-gizmo": {
                    "ruleA": false
                }
            }
        }
         */
        // <preset-name> or textlint-rule-preset-<rule-name>
        const packageNameWithoutPreset = packageName.replace(/^preset\-/, "");
        const fullFullPackageName = `${PREFIX}${packageNameWithoutPreset}`;
        // preset-<preset-name> or textlint-rule-preset-<preset-name>
        const pkgPath = tryResolve(path.join(baseDir, fullFullPackageName)) ||
            tryResolve(path.join(baseDir, packageNameWithoutPreset)) ||
            // <preset-name> or textlint-rule-preset-<rule-name>
            tryResolve(path.join(baseDir, fullPackageName)) ||
            tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's preset module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }

    /**
     * Take Config package name, and return path to module.
     * @param {string} packageName
     * @returns {string} return path to module
     */
    resolveConfigPackageName(packageName) {
        const baseDir = this.baseDirectory;
        const PREFIX = this.CONFIG_PACKAGE_PREFIX;
        const fullPackageName = `${PREFIX}${packageName}`;
        // <plugin-name> or textlint-config-<rule-name>
        const pkgPath = tryResolve(path.join(baseDir, fullPackageName)) || tryResolve(path.join(baseDir, packageName));
        if (!pkgPath) {
            throw new ReferenceError(`Failed to load textlint's config module: "${packageName}" is not found.
See FAQ: https://github.com/textlint/textlint/blob/master/docs/faq/failed-to-load-textlints-module.md
`);
        }
        return pkgPath;
    }
}

<|endoftext|>


<commit_before>'use strict';

function parseJSON(data) {
  try {
    var jsonString = data.toString().replace(/^\uFEFF/, '');
    return JSON.parse(jsonString);
  } catch (e) {
    return undefined;
  }
}

// Extracted from: http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type
function isFunction(data) {
  var getType = {};
  return data && getType.toString.call(data) === '[object Function]';
}

function isString(data) {
  return typeof data === 'string';
}

function capitalize(string) {
   return (isString(string) && string.length > 0 ? string.charAt(0).toUpperCase() + string.slice(1) : '');
}

function newGuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

function sanitizeName(name) {
  return name
          .replace(/\//g, '')
          .replace(/\s/g, '');
}

var urlRegex = /(\/?[\w-]+)(\/[\w-]+)*\/?|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/gi;

function isURL(data) {
  return (typeof data === 'string' && urlRegex.test(data));
}

module.exports = {
  parseJSON: parseJSON,
  isFunction: isFunction,
  isString: isString,
  capitalize: capitalize,
  newGuid: newGuid,
  sanitizeName: sanitizeName,
  isURL: isURL
};
<commit_msg>Revert "Replaced URL validation regular expression (needs to be improved)"<commit_after>'use strict';

function parseJSON(data) {
  try {
    var jsonString = data.toString().replace(/^\uFEFF/, '');
    return JSON.parse(jsonString);
  } catch (e) {
    return undefined;
  }
}

// Extracted from: http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type
function isFunction(data) {
  var getType = {};
  return data && getType.toString.call(data) === '[object Function]';
}

function isString(data) {
  return typeof data === 'string';
}

function capitalize(string) {
   return (isString(string) && string.length > 0 ? string.charAt(0).toUpperCase() + string.slice(1) : '');
}

function newGuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

function sanitizeName(name) {
  return name
          .replace(/\//g, '')
          .replace(/\s/g, '');
}

var urlRegex = /^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4:){6(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|::(?:[0-9a-f]{1,4:){5(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:){4(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:[0-9a-f]{1,4:[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:){3(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,2[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:){2(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,3[0-9a-f]{1,4)?::[0-9a-f]{1,4:(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,4[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,5[0-9a-f]{1,4)?::[0-9a-f]{1,4|(?:(?:[0-9a-f]{1,4:){0,6[0-9a-f]{1,4)?::)|v[0-9a-f]+[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=@])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])|[\uE000-\uF8FF\uF0000-\uFFFFD|\u100000-\u10FFFD\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4:){6(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|::(?:[0-9a-f]{1,4:){5(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:){4(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:[0-9a-f]{1,4:[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:){3(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,2[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:){2(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,3[0-9a-f]{1,4)?::[0-9a-f]{1,4:(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,4[0-9a-f]{1,4)?::(?:[0-9a-f]{1,4:[0-9a-f]{1,4|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3)|(?:(?:[0-9a-f]{1,4:){0,5[0-9a-f]{1,4)?::[0-9a-f]{1,4|(?:(?:[0-9a-f]{1,4:){0,6[0-9a-f]{1,4)?::)|v[0-9a-f]+[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=@])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])|[\uE000-\uF8FF\uF0000-\uFFFFD|\u100000-\u10FFFD\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\uA0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\u10000-\u1FFFD\u20000-\u2FFFD\u30000-\u3FFFD\u40000-\u4FFFD\u50000-\u5FFFD\u60000-\u6FFFD\u70000-\u7FFFD\u80000-\u8FFFD\u90000-\u9FFFD\uA0000-\uAFFFD\uB0000-\uBFFFD\uC0000-\uCFFFD\uD0000-\uDFFFD\uE1000-\uEFFFD!\$&'\(\)\*\+,;=:@])|[\/\?])*)?)$/i;
function isURL(data) {
  return (typeof data === 'string' && urlRegex.test(data));
}

module.exports = {
  parseJSON: parseJSON,
  isFunction: isFunction,
  isString: isString,
  capitalize: capitalize,
  newGuid: newGuid,
  sanitizeName: sanitizeName,
  isURL: isURL
};
<|endoftext|>


<commit_before>/*
 * Conditions Extension
 *
 *   Allows a condition module to alter the resolution of an import via syntax:
 *
 *     import $ from 'jquery/#{browser}';
 *
 *   Will first load the module 'browser' via `System.import('browser')` and
 *   take the default export of that module.
 *   If the default export is not a string, an error is thrown.
 *
 *   We then substitute the string into the require to get the conditional resolution
 *   enabling environment-specific variations like:
 *
 *     import $ from 'jquery/ie'
 *     import $ from 'jquery/firefox'
 *     import $ from 'jquery/chrome'
 *     import $ from 'jquery/safari'
 *
 *   It can be useful for a condition module to define multiple conditions.
 *   This can be done via the `|` modifier to specify an export member expression:
 *
 *     import 'jquery/#{./browser.js|grade.version}'
 *
 *   Where the `grade` export `version` member in the `browser.js` module  is substituted.
 *
 *
 * Boolean Conditionals
 *
 *   For polyfill modules, that are used as imports but have no module value,
 *   a binary conditional allows a module not to be loaded at all if not needed:
 *
 *     import 'es5-shim#?./conditions.js|needs-es5shim'
 *
 *   These conditions can also be negated via:
 *
 *     import 'es5-shim#?~./conditions.js|es6'
 *
 */
  function resolveCondition(conditionModule, parentName, bool) {
    var conditionExport;
    var conditionExportIndex = conditionModule.lastIndexOf('|');
    if (conditionExportIndex != -1) {
      conditionExport = conditionModule.substr(conditionExportIndex + 1);
      conditionModule = conditionModule.substr(0, conditionExportIndex);
    }

    var booleanNegation = bool && conditionModule && conditionModule[0] == '~';
    if (booleanNegation)
      conditionModule = conditionModule.substr(1);

    return this['import'](conditionModule, parentName)
    .then(function(m) {
      if (conditionExport)
        m = readMemberExpression(conditionExport, m);
      else if (typeof m == 'object' && m + '' == 'Module')
        m = m['default'];

      return booleanNegation ? !m : m;
    });
  }

  var interpolationRegEx = /#\{[^\}]+\}/;
  function interpolateConditional(name, parentName) {
    // first we normalize the conditional
    var conditionalMatch = name.match(interpolationRegEx);

    if (!conditionalMatch)
      return Promise.resolve(name);

    var conditionModule = conditionalMatch[0].substr(2, conditionalMatch[0].length - 3);

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionModule, parentName)
      .then(function(conditionModule) {
        return name.replace(interpolationRegEx, '#{' + conditionModule + '}');
      });

    return resolveCondition.call(this, conditionModule, parentName, false)
    .then(function(conditionValue) {
      if (typeof conditionValue !== 'string')
        throw new TypeError('The condition value for ' + conditionModule + ' doesn\'t resolve to a string.');

      return name.replace(interpolationRegEx, conditionValue);
    });
  }

  function booleanConditional(name, parentName) {
    // first we normalize the conditional
    var booleanIndex = name.lastIndexOf('#?');

    if (booleanIndex == -1)
      return Promise.resolve(name);

    var conditionModule = name.substr(booleanIndex + 2);

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionModule, parentName)
      .then(function(conditionModule) {
        return name.substr(0, name.length - conditionModule.length) = conditionModule;
      });

    return resolveCondition.call(this, conditionModule, parentName, true)
    .then(function(conditionValue) {
      return conditionValue ? name.substr(0, name.length - conditionModule.length - 2) : '@empty';
    });
  }

  hookConstructor(function(constructor) {
    return function() {
      constructor.call(this);

      // standard environment module, starting small as backwards-compat matters!
      this.set('@system-env', this.newModule({
        browser: isBrowser,
        node: !!this._nodeRequire
      }));
    };
  });

  // no normalizeSync
  hook('normalize', function(normalize) {
    return function(name, parentName, parentAddress) {
      var loader = this;
      return booleanConditional.call(loader, name, parentName)
      .then(function(name) {
        return normalize.call(loader, name, parentName, parentAddress);
      })
      .then(function(normalized) {
        return interpolateConditional.call(loader, normalized, parentName);
      });
    };
  });
<commit_msg>conditional default module as @system-env, build adjustments<commit_after>/*
 * Conditions Extension
 *
 *   Allows a condition module to alter the resolution of an import via syntax:
 *
 *     import $ from 'jquery/#{browser}';
 *
 *   Will first load the module 'browser' via `System.import('browser')` and
 *   take the default export of that module.
 *   If the default export is not a string, an error is thrown.
 *
 *   We then substitute the string into the require to get the conditional resolution
 *   enabling environment-specific variations like:
 *
 *     import $ from 'jquery/ie'
 *     import $ from 'jquery/firefox'
 *     import $ from 'jquery/chrome'
 *     import $ from 'jquery/safari'
 *
 *   It can be useful for a condition module to define multiple conditions.
 *   This can be done via the `|` modifier to specify an export member expression:
 *
 *     import 'jquery/#{./browser.js|grade.version}'
 *
 *   Where the `grade` export `version` member in the `browser.js` module  is substituted.
 *
 *
 * Boolean Conditionals
 *
 *   For polyfill modules, that are used as imports but have no module value,
 *   a binary conditional allows a module not to be loaded at all if not needed:
 *
 *     import 'es5-shim#?./conditions.js|needs-es5shim'
 *
 *   These conditions can also be negated via:
 *
 *     import 'es5-shim#?~./conditions.js|es6'
 *
 */

  function parseCondition(condition) {
    var conditionExport, conditionModule, negation;
    var conditionExportIndex = condition.lastIndexOf('|');
    if (conditionExportIndex != -1) {
      conditionExport = condition.substr(conditionExportIndex + 1);
      conditionModule = condition.substr(0, conditionExportIndex) || '@system-env';
    }
    else {
      conditionExport = null;
      conditionModule = condition;
    }

    var negation = !!conditionModule && conditionModule[0] == '~';
    if (negation)
      conditionModule = conditionModule.substr(1);

    return {
      module: conditionModule,
      prop: conditionExport,
      negate: negation
    };
  }

  function serializeCondition(conditionObj) {
    return (conditionObj.negate ? '~' : '') + conditionObj.module + (conditionObj.prop ? '|' + conditionObj.prop : '');
  }

  function resolveCondition(conditionObj, parentName, bool) {
    return this['import'](conditionObj.module, parentName)
    .then(function(m) {
      if (conditionObj.prop)
        m = readMemberExpression(conditionObj.prop, m);
      else if (typeof m == 'object' && m + '' == 'Module')
        m = m['default'];

      return conditionObj.negate ? !m : m;
    });
  }

  var interpolationRegEx = /#\{[^\}]+\}/;
  function interpolateConditional(name, parentName) {
    // first we normalize the conditional
    var conditionalMatch = name.match(interpolationRegEx);

    if (!conditionalMatch)
      return Promise.resolve(name);

    var conditionObj = parseCondition(conditionalMatch[0].substr(2, conditionalMatch[0].length - 3));

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionObj.module, parentName)
      .then(function(conditionModule) {
        conditionObj.conditionModule = conditionModule;
        return name.replace(interpolationRegEx, '#{' + serializeCondition(conditionObj) + '}');
      });

    return resolveCondition.call(this, conditionObj, parentName, false)
    .then(function(conditionValue) {
      if (typeof conditionValue !== 'string')
        throw new TypeError('The condition value for ' + name + ' doesn\'t resolve to a string.');

      return name.replace(interpolationRegEx, conditionValue);
    });
  }

  function booleanConditional(name, parentName) {
    // first we normalize the conditional
    var booleanIndex = name.lastIndexOf('#?');

    if (booleanIndex == -1)
      return Promise.resolve(name);

    var conditionObj = parseCondition(name.substr(booleanIndex + 2));

    // in builds, return normalized conditional
    if (this.builder)
      return this['normalize'](conditionObj.module, parentName)
      .then(function(conditionModule) {
        conditionObj.module = conditionModule;
        return name.substr(0, booleanIndex) + '#?' + serializeCondition(conditionObj);
      });

    return resolveCondition.call(this, conditionObj, parentName, true)
    .then(function(conditionValue) {
      return conditionValue ? name.substr(0, booleanIndex) : '@empty';
    });
  }

  hookConstructor(function(constructor) {
    return function() {
      constructor.call(this);

      // standard environment module, starting small as backwards-compat matters!
      this.set('@system-env', this.newModule({
        browser: isBrowser,
        node: !!this._nodeRequire
      }));
    };
  });

  // no normalizeSync
  hook('normalize', function(normalize) {
    return function(name, parentName, parentAddress) {
      var loader = this;
      return booleanConditional.call(loader, name, parentName)
      .then(function(name) {
        return normalize.call(loader, name, parentName, parentAddress);
      })
      .then(function(normalized) {
        return interpolateConditional.call(loader, normalized, parentName);
      });
    };
  });
<|endoftext|>


<commit_before>/**
 * Extend module's NODE_PATH
 * HACK: temporary solution
 */

require('node-path')(module);

/**
 * Module dependencies.
 */

var log = require('debug')('democracyos:config');
var environment = process.env.NODE_ENV || 'development';
var resolve = require('path').resolve;
var merge = require('merge-util');
var utils = require('lib/utils');
var has = utils.has;
var md5 = utils.md5;
var envConf = require('./env');

var filepath = resolve(__dirname, "..", "..", "config", environment + ".json");

var localConf = {};

try {
  log('Load local configuration from %s', filepath);
  localConf = require(filepath);
} catch (e) {
  log('Found error: %s', e.message);
}

log('Merge environment set configuration variables');

var conf = merge(localConf, envConf, { discardEmpty: false });
conf.env = environment;

log('Loaded config object for env %s with sha %j', environment, md5(JSON.stringify(conf)));

module.exports = config;

function config(key) {
  if (has.call(conf, key)) return conf[key];
  log('Invalid config key "%s"', key);
  // throw new Error('Invalid config key "' + key + '"');
  return undefined;
}

for (var key in conf) config[key] = conf[key];<commit_msg>Update error message<commit_after>/**
 * Extend module's NODE_PATH
 * HACK: temporary solution
 */

require('node-path')(module);

/**
 * Module dependencies.
 */

var log = require('debug')('democracyos:config');
var environment = process.env.NODE_ENV || 'development';
var resolve = require('path').resolve;
var merge = require('merge-util');
var utils = require('lib/utils');
var has = utils.has;
var md5 = utils.md5;
var envConf = require('./env');

var filepath = resolve(__dirname, "..", "..", "config", environment + ".json");

var localConf = {};

try {
  log('Load local configuration from %s', filepath);
  localConf = require(filepath);
} catch (e) {
  log('Unalbe to read configuration from file %s: %s', filepath, e.message);
}

log('Merge environment set configuration variables');

var conf = merge(localConf, envConf, { discardEmpty: false });
conf.env = environment;

log('Loaded config object for env %s with sha %j', environment, md5(JSON.stringify(conf)));

module.exports = config;

function config(key) {
  if (has.call(conf, key)) return conf[key];
  log('Invalid config key "%s"', key);
  // throw new Error('Invalid config key "' + key + '"');
  return undefined;
}

for (var key in conf) config[key] = conf[key];<|endoftext|>


<commit_before>var util = require('util');
var debug = require('debug')('reddit-emit:request');
var lodash = require('lodash');
var request = require('request');
var ValueEmitter = require('./ValueEmitter');
var pkg = require('../../package.json');

var author = (typeof author === 'object') ? author.name : author;

module.exports = Request;

util.inherits(Request, ValueEmitter);

/**
 * Create `request` function with default headers:
 *
 *     user-agent: '<pkg.name>/<pkg.version> by <pkg.author>'
 *
 * @returns {function}
 */

Request.go = request.defaults({
  headers: {
    'user-agent': pkg.name + '/' + pkg.version + ' by ' + author
  }
});

/**
 * Send requests at intervals.
 *
 * @class
 * @augments ValueEmitter
 * @param {object} options Same options as `request` with additional:
 * @param {number} options.interval
 * @param {array}  options.failStatus
 */

function Request (options) {
  ValueEmitter.call(this);

  if (!options) {
    throw new Error('Request requires the "options" argument');
  }

  options = lodash.cloneDeep(options);
  options.interval = options.interval || 0;
  options.failStatus = options.failStatus || [/^[^2]/];

  this.on('error', this._error);

  this.options = options;
  this._poll = false;
  this._timer = null;
  this._predicate();
}

/**
 * Validate current options object. To override in subclass.
 *
 * Default implementation always return true.
 *
 * @protected
 * @returns {boolean}
 */

Request.prototype.validate = function () {
  return true;
};

/**
 * Parse the response body. To override in subclass.
 *
 * Default implementation uses JSON.parse.
 *
 * @protected
 * @param {string} body
 * @returns {boolean}
 */

Request.prototype.parse = function (body) {
  return JSON.parse(body);
};

/**
 * Fetch the URL.
 */

Request.prototype.fetch = function (poll) {
  // enable/disable polling if `poll` arg given
  if (typeof poll !== 'undefined') {
    this._poll = poll;
  }

  try {
    // don't throw errors here, instead
    // emit them as events because
    // `fetch` might be called async-ly
    this._predicate();
  } catch (e) {
    this.emit('error', e);
    return false;
  }

  if (this.validate()) {
    // always clear timer before sending request
    // in case `fetch` is called while we are
    // already waiting on a timeout (TODO test)
    this._clear();
    debug('fetching', this.options.url);
    return Request.go(this.options, this._callback.bind(this));
  }

  return false;
};

/**
 * Start polling the URL.
 */

Request.prototype.poll = function (interval) {
  if (typeof interval !== 'undefined') {
    this.options.interval = interval;
  }
  this.fetch(true);
};

/**
 * Stop polling the URL.
 */

Request.prototype.stop = function () {
  debug('stopping poll');
  this._clear();
  this._poll = false;
};

/**
 * Returns true if in poll mode
 */

Request.prototype.isActive = function () {
  return this._poll;
};

/**
 * @private
 */

Request.prototype._clear = function () {
  if (this._timer) {
    debug('clearing timer');
    clearTimeout(this._timer);
    this._timer = null;
  }
};

/**
 * @private
 */

Request.prototype._predicate = function () {
  debug('predicate: url', this.options.url);
  if (!this.options.url) {
    throw new Error('Request requires the "url" option');
  }
  return true;
};

/**
 * @private
 */

Request.prototype._callback = function (err, resp, body) {
  debug('response', err, resp && resp.statusCode, body && body.length);

  if (resp) {
    // always emit response, even on error
    this.emit('response', resp);
    // check for non-200 errors
    if (!err && lodash.any(this.options.failStatus, match(resp.statusCode))) {
      err = new Error('Request: request responded with ' + resp.statusCode);
    }
  }

  if (!err) {
    // parse body, catching any parse errors
    try {
      body = this.parse(body);
    } catch (e) {
      err = e;
    }
  }

  if (err) {
    // attach response to error object
    err.response = resp;
    // emit error *after* stopping timer
    this.emit('error', err);
  } else {
    // everything ok? emit parsed body
    this.emit('data', body);
  }

  // only setTimeout if in 'poll' mode and interval > 0
  if (this._poll && this.options.interval) {
    debug('interval', this.options.interval);
    this._timer = setTimeout(this.fetch.bind(this), this.options.interval);
  }
};

/**
 * @private
 */

Request.prototype._error = function (err) {
  if (this.options.stopOnFail) {
    this.stop();
  }
};

function match (code) {
  return function (regexp) {
    return String(code).search(regexp) !== -1;
  };
}
<commit_msg>Fix pkg.author error<commit_after>var util = require('util');
var debug = require('debug')('reddit-emit:request');
var lodash = require('lodash');
var request = require('request');
var ValueEmitter = require('./ValueEmitter');
var pkg = require('../../package.json');

var author = (typeof pkg.author === 'object') ? author.name : author;

module.exports = Request;

util.inherits(Request, ValueEmitter);

/**
 * Create `request` function with default headers:
 *
 *     user-agent: '<pkg.name>/<pkg.version> by <pkg.author>'
 *
 * @returns {function}
 */

Request.go = request.defaults({
  headers: {
    'user-agent': pkg.name + '/' + pkg.version + ' by ' + author
  }
});

/**
 * Send requests at intervals.
 *
 * @class
 * @augments ValueEmitter
 * @param {object} options Same options as `request` with additional:
 * @param {number} options.interval
 * @param {array}  options.failStatus
 */

function Request (options) {
  ValueEmitter.call(this);

  if (!options) {
    throw new Error('Request requires the "options" argument');
  }

  options = lodash.cloneDeep(options);
  options.interval = options.interval || 0;
  options.failStatus = options.failStatus || [/^[^2]/];

  this.on('error', this._error);

  this.options = options;
  this._poll = false;
  this._timer = null;
  this._predicate();
}

/**
 * Validate current options object. To override in subclass.
 *
 * Default implementation always return true.
 *
 * @protected
 * @returns {boolean}
 */

Request.prototype.validate = function () {
  return true;
};

/**
 * Parse the response body. To override in subclass.
 *
 * Default implementation uses JSON.parse.
 *
 * @protected
 * @param {string} body
 * @returns {boolean}
 */

Request.prototype.parse = function (body) {
  return JSON.parse(body);
};

/**
 * Fetch the URL.
 */

Request.prototype.fetch = function (poll) {
  // enable/disable polling if `poll` arg given
  if (typeof poll !== 'undefined') {
    this._poll = poll;
  }

  try {
    // don't throw errors here, instead
    // emit them as events because
    // `fetch` might be called async-ly
    this._predicate();
  } catch (e) {
    this.emit('error', e);
    return false;
  }

  if (this.validate()) {
    // always clear timer before sending request
    // in case `fetch` is called while we are
    // already waiting on a timeout (TODO test)
    this._clear();
    debug('fetching', this.options.url);
    return Request.go(this.options, this._callback.bind(this));
  }

  return false;
};

/**
 * Start polling the URL.
 */

Request.prototype.poll = function (interval) {
  if (typeof interval !== 'undefined') {
    this.options.interval = interval;
  }
  this.fetch(true);
};

/**
 * Stop polling the URL.
 */

Request.prototype.stop = function () {
  debug('stopping poll');
  this._clear();
  this._poll = false;
};

/**
 * Returns true if in poll mode
 */

Request.prototype.isActive = function () {
  return this._poll;
};

/**
 * @private
 */

Request.prototype._clear = function () {
  if (this._timer) {
    debug('clearing timer');
    clearTimeout(this._timer);
    this._timer = null;
  }
};

/**
 * @private
 */

Request.prototype._predicate = function () {
  debug('predicate: url', this.options.url);
  if (!this.options.url) {
    throw new Error('Request requires the "url" option');
  }
  return true;
};

/**
 * @private
 */

Request.prototype._callback = function (err, resp, body) {
  debug('response', err, resp && resp.statusCode, body && body.length);

  if (resp) {
    // always emit response, even on error
    this.emit('response', resp);
    // check for non-200 errors
    if (!err && lodash.any(this.options.failStatus, match(resp.statusCode))) {
      err = new Error('Request: request responded with ' + resp.statusCode);
    }
  }

  if (!err) {
    // parse body, catching any parse errors
    try {
      body = this.parse(body);
    } catch (e) {
      err = e;
    }
  }

  if (err) {
    // attach response to error object
    err.response = resp;
    // emit error *after* stopping timer
    this.emit('error', err);
  } else {
    // everything ok? emit parsed body
    this.emit('data', body);
  }

  // only setTimeout if in 'poll' mode and interval > 0
  if (this._poll && this.options.interval) {
    debug('interval', this.options.interval);
    this._timer = setTimeout(this.fetch.bind(this), this.options.interval);
  }
};

/**
 * @private
 */

Request.prototype._error = function (err) {
  if (this.options.stopOnFail) {
    this.stop();
  }
};

function match (code) {
  return function (regexp) {
    return String(code).search(regexp) !== -1;
  };
}
<|endoftext|>


<commit_before>'use strict';

var NET   = require('net');
var PORTS = {};

function CreateServer(
  port,
  callback
){

  var server;

  if(
    (typeof port === 'number')
  ){

    port = parseFloat(port);

    if(
      (PORTS[port.toString()])
    ){

      process.nextTick(function CreateServerAgain(){

        CreateServer(port,callback);
      });

      return;
    }

    PORTS[port.toString()] = true;

    server = new NET.Server;

    server.on('error',function CreateServerError(
      error
     ){

      CloseServer(server);

      delete PORTS[port.toString()];

      callback(
        (error.code === 'EADDRINUSE') ? null : error,
        false,
        port
      );
    });

    server.on('listening',function CreateServerListening(
    ){

      CloseServer(server);

      delete PORTS[port.toString()];

      callback(null,true,port);
    });

    server.listen(port);
  }
  else if(typeof callback === 'function') callback(null,false);
}

/* This function is to allow 'CreateServer'
// to be optimized by isolating the 'try'.
// Because this is just to try and close the
// server, if it's somehow listening after
// erroring, we won't handle any errors that
// come out of this `CloseServer`.
*/
function CloseServer(
  server
){

  try{

    if(typeof server.unref === 'function') server.unref();
    server.close();
  }
  catch(error){}
}

module.exports = CreateServer;

<commit_msg>Replace multiple .toString calls with a defined variable.<commit_after>'use strict';

var NET   = require('net');
var PORTS = {};

function CreateServer(
  port,
  callback
){

  var server;
  var port_string;

  if(
    (typeof port === 'number')
  ){

    port = parseFloat(port);
    port_string = port.toString();

    if(
      (PORTS[port_string])
    ){

      process.nextTick(function CreateServerAgain(){

        CreateServer(port,callback);
      });

      return;
    }

    PORTS[port_string] = true;

    server = new NET.Server;

    server.on('error',function CreateServerError(
      error
     ){

      CloseServer(server);

      delete PORTS[port_string];

      callback(
        (error.code === 'EADDRINUSE') ? null : error,
        false,
        port
      );
    });

    server.on('listening',function CreateServerListening(
    ){

      CloseServer(server);

      delete PORTS[port_string];

      callback(null,true,port);
    });

    server.listen(port);
  }
  else if(typeof callback === 'function') callback(null,false);
}

/* This function is to allow 'CreateServer'
// to be optimized by isolating the 'try'.
// Because this is just to try and close the
// server, if it's somehow listening after
// erroring, we won't handle any errors that
// come out of this `CloseServer`.
*/
function CloseServer(
  server
){

  try{

    if(typeof server.unref === 'function') server.unref();
    server.close();
  }
  catch(error){}
}

module.exports = CreateServer;

<|endoftext|>


<commit_before>import assert from 'assert';
import { errors } from 'arsenal';

import Sproxy from 'sproxydclient';

import inMemory from './in_memory/backend';
import Config from '../Config';

let client;
let implName;

if (process.env.S3BACKEND && process.env.S3BACKEND === 'mem') {
    client = inMemory;
    implName = 'mem';
} else {
    const config = new Config();
    assert(config.sproxyd.bootstrap.length > 0,
           'sproxyd bootstrap list is empty');
    client = new Sproxy({
        bootstrap: config.sproxyd.bootstrap,
        log: config.log,
    });
    implName = 'sproxyd';
}

const data = {
    put: (value, keyContext, log, cb) => {
        log.debug('sending put to datastore', { implName, keyContext,
            method: 'put' });
        client.put(value, keyContext, log.getSerializedUids(), (err, key) => {
            if (err) {
                log.error('error from sproxyd', { error: err });
                return cb(errors.InternalError);
            }
            return cb(null, key);
        });
    },

    get: (key, log, cb) => {
        log.debug('sending get to datastore', { implName, key, method: 'get' });
        client.get(key, log.getSerializedUids(), (err, val) => {
            if (err) {
                log.error('error from sproxyd', { error: err });
                return cb(errors.InternalError);
            }
            return cb(null, val);
        });
    },

    delete: (key, log, cb) => {
        log.debug('sending delete to datastore', { implName, key,
            method: 'delete' });
        client.delete(key, log.getSerializedUids(), err => {
            if (err) {
                log.error('error from sproxyd', { error: err });
                return cb(errors.InternalError);
            }
            return cb();
        });
    },

    switch: (newClient) => {
        client = newClient;
        return client;
    },
};

export default data;
<commit_msg>FT: (sproxyd_backend) env variable<commit_after>import assert from 'assert';
import { errors } from 'arsenal';

import Sproxy from 'sproxydclient';

import inMemory from './in_memory/backend';
import Config from '../Config';

let client;
let implName;

if ((process.env.S3BACKEND && process.env.S3BACKEND === 'mem')
    || (process.env.S3SPROXYD && process.env.S3SPROXYD === 'mem')) {
    client = inMemory;
    implName = 'mem';
} else {
    const config = new Config();
    assert(config.sproxyd.bootstrap.length > 0,
           'sproxyd bootstrap list is empty');
    client = new Sproxy({
        bootstrap: config.sproxyd.bootstrap,
        log: config.log,
    });
    implName = 'sproxyd';
}

const data = {
    put: (value, keyContext, log, cb) => {
        log.debug('sending put to datastore', { implName, keyContext,
            method: 'put' });
        client.put(value, keyContext, log.getSerializedUids(), (err, key) => {
            if (err) {
                log.error('error from sproxyd', { error: err });
                return cb(errors.InternalError);
            }
            return cb(null, key);
        });
    },

    get: (key, log, cb) => {
        log.debug('sending get to datastore', { implName, key, method: 'get' });
        client.get(key, log.getSerializedUids(), (err, val) => {
            if (err) {
                log.error('error from sproxyd', { error: err });
                return cb(errors.InternalError);
            }
            return cb(null, val);
        });
    },

    delete: (key, log, cb) => {
        log.debug('sending delete to datastore', { implName, key,
            method: 'delete' });
        client.delete(key, log.getSerializedUids(), err => {
            if (err) {
                log.error('error from sproxyd', { error: err });
                return cb(errors.InternalError);
            }
            return cb();
        });
    },

    switch: (newClient) => {
        client = newClient;
        return client;
    },
};

export default data;
<|endoftext|>


<commit_before>/* eslint no-caller:0 */
function decode_error(err) {
  if (err.response) {
    if (err.response.body) {
      err = new Error(err.response.body.message);
    } else {
      err = new Error(err.response.text);
    }
    Error.captureStackTrace(err, arguments.callee);
  } else if (err.res) {
    err = new Error(err.res.body.message);
    Error.captureStackTrace(err, arguments.callee);
  } else if (err.code === 'ECONNREFUSED') {
    err.message = 'scout-server not running on endpoint?';
  } else if (err.message === 'Origin is not allowed by Access-Control-Allow-Origin') {
    err.message = 'scout-server not running on endpoint?';
  }
  return err;
}

module.exports = decode_error;
<commit_msg>:memo: update from deprecated name<commit_after>/* eslint no-caller:0 */
function decode_error(err) {
  if (err.response) {
    if (err.response.body) {
      err = new Error(err.response.body.message);
    } else {
      err = new Error(err.response.text);
    }
    Error.captureStackTrace(err, arguments.callee);
  } else if (err.res) {
    err = new Error(err.res.body.message);
    Error.captureStackTrace(err, arguments.callee);
  } else if (err.code === 'ECONNREFUSED') {
    err.message = 'mongodb-scope-server not running on endpoint?';
  } else if (err.message === 'Origin is not allowed by Access-Control-Allow-Origin') {
    err.message = 'mongodb-scope-server not running on endpoint?';
  }
  return err;
}

module.exports = decode_error;
<|endoftext|>