Initial commit

This commit is contained in:
pasketti
2026-04-05 16:14:49 -04:00
commit ebee3a5534
14059 changed files with 2588797 additions and 0 deletions

43469
node_modules/neo4j-driver/lib/browser/neo4j-web.js generated vendored Normal file

File diff suppressed because one or more lines are too long

23
node_modules/neo4j-driver/lib/browser/neo4j-web.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
// This is free and unencumbered software released into the public domain.
// See LICENSE.md for more information.
var encoding = require("./lib/encoding.js");
module.exports = {
TextEncoder: encoding.TextEncoder,
TextDecoder: encoding.TextDecoder,
};

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
//
// Externs for Closure Compiler
// https://developers.google.com/closure/compiler/
//
// Usage:
// java -jar compiler.jar \
// --jscomp_warning reportUnknownTypes \
// --warning_level VERBOSE \
// --summary_detail_level 3 \
// --externs util/externs.js \
// lib/encoding.js
//
/**
* @param {string} name
* @return {*}
*/
function require(name) {}
/**
* @type {Object}
*/
var module;
/**
* @type {Object.<string,*>}
*/
module.exports;

33
node_modules/neo4j-driver/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.v1 = undefined;
var _index = require('./v1/index');
var v1 = _interopRequireWildcard(_index);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
exports.v1 = v1; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = v1;

386
node_modules/neo4j-driver/lib/v1/driver.js generated vendored Normal file
View File

@@ -0,0 +1,386 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WRITE = exports.READ = exports.Driver = undefined;
var _maxSafeInteger = require('babel-runtime/core-js/number/max-safe-integer');
var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _get2 = require('babel-runtime/helpers/get');
var _get3 = _interopRequireDefault(_get2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _session = require('./session');
var _session2 = _interopRequireDefault(_session);
var _pool = require('./internal/pool');
var _pool2 = _interopRequireDefault(_pool);
var _connector = require('./internal/connector');
var _streamObserver = require('./internal/stream-observer');
var _streamObserver2 = _interopRequireDefault(_streamObserver);
var _error = require('./error');
var _connectionProviders = require('./internal/connection-providers');
var _bookmark = require('./internal/bookmark');
var _bookmark2 = _interopRequireDefault(_bookmark);
var _connectivityVerifier = require('./internal/connectivity-verifier');
var _connectivityVerifier2 = _interopRequireDefault(_connectivityVerifier);
var _poolConfig = require('./internal/pool-config');
var _poolConfig2 = _interopRequireDefault(_poolConfig);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_MAX_CONNECTION_LIFETIME = 60 * 60 * 1000; // 1 hour
/**
* Constant that represents read session access mode.
* Should be used like this: <code>driver.session(READ)</code>.
* @type {string}
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var READ = 'READ';
/**
* Constant that represents write session access mode.
* Should be used like this: <code>driver.session(WRITE)</code>.
* @type {string}
*/
var WRITE = 'WRITE';
/**
* A driver maintains one or more {@link Session}s with a remote
* Neo4j instance. Through the {@link Session}s you can send statements
* and retrieve results from the database.
*
* Drivers are reasonably expensive to create - you should strive to keep one
* driver instance around per Neo4j Instance you connect to.
*
* @access public
*/
var Driver = function () {
/**
* You should not be calling this directly, instead use {@link driver}.
* @constructor
* @param {string} hostPort
* @param {string} userAgent
* @param {object} token
* @param {object} config
* @protected
*/
function Driver(hostPort, userAgent) {
var token = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
(0, _classCallCheck3.default)(this, Driver);
sanitizeConfig(config);
this._hostPort = hostPort;
this._userAgent = userAgent;
this._openSessions = {};
this._sessionIdGenerator = 0;
this._token = token;
this._config = config;
this._pool = new _pool2.default(this._createConnection.bind(this), this._destroyConnection.bind(this), this._validateConnection.bind(this), _poolConfig2.default.fromDriverConfig(config));
/**
* Reference to the connection provider. Initialized lazily by {@link _getOrCreateConnectionProvider}.
* @type {ConnectionProvider}
* @protected
*/
this._connectionProvider = null;
this._onCompleted = null;
}
/**
* Get the installed connectivity verification callback.
* @return {null|function}
* @deprecated driver can be used directly once instantiated, use of this callback is not required.
*/
(0, _createClass3.default)(Driver, [{
key: '_createConnection',
/**
* Create a new connection instance.
* @return {Connection} new connector-api session instance, a low level session API.
* @access private
*/
value: function _createConnection(hostPort, release) {
var sessionId = this._sessionIdGenerator++;
var conn = (0, _connector.connect)(hostPort, this._config, this._connectionErrorCode());
var streamObserver = new _ConnectionStreamObserver(this, conn);
conn.initialize(this._userAgent, this._token, streamObserver);
conn._id = sessionId;
conn._release = function () {
return release(hostPort, conn);
};
this._openSessions[sessionId] = conn;
return conn;
}
/**
* Check that a connection is usable
* @return {boolean} true if the connection is open
* @access private
**/
}, {
key: '_validateConnection',
value: function _validateConnection(conn) {
if (!conn.isOpen()) {
return false;
}
var maxConnectionLifetime = this._config.maxConnectionLifetime;
var lifetime = Date.now() - conn.creationTimestamp;
return lifetime <= maxConnectionLifetime;
}
/**
* Dispose of a live session, closing any associated resources.
* @return {Session} new session.
* @access private
*/
}, {
key: '_destroyConnection',
value: function _destroyConnection(conn) {
delete this._openSessions[conn._id];
conn.close();
}
/**
* Acquire a session to communicate with the database. The driver maintains
* a pool of sessions, so calling this method is normally cheap because you
* will be pulling a session out of the common pool.
*
* This comes with some responsibility - make sure you always call
* {@link close} when you are done using a session, and likewise,
* make sure you don't close your session before you are done using it. Once
* it is returned to the pool, the session will be reset to a clean state and
* made available for others to use.
*
* @param {string} [mode=WRITE] the access mode of this session, allowed values are {@link READ} and {@link WRITE}.
* @param {string|string[]} [bookmarkOrBookmarks=null] the initial reference or references to some previous
* transactions. Value is optional and absence indicates that that the bookmarks do not exist or are unknown.
* @return {Session} new session.
*/
}, {
key: 'session',
value: function session(mode, bookmarkOrBookmarks) {
var sessionMode = Driver._validateSessionMode(mode);
var connectionProvider = this._getOrCreateConnectionProvider();
var bookmark = new _bookmark2.default(bookmarkOrBookmarks);
return this._createSession(sessionMode, connectionProvider, bookmark, this._config);
}
}, {
key: '_createConnectionProvider',
// Extension point
value: function _createConnectionProvider(hostPort, connectionPool, driverOnErrorCallback) {
return new _connectionProviders.DirectConnectionProvider(hostPort, connectionPool, driverOnErrorCallback);
}
// Extension point
}, {
key: '_createSession',
value: function _createSession(mode, connectionProvider, bookmark, config) {
return new _session2.default(mode, connectionProvider, bookmark, config);
}
// Extension point
}, {
key: '_connectionErrorCode',
value: function _connectionErrorCode() {
// connection errors might result in different error codes depending on the driver
return _error.SERVICE_UNAVAILABLE;
}
}, {
key: '_getOrCreateConnectionProvider',
value: function _getOrCreateConnectionProvider() {
if (!this._connectionProvider) {
var driverOnErrorCallback = this._driverOnErrorCallback.bind(this);
this._connectionProvider = this._createConnectionProvider(this._hostPort, this._pool, driverOnErrorCallback);
}
return this._connectionProvider;
}
}, {
key: '_driverOnErrorCallback',
value: function _driverOnErrorCallback(error) {
var userDefinedOnErrorCallback = this.onError;
if (userDefinedOnErrorCallback && error.code === _error.SERVICE_UNAVAILABLE) {
userDefinedOnErrorCallback(error);
} else {
// we don't need to tell the driver about this error
}
}
/**
* Close all open sessions and other associated resources. You should
* make sure to use this when you are done with this driver instance.
* @return undefined
*/
}, {
key: 'close',
value: function close() {
for (var sessionId in this._openSessions) {
if (this._openSessions.hasOwnProperty(sessionId)) {
this._openSessions[sessionId].close();
}
this._pool.purgeAll();
}
}
}, {
key: 'onCompleted',
get: function get() {
return this._onCompleted;
}
/**
* Install a connectivity verification callback.
* @param {null|function} callback the new function to be notified about successful connection.
* @deprecated driver can be used directly once instantiated, use of this callback is not required.
*/
,
set: function set(callback) {
this._onCompleted = callback;
if (this._onCompleted) {
var connectionProvider = this._getOrCreateConnectionProvider();
var connectivityVerifier = new _connectivityVerifier2.default(connectionProvider, this._onCompleted);
connectivityVerifier.verify();
}
}
}], [{
key: '_validateSessionMode',
value: function _validateSessionMode(rawMode) {
var mode = rawMode || WRITE;
if (mode !== READ && mode !== WRITE) {
throw (0, _error.newError)('Illegal session mode ' + mode);
}
return mode;
}
}]);
return Driver;
}();
/** Internal stream observer used for connection state */
var _ConnectionStreamObserver = function (_StreamObserver) {
(0, _inherits3.default)(_ConnectionStreamObserver, _StreamObserver);
function _ConnectionStreamObserver(driver, conn) {
(0, _classCallCheck3.default)(this, _ConnectionStreamObserver);
var _this = (0, _possibleConstructorReturn3.default)(this, (_ConnectionStreamObserver.__proto__ || (0, _getPrototypeOf2.default)(_ConnectionStreamObserver)).call(this));
_this._driver = driver;
_this._conn = conn;
_this._hasFailed = false;
return _this;
}
(0, _createClass3.default)(_ConnectionStreamObserver, [{
key: 'onError',
value: function onError(error) {
if (!this._hasFailed) {
(0, _get3.default)(_ConnectionStreamObserver.prototype.__proto__ || (0, _getPrototypeOf2.default)(_ConnectionStreamObserver.prototype), 'onError', this).call(this, error);
if (this._driver.onError) {
this._driver.onError(error);
}
this._hasFailed = true;
}
}
}]);
return _ConnectionStreamObserver;
}(_streamObserver2.default);
/**
* @private
*/
function sanitizeConfig(config) {
config.maxConnectionLifetime = sanitizeIntValue(config.maxConnectionLifetime, DEFAULT_MAX_CONNECTION_LIFETIME);
config.maxConnectionPoolSize = sanitizeIntValue(config.maxConnectionPoolSize, _poolConfig.DEFAULT_MAX_SIZE);
config.connectionAcquisitionTimeout = sanitizeIntValue(config.connectionAcquisitionTimeout, _poolConfig.DEFAULT_ACQUISITION_TIMEOUT);
}
function sanitizeIntValue(rawValue, defaultWhenAbsent) {
var sanitizedValue = parseInt(rawValue, 10);
if (sanitizedValue > 0 || sanitizedValue === 0) {
return sanitizedValue;
} else if (sanitizedValue < 0) {
return _maxSafeInteger2.default;
} else {
return defaultWhenAbsent;
}
}
exports.Driver = Driver;
exports.READ = READ;
exports.WRITE = WRITE;
exports.default = Driver;

105
node_modules/neo4j-driver/lib/v1/error.js generated vendored Normal file
View File

@@ -0,0 +1,105 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PROTOCOL_ERROR = exports.SESSION_EXPIRED = exports.SERVICE_UNAVAILABLE = exports.Neo4jError = exports.newError = undefined;
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A common place for constructing error objects, to keep them
// uniform across the driver surface.
/**
* Error code representing complete loss of service. Used by {@link Neo4jError#code}.
* @type {string}
*/
var SERVICE_UNAVAILABLE = 'ServiceUnavailable';
/**
* Error code representing transient loss of service. Used by {@link Neo4jError#code}.
* @type {string}
*/
var SESSION_EXPIRED = 'SessionExpired';
/**
* Error code representing serialization/deserialization issue in the Bolt protocol. Used by {@link Neo4jError#code}.
* @type {string}
*/
var PROTOCOL_ERROR = 'ProtocolError';
function newError(message) {
var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "N/A";
// TODO: Idea is that we can check the code here and throw sub-classes
// of Neo4jError as appropriate
return new Neo4jError(message, code);
}
/**
* Class for all errors thrown/returned by the driver.
*/
var Neo4jError = function (_Error) {
(0, _inherits3.default)(Neo4jError, _Error);
/**
* @constructor
* @param {string} message - The error message.
* @param {string} code - Optional error code. Will be populated when error originates in the database.
*/
function Neo4jError(message) {
var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'N/A';
(0, _classCallCheck3.default)(this, Neo4jError);
var _this = (0, _possibleConstructorReturn3.default)(this, (Neo4jError.__proto__ || (0, _getPrototypeOf2.default)(Neo4jError)).call(this, message));
_this.message = message;
_this.code = code;
_this.name = "Neo4jError";
return _this;
}
return Neo4jError;
}(Error);
exports.newError = newError;
exports.Neo4jError = Neo4jError;
exports.SERVICE_UNAVAILABLE = SERVICE_UNAVAILABLE;
exports.SESSION_EXPIRED = SESSION_EXPIRED;
exports.PROTOCOL_ERROR = PROTOCOL_ERROR;

231
node_modules/neo4j-driver/lib/v1/graph-types.js generated vendored Normal file
View File

@@ -0,0 +1,231 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PathSegment = exports.Path = exports.UnboundRelationship = exports.Relationship = exports.Node = undefined;
var _stringify = require("babel-runtime/core-js/json/stringify");
var _stringify2 = _interopRequireDefault(_stringify);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
var _integer = require("./integer");
var _integer2 = _interopRequireDefault(_integer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Class for Node Type.
*/
var Node = function () {
/**
* @constructor
* @param {Integer} identity - Unique identity
* @param {Array<string>} labels - Array for all labels
* @param {Object} properties - Map with node properties
*/
function Node(identity, labels, properties) {
(0, _classCallCheck3.default)(this, Node);
this.identity = identity;
this.labels = labels;
this.properties = properties;
}
(0, _createClass3.default)(Node, [{
key: "toString",
value: function toString() {
var s = "(" + this.identity;
for (var i = 0; i < this.labels.length; i++) {
s += ":" + this.labels[i];
}
var keys = (0, _keys2.default)(this.properties);
if (keys.length > 0) {
s += " {";
for (var _i = 0; _i < keys.length; _i++) {
if (_i > 0) s += ",";
s += keys[_i] + ":" + (0, _stringify2.default)(this.properties[keys[_i]]);
}
s += "}";
}
s += ")";
return s;
}
}]);
return Node;
}();
/**
* Class for Relationship Type.
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Relationship = function () {
/**
* @constructor
* @param {Integer} identity - Unique identity
* @param {Integer} start - Identity of start Node
* @param {Integer} end - Identity of end Node
* @param {string} type - Relationship type
* @param {Object} properties - Map with relationship properties
*/
function Relationship(identity, start, end, type, properties) {
(0, _classCallCheck3.default)(this, Relationship);
this.identity = identity;
this.start = start;
this.end = end;
this.type = type;
this.properties = properties;
}
(0, _createClass3.default)(Relationship, [{
key: "toString",
value: function toString() {
var s = "(" + this.start + ")-[:" + this.type;
var keys = (0, _keys2.default)(this.properties);
if (keys.length > 0) {
s += " {";
for (var i = 0; i < keys.length; i++) {
if (i > 0) s += ",";
s += keys[i] + ":" + (0, _stringify2.default)(this.properties[keys[i]]);
}
s += "}";
}
s += "]->(" + this.end + ")";
return s;
}
}]);
return Relationship;
}();
/**
* Class for UnboundRelationship Type.
* @access private
*/
var UnboundRelationship = function () {
/**
* @constructor
* @param {Integer} identity - Unique identity
* @param {string} type - Relationship type
* @param {Object} properties - Map with relationship properties
*/
function UnboundRelationship(identity, type, properties) {
(0, _classCallCheck3.default)(this, UnboundRelationship);
this.identity = identity;
this.type = type;
this.properties = properties;
}
/**
* Bind relationship
* @param {Integer} start - Identity of start node
* @param {Integer} end - Identity of end node
* @return {Relationship} - Created relationship
*/
(0, _createClass3.default)(UnboundRelationship, [{
key: "bind",
value: function bind(start, end) {
return new Relationship(this.identity, start, end, this.type, this.properties);
}
}, {
key: "toString",
value: function toString() {
var s = "-[:" + this.type;
var keys = (0, _keys2.default)(this.properties);
if (keys.length > 0) {
s += " {";
for (var i = 0; i < keys.length; i++) {
if (i > 0) s += ",";
s += keys[i] + ":" + (0, _stringify2.default)(this.properties[keys[i]]);
}
s += "}";
}
s += "]->";
return s;
}
}]);
return UnboundRelationship;
}();
/**
* Class for PathSegment Type.
*/
var PathSegment =
/**
* @constructor
* @param {Node} start - start node
* @param {Relationship} rel - relationship that connects start and end node
* @param {Node} end - end node
*/
function PathSegment(start, rel, end) {
(0, _classCallCheck3.default)(this, PathSegment);
this.start = start;
this.relationship = rel;
this.end = end;
};
/**
* Class for Path Type.
*/
var Path =
/**
* @constructor
* @param {Node} start - start node
* @param {Node} end - end node
* @param {Array<PathSegment>} segments - Array of Segments
*/
function Path(start, end, segments) {
(0, _classCallCheck3.default)(this, Path);
this.start = start;
this.end = end;
this.segments = segments;
this.length = segments.length;
};
exports.Node = Node;
exports.Relationship = Relationship;
exports.UnboundRelationship = UnboundRelationship;
exports.Path = Path;
exports.PathSegment = PathSegment;

349
node_modules/neo4j-driver/lib/v1/index.js generated vendored Normal file
View File

@@ -0,0 +1,349 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.temporal = exports.spatial = exports.error = exports.session = exports.types = exports.auth = exports.Neo4jError = exports.integer = exports.isDateTime = exports.isLocalDateTime = exports.isDate = exports.isTime = exports.isLocalTime = exports.isDuration = exports.isPoint = exports.isInt = exports.int = exports.driver = undefined;
var _integer = require('./integer');
var _graphTypes = require('./graph-types');
var _error = require('./error');
var _result = require('./result');
var _result2 = _interopRequireDefault(_result);
var _resultSummary = require('./result-summary');
var _resultSummary2 = _interopRequireDefault(_resultSummary);
var _record = require('./record');
var _record2 = _interopRequireDefault(_record);
var _driver = require('./driver');
var _routingDriver = require('./routing-driver');
var _routingDriver2 = _interopRequireDefault(_routingDriver);
var _version = require('../version');
var _version2 = _interopRequireDefault(_version);
var _util = require('./internal/util');
var _urlUtil = require('./internal/url-util');
var _urlUtil2 = _interopRequireDefault(_urlUtil);
var _httpDriver = require('./internal/http/http-driver');
var _httpDriver2 = _interopRequireDefault(_httpDriver);
var _spatialTypes = require('./spatial-types');
var _temporalTypes = require('./temporal-types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @property {function(username: string, password: string, realm: ?string)} basic the function to create a
* basic authentication token.
* @property {function(base64EncodedTicket: string)} kerberos the function to create a Kerberos authentication token.
* Accepts a single string argument - base64 encoded Kerberos ticket.
* @property {function(principal: string, credentials: string, realm: string, scheme: string, parameters: ?object)} custom
* the function to create a custom authentication token.
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var auth = {
basic: function basic(username, password) {
var realm = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
if (realm) {
return { scheme: 'basic', principal: username, credentials: password, realm: realm };
} else {
return { scheme: 'basic', principal: username, credentials: password };
}
},
kerberos: function kerberos(base64EncodedTicket) {
return {
scheme: 'kerberos',
principal: '', // This empty string is required for backwards compatibility.
credentials: base64EncodedTicket
};
},
custom: function custom(principal, credentials, realm, scheme) {
var parameters = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
if (parameters) {
return {
scheme: scheme, principal: principal, credentials: credentials, realm: realm,
parameters: parameters
};
} else {
return { scheme: scheme, principal: principal, credentials: credentials, realm: realm };
}
}
};
var USER_AGENT = "neo4j-javascript/" + _version2.default;
/**
* Construct a new Neo4j Driver. This is your main entry point for this
* library.
*
* ## Configuration
*
* This function optionally takes a configuration argument. Available configuration
* options are as follows:
*
* {
* // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF.
* encrypted: ENCRYPTION_ON|ENCRYPTION_OFF
*
* // Trust strategy to use if encryption is enabled. There is no mode to disable
* // trust other than disabling encryption altogether. The reason for
* // this is that if you don't know who you are talking to, it is easy for an
* // attacker to hijack your encrypted connection, rendering encryption pointless.
* //
* // TRUST_ALL_CERTIFICATES is the default choice for NodeJS deployments. It only requires
* // new host to provide a certificate and does no verification of the provided certificate.
* //
* // TRUST_ON_FIRST_USE is available for modern NodeJS deployments, and works
* // similarly to how `ssl` works - the first time we connect to a new host,
* // we remember the certificate they use. If the certificate ever changes, we
* // assume it is an attempt to hijack the connection and require manual intervention.
* // This means that by default, connections "just work" while still giving you
* // good encrypted protection.
* //
* // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is the classic approach to trust verification -
* // whenever we establish an encrypted connection, we ensure the host is using
* // an encryption certificate that is in, or is signed by, a certificate listed
* // as trusted. In the web bundle, this list of trusted certificates is maintained
* // by the web browser. In NodeJS, you configure the list with the next config option.
* //
* // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES means that you trust whatever certificates
* // are in the default certificate chain of th
* trust: "TRUST_ALL_CERTIFICATES" | "TRUST_ON_FIRST_USE" | "TRUST_SIGNED_CERTIFICATES" |
* "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES",
*
* // List of one or more paths to trusted encryption certificates. This only
* // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES".
* // The certificate files should be in regular X.509 PEM format.
* // For instance, ['./trusted.pem']
* trustedCertificates: [],
*
* // Path to a file where the driver saves hosts it has seen in the past, this is
* // very similar to the ssl tool's known_hosts file. Each time we connect to a
* // new host, a hash of their certificate is stored along with the domain name and
* // port, and this is then used to verify the host certificate does not change.
* // This setting has no effect unless TRUST_ON_FIRST_USE is enabled.
* knownHosts:"~/.neo4j/known_hosts",
*
* // The max number of connections that are allowed idle in the pool at any time.
* // Connection will be destroyed if this threshold is exceeded.
* // <b>Deprecated:</b> please use <code>maxConnectionPoolSize</code> instead.
* connectionPoolSize: 100,
*
* // The maximum total number of connections allowed to be managed by the connection pool, per host.
* // This includes both in-use and idle connections. No maximum connection pool size is imposed
* // by default.
* maxConnectionPoolSize: 100,
*
* // The maximum allowed lifetime for a pooled connection in milliseconds. Pooled connections older than this
* // threshold will be closed and removed from the pool. Such discarding happens during connection acquisition
* // so that new session is never backed by an old connection. Setting this option to a low value will cause
* // a high connection churn and might result in a performance hit. It is recommended to set maximum lifetime
* // to a slightly smaller value than the one configured in network equipment (load balancer, proxy, firewall,
* // etc. can also limit maximum connection lifetime). No maximum lifetime limit is imposed by default. Zero
* // and negative values result in lifetime not being checked.
* maxConnectionLifetime: 60 * 60 * 1000, // 1 hour
*
* // The maximum amount of time to wait to acquire a connection from the pool (to either create a new
* // connection or borrow an existing one.
* connectionAcquisitionTimeout: 60000, // 1 minute
*
* // Specify the maximum time in milliseconds transactions are allowed to retry via
* // <code>Session#readTransaction()</code> and <code>Session#writeTransaction()</code> functions.
* // These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient
* // errors with exponential backoff using initial delay of 1 second.
* // Default value is 30000 which is 30 seconds.
* maxTransactionRetryTime: 30000, // 30 seconds
*
* // Provide an alternative load balancing strategy for the routing driver to use.
* // Driver uses "least_connected" by default.
* // <b>Note:</b> We are experimenting with different strategies. This could be removed in the next minor
* // version.
* loadBalancingStrategy: "least_connected" | "round_robin",
*
* // Specify socket connection timeout in milliseconds. Numeric values are expected. Negative and zero values
* // result in no timeout being applied. Connection establishment will be then bound by the timeout configured
* // on the operating system level. Default value is 5000, which is 5 seconds.
* connectionTimeout: 5000, // 5 seconds
*
* // Make this driver always return native JavaScript numbers for integer values, instead of the
* // dedicated {@link Integer} class. Values that do not fit in native number bit range will be represented as
* // <code>Number.NEGATIVE_INFINITY</code> or <code>Number.POSITIVE_INFINITY</code>.
* // <b>Warning:</b> It is not always safe to enable this setting when JavaScript applications are not the only ones
* // interacting with the database. Stored numbers might in such case be not representable by native
* // {@link Number} type and thus driver will return lossy values. This might also happen when data was
* // initially imported using neo4j import tool and contained numbers larger than
* // <code>Number.MAX_SAFE_INTEGER</code>. Driver will then return positive infinity, which is lossy.
* // Default value for this option is <code>false</code> because native JavaScript numbers might result
* // in loss of precision in the general case.
* disableLosslessIntegers: false,
* }
*
* @param {string} url The URL for the Neo4j database, for instance "bolt://localhost"
* @param {Map<String,String>} authToken Authentication credentials. See {@link auth} for helpers.
* @param {Object} config Configuration object. See the configuration section above for details.
* @returns {Driver}
*/
function driver(url, authToken) {
var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
(0, _util.assertString)(url, 'Bolt URL');
var parsedUrl = _urlUtil2.default.parseDatabaseUrl(url);
if (parsedUrl.scheme === 'bolt+routing') {
return new _routingDriver2.default(parsedUrl.hostAndPort, parsedUrl.query, USER_AGENT, authToken, config);
} else if (parsedUrl.scheme === 'bolt') {
if (!(0, _util.isEmptyObjectOrNull)(parsedUrl.query)) {
throw new Error('Parameters are not supported with scheme \'bolt\'. Given URL: \'' + url + '\'');
}
return new _driver.Driver(parsedUrl.hostAndPort, USER_AGENT, authToken, config);
} else if (parsedUrl.scheme === 'http' || parsedUrl.scheme === 'https') {
return new _httpDriver2.default(parsedUrl, USER_AGENT, authToken, config);
} else {
throw new Error('Unknown scheme: ' + parsedUrl.scheme);
}
}
/**
* Object containing constructors for all neo4j types.
*/
var types = {
Node: _graphTypes.Node,
Relationship: _graphTypes.Relationship,
UnboundRelationship: _graphTypes.UnboundRelationship,
PathSegment: _graphTypes.PathSegment,
Path: _graphTypes.Path,
Result: _result2.default,
ResultSummary: _resultSummary2.default,
Record: _record2.default,
Point: _spatialTypes.Point,
Date: _temporalTypes.Date,
DateTime: _temporalTypes.DateTime,
Duration: _temporalTypes.Duration,
LocalDateTime: _temporalTypes.LocalDateTime,
LocalTime: _temporalTypes.LocalTime,
Time: _temporalTypes.Time
};
/**
* Object containing string constants representing session access modes.
*/
var session = {
READ: _driver.READ,
WRITE: _driver.WRITE
};
/**
* Object containing string constants representing predefined {@link Neo4jError} codes.
*/
var error = {
SERVICE_UNAVAILABLE: _error.SERVICE_UNAVAILABLE,
SESSION_EXPIRED: _error.SESSION_EXPIRED,
PROTOCOL_ERROR: _error.PROTOCOL_ERROR
};
/**
* Object containing functions to work with {@link Integer} objects.
*/
var integer = {
toNumber: _integer.toNumber,
toString: _integer.toString,
inSafeRange: _integer.inSafeRange
};
/**
* Object containing functions to work with spatial types, like {@link Point}.
*/
var spatial = {
isPoint: _spatialTypes.isPoint
};
/**
* Object containing functions to work with temporal types, like {@link Time} or {@link Duration}.
*/
var temporal = {
isDuration: _temporalTypes.isDuration,
isLocalTime: _temporalTypes.isLocalTime,
isTime: _temporalTypes.isTime,
isDate: _temporalTypes.isDate,
isLocalDateTime: _temporalTypes.isLocalDateTime,
isDateTime: _temporalTypes.isDateTime
};
/**
* @private
*/
var forExport = {
driver: driver,
int: _integer.int,
isInt: _integer.isInt,
isPoint: _spatialTypes.isPoint,
isDuration: _temporalTypes.isDuration,
isLocalTime: _temporalTypes.isLocalTime,
isTime: _temporalTypes.isTime,
isDate: _temporalTypes.isDate,
isLocalDateTime: _temporalTypes.isLocalDateTime,
isDateTime: _temporalTypes.isDateTime,
integer: integer,
Neo4jError: _error.Neo4jError,
auth: auth,
types: types,
session: session,
error: error,
spatial: spatial,
temporal: temporal
};
exports.driver = driver;
exports.int = _integer.int;
exports.isInt = _integer.isInt;
exports.isPoint = _spatialTypes.isPoint;
exports.isDuration = _temporalTypes.isDuration;
exports.isLocalTime = _temporalTypes.isLocalTime;
exports.isTime = _temporalTypes.isTime;
exports.isDate = _temporalTypes.isDate;
exports.isLocalDateTime = _temporalTypes.isLocalDateTime;
exports.isDateTime = _temporalTypes.isDateTime;
exports.integer = integer;
exports.Neo4jError = _error.Neo4jError;
exports.auth = auth;
exports.types = types;
exports.session = session;
exports.error = error;
exports.spatial = spatial;
exports.temporal = temporal;
exports.default = forExport;

1000
node_modules/neo4j-driver/lib/v1/integer.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

183
node_modules/neo4j-driver/lib/v1/internal/bookmark.js generated vendored Normal file
View File

@@ -0,0 +1,183 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _util = require('./util');
var util = _interopRequireWildcard(_util);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var BOOKMARK_KEY = 'bookmark'; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var BOOKMARKS_KEY = 'bookmarks';
var BOOKMARK_PREFIX = 'neo4j:bookmark:v1:tx';
var UNKNOWN_BOOKMARK_VALUE = -1;
var Bookmark = function () {
/**
* @constructor
* @param {string|string[]} values single bookmark as string or multiple bookmarks as a string array.
*/
function Bookmark(values) {
(0, _classCallCheck3.default)(this, Bookmark);
this._values = asStringArray(values);
this._maxValue = maxBookmark(this._values);
}
/**
* Check if the given bookmark is meaningful and can be send to the database.
* @return {boolean} returns <code>true</code> bookmark has a value, <code>false</code> otherwise.
*/
(0, _createClass3.default)(Bookmark, [{
key: 'isEmpty',
value: function isEmpty() {
return this._maxValue === null;
}
/**
* Get maximum value of this bookmark as string.
* @return {string|null} the maximum value or <code>null</code> if it is not defined.
*/
}, {
key: 'maxBookmarkAsString',
value: function maxBookmarkAsString() {
return this._maxValue;
}
/**
* Get this bookmark as an object for begin transaction call.
* @return {object} the value of this bookmark as object.
*/
}, {
key: 'asBeginTransactionParameters',
value: function asBeginTransactionParameters() {
var _ref;
if (this.isEmpty()) {
return {};
}
// Driver sends {bookmark: "max", bookmarks: ["one", "two", "max"]} instead of simple
// {bookmarks: ["one", "two", "max"]} for backwards compatibility reasons. Old servers can only accept single
// bookmark that is why driver has to parse and compare given list of bookmarks. This functionality will
// eventually be removed.
return _ref = {}, (0, _defineProperty3.default)(_ref, BOOKMARK_KEY, this._maxValue), (0, _defineProperty3.default)(_ref, BOOKMARKS_KEY, this._values), _ref;
}
}]);
return Bookmark;
}();
/**
* Converts given value to an array.
* @param {string|string[]} [value=undefined] argument to convert.
* @return {string[]} value converted to an array.
*/
exports.default = Bookmark;
function asStringArray(value) {
if (!value) {
return [];
}
if (util.isString(value)) {
return [value];
}
if (Array.isArray(value)) {
var result = [];
for (var i = 0; i < value.length; i++) {
var element = value[i];
// if it is undefined or null, ignore it
if (element !== undefined && element !== null) {
if (!util.isString(element)) {
throw new TypeError('Bookmark should be a string, given: \'' + element + '\'');
}
result.push(element);
}
}
return result;
}
throw new TypeError('Bookmark should either be a string or a string array, given: \'' + value + '\'');
}
/**
* Find latest bookmark in the given array of bookmarks.
* @param {string[]} bookmarks array of bookmarks.
* @return {string|null} latest bookmark value.
*/
function maxBookmark(bookmarks) {
if (!bookmarks || bookmarks.length === 0) {
return null;
}
var maxBookmark = bookmarks[0];
var maxValue = bookmarkValue(maxBookmark);
for (var i = 1; i < bookmarks.length; i++) {
var bookmark = bookmarks[i];
var value = bookmarkValue(bookmark);
if (value > maxValue) {
maxBookmark = bookmark;
maxValue = value;
}
}
return maxBookmark;
}
/**
* Calculate numeric value for the given bookmark.
* @param {string} bookmark argument to get numeric value for.
* @return {number} value of the bookmark.
*/
function bookmarkValue(bookmark) {
if (bookmark && bookmark.indexOf(BOOKMARK_PREFIX) === 0) {
var result = parseInt(bookmark.substring(BOOKMARK_PREFIX.length));
return result ? result : UNKNOWN_BOOKMARK_VALUE;
}
return UNKNOWN_BOOKMARK_VALUE;
}

794
node_modules/neo4j-driver/lib/v1/internal/buf.js generated vendored Normal file
View File

@@ -0,0 +1,794 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.alloc = exports.NodeBuffer = exports.CombinedBuffer = exports.SliceBuffer = exports.HeapBuffer = exports.BaseBuffer = undefined;
var _get2 = require("babel-runtime/helpers/get");
var _get3 = _interopRequireDefault(_get2);
var _getPrototypeOf = require("babel-runtime/core-js/object/get-prototype-of");
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** This module defines a common API for dealing with binary data that
* works for both browsers (via ArrayBuffer/DataView) and for NodeJS
*(via Buffer API).
*/
var _node = require("buffer");
/**
* Common base with default implementation for most buffer methods.
* Buffers are stateful - they track a current "position", this helps greatly
* when reading and writing from them incrementally. You can also ignore the
* stateful read/write methods.
* readXXX and writeXXX-methods move the inner position of the buffer.
* putXXX and getXXX-methods do not.
* @access private
*/
var BaseBuffer = function () {
/**
* Create a instance with the injected size.
* @constructor
* @param {Integer} size
*/
function BaseBuffer(size) {
(0, _classCallCheck3.default)(this, BaseBuffer);
this.position = 0;
this.length = size;
// Calling these out - this is the required
// methods a subclass needs to implement
var getUInt8 = null;
var getInt8 = null;
var getFloat64 = null;
var getSlice = null;
var putFloat64 = null;
var putUInt8 = null;
var putInt8 = null;
}
/**
* @param p
*/
(0, _createClass3.default)(BaseBuffer, [{
key: "getInt16",
value: function getInt16(p) {
return this.getInt8(p) << 8 | this.getUInt8(p + 1);
}
/**
* @param p
*/
}, {
key: "getUInt16",
value: function getUInt16(p) {
return this.getUInt8(p) << 8 | this.getUInt8(p + 1);
}
/**
* @param p
*/
}, {
key: "getInt32",
value: function getInt32(p) {
return this.getInt8(p) << 24 | this.getUInt8(p + 1) << 16 | this.getUInt8(p + 2) << 8 | this.getUInt8(p + 3);
}
/**
* @param p
*/
}, {
key: "getUInt32",
value: function getUInt32(p) {
return this.getUInt8(p) << 24 | this.getUInt8(p + 1) << 16 | this.getUInt8(p + 2) << 8 | this.getUInt8(p + 3);
}
/**
* @param p
*/
}, {
key: "getInt64",
value: function getInt64(p) {
return this.getInt8(p) << 56 | this.getUInt8(p + 1) << 48 | this.getUInt8(p + 2) << 40 | this.getUInt8(p + 3) << 32 | this.getUInt8(p + 4) << 24 | this.getUInt8(p + 5) << 16 | this.getUInt8(p + 6) << 8 | this.getUInt8(p + 7);
}
/**
* Get a slice of this buffer. This method does not copy any data,
* but simply provides a slice view of this buffer
* @param start
* @param length
*/
}, {
key: "getSlice",
value: function getSlice(start, length) {
return new SliceBuffer(start, length, this);
}
/**
* @param p
* @param val
*/
}, {
key: "putInt16",
value: function putInt16(p, val) {
this.putInt8(p, val >> 8);
this.putUInt8(p + 1, val & 0xFF);
}
/**
* @param p
* @param val
*/
}, {
key: "putUInt16",
value: function putUInt16(p, val) {
this.putUInt8(p, val >> 8 & 0xFF);
this.putUInt8(p + 1, val & 0xFF);
}
/**
* @param p
* @param val
*/
}, {
key: "putInt32",
value: function putInt32(p, val) {
this.putInt8(p, val >> 24);
this.putUInt8(p + 1, val >> 16 & 0xFF);
this.putUInt8(p + 2, val >> 8 & 0xFF);
this.putUInt8(p + 3, val & 0xFF);
}
/**
* @param p
* @param val
*/
}, {
key: "putUInt32",
value: function putUInt32(p, val) {
this.putUInt8(p, val >> 24 & 0xFF);
this.putUInt8(p + 1, val >> 16 & 0xFF);
this.putUInt8(p + 2, val >> 8 & 0xFF);
this.putUInt8(p + 3, val & 0xFF);
}
/**
* @param p
* @param val
*/
}, {
key: "putInt64",
value: function putInt64(p, val) {
this.putInt8(p, val >> 48);
this.putUInt8(p + 1, val >> 42 & 0xFF);
this.putUInt8(p + 2, val >> 36 & 0xFF);
this.putUInt8(p + 3, val >> 30 & 0xFF);
this.putUInt8(p + 4, val >> 24 & 0xFF);
this.putUInt8(p + 5, val >> 16 & 0xFF);
this.putUInt8(p + 6, val >> 8 & 0xFF);
this.putUInt8(p + 7, val & 0xFF);
}
/**
* @param position
* @param other
*/
}, {
key: "putBytes",
value: function putBytes(position, other) {
for (var i = 0, end = other.remaining(); i < end; i++) {
this.putUInt8(position + i, other.readUInt8());
}
}
/**
* Read from state position.
*/
}, {
key: "readUInt8",
value: function readUInt8() {
return this.getUInt8(this._updatePos(1));
}
/**
* Read from state position.
*/
}, {
key: "readInt8",
value: function readInt8() {
return this.getInt8(this._updatePos(1));
}
/**
* Read from state position.
*/
}, {
key: "readUInt16",
value: function readUInt16() {
return this.getUInt16(this._updatePos(2));
}
/**
* Read from state position.
*/
}, {
key: "readUInt32",
value: function readUInt32() {
return this.getUInt32(this._updatePos(4));
}
/**
* Read from state position.
*/
}, {
key: "readInt16",
value: function readInt16() {
return this.getInt16(this._updatePos(2));
}
/**
* Read from state position.
*/
}, {
key: "readInt32",
value: function readInt32() {
return this.getInt32(this._updatePos(4));
}
/**
* Read from state position.
*/
}, {
key: "readInt64",
value: function readInt64() {
return this.getInt32(this._updatePos(8));
}
/**
* Read from state position.
*/
}, {
key: "readFloat64",
value: function readFloat64() {
return this.getFloat64(this._updatePos(8));
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeUInt8",
value: function writeUInt8(val) {
this.putUInt8(this._updatePos(1), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeInt8",
value: function writeInt8(val) {
this.putInt8(this._updatePos(1), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeInt16",
value: function writeInt16(val) {
this.putInt16(this._updatePos(2), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeInt32",
value: function writeInt32(val) {
this.putInt32(this._updatePos(4), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeUInt32",
value: function writeUInt32(val) {
this.putUInt32(this._updatePos(4), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeInt64",
value: function writeInt64(val) {
this.putInt64(this._updatePos(8), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeFloat64",
value: function writeFloat64(val) {
this.putFloat64(this._updatePos(8), val);
}
/**
* Write to state position.
* @param val
*/
}, {
key: "writeBytes",
value: function writeBytes(val) {
this.putBytes(this._updatePos(val.remaining()), val);
}
/**
* Get a slice of this buffer. This method does not copy any data,
* but simply provides a slice view of this buffer
* @param length
*/
}, {
key: "readSlice",
value: function readSlice(length) {
return this.getSlice(this._updatePos(length), length);
}
}, {
key: "_updatePos",
value: function _updatePos(length) {
var p = this.position;
this.position += length;
return p;
}
/**
* Get remaining
*/
}, {
key: "remaining",
value: function remaining() {
return this.length - this.position;
}
/**
* Has remaining
*/
}, {
key: "hasRemaining",
value: function hasRemaining() {
return this.remaining() > 0;
}
/**
* Reset position state
*/
}, {
key: "reset",
value: function reset() {
this.position = 0;
}
/**
* Get string representation of buffer and it's state.
* @return {string} Buffer as a string
*/
}, {
key: "toString",
value: function toString() {
return this.constructor.name + "( position=" + this.position + " )\n " + this.toHex();
}
/**
* Get string representation of buffer.
* @return {string} Buffer as a string
*/
}, {
key: "toHex",
value: function toHex() {
// TODO something like StringBuilder?
var out = "";
for (var i = 0; i < this.length; i++) {
var hexByte = this.getUInt8(i).toString(16);
if (hexByte.length == 1) {
hexByte = "0" + hexByte;
}
out += hexByte + " ";
}
return out;
}
}]);
return BaseBuffer;
}();
/**
* Basic buffer implementation that should work in most any modern JS env.
* @access private
*/
var HeapBuffer = function (_BaseBuffer) {
(0, _inherits3.default)(HeapBuffer, _BaseBuffer);
function HeapBuffer(arg) {
(0, _classCallCheck3.default)(this, HeapBuffer);
var buffer = arg instanceof ArrayBuffer ? arg : new ArrayBuffer(arg);
var _this = (0, _possibleConstructorReturn3.default)(this, (HeapBuffer.__proto__ || (0, _getPrototypeOf2.default)(HeapBuffer)).call(this, buffer.byteLength));
_this._buffer = buffer;
_this._view = new DataView(_this._buffer);
return _this;
}
(0, _createClass3.default)(HeapBuffer, [{
key: "putUInt8",
value: function putUInt8(position, val) {
this._view.setUint8(position, val);
}
}, {
key: "getUInt8",
value: function getUInt8(position) {
return this._view.getUint8(position);
}
}, {
key: "putInt8",
value: function putInt8(position, val) {
this._view.setInt8(position, val);
}
}, {
key: "getInt8",
value: function getInt8(position) {
return this._view.getInt8(position);
}
}, {
key: "getFloat64",
value: function getFloat64(position) {
return this._view.getFloat64(position);
}
}, {
key: "putFloat64",
value: function putFloat64(position, val) {
this._view.setFloat64(position, val);
}
}, {
key: "getSlice",
value: function getSlice(start, length) {
if (this._buffer.slice) {
return new HeapBuffer(this._buffer.slice(start, start + length));
} else {
// Some platforms (eg. phantomjs) don't support slice, so fall back to a copy
// We do this rather than return a SliceBuffer, because sliceBuffer cannot
// be passed to native network write ops etc - we need ArrayBuffer for that
var copy = new HeapBuffer(length);
for (var i = 0; i < length; i++) {
copy.putUInt8(i, this.getUInt8(i + start));
}
return copy;
}
}
/**
* Specific to HeapBuffer, this gets a DataView from the
* current position and of the specified length.
*/
}, {
key: "readView",
value: function readView(length) {
return new DataView(this._buffer, this._updatePos(length), length);
}
}]);
return HeapBuffer;
}(BaseBuffer);
/**
* Represents a view as slice of another buffer.
* @access private
*/
var SliceBuffer = function (_BaseBuffer2) {
(0, _inherits3.default)(SliceBuffer, _BaseBuffer2);
function SliceBuffer(start, length, inner) {
(0, _classCallCheck3.default)(this, SliceBuffer);
var _this2 = (0, _possibleConstructorReturn3.default)(this, (SliceBuffer.__proto__ || (0, _getPrototypeOf2.default)(SliceBuffer)).call(this, length));
_this2._start = start;
_this2._inner = inner;
return _this2;
}
(0, _createClass3.default)(SliceBuffer, [{
key: "putUInt8",
value: function putUInt8(position, val) {
this._inner.putUInt8(this._start + position, val);
}
}, {
key: "getUInt8",
value: function getUInt8(position) {
return this._inner.getUInt8(this._start + position);
}
}, {
key: "putInt8",
value: function putInt8(position, val) {
this._inner.putInt8(this._start + position, val);
}
}, {
key: "putFloat64",
value: function putFloat64(position, val) {
this._inner.putFloat64(this._start + position, val);
}
}, {
key: "getInt8",
value: function getInt8(position) {
return this._inner.getInt8(this._start + position);
}
}, {
key: "getFloat64",
value: function getFloat64(position) {
return this._inner.getFloat64(this._start + position);
}
}]);
return SliceBuffer;
}(BaseBuffer);
/**
* Buffer that combines multiple buffers, exposing them as one single buffer.
* @access private
*/
var CombinedBuffer = function (_BaseBuffer3) {
(0, _inherits3.default)(CombinedBuffer, _BaseBuffer3);
function CombinedBuffer(buffers) {
(0, _classCallCheck3.default)(this, CombinedBuffer);
var length = 0;
for (var i = 0; i < buffers.length; i++) {
length += buffers[i].length;
}
var _this3 = (0, _possibleConstructorReturn3.default)(this, (CombinedBuffer.__proto__ || (0, _getPrototypeOf2.default)(CombinedBuffer)).call(this, length));
_this3._buffers = buffers;
return _this3;
}
(0, _createClass3.default)(CombinedBuffer, [{
key: "getUInt8",
value: function getUInt8(position) {
// Surely there's a faster way to do this.. some sort of lookup table thing?
for (var i = 0; i < this._buffers.length; i++) {
var buffer = this._buffers[i];
// If the position is not in the current buffer, skip the current buffer
if (position >= buffer.length) {
position -= buffer.length;
} else {
return buffer.getUInt8(position);
}
}
}
}, {
key: "getInt8",
value: function getInt8(position) {
// Surely there's a faster way to do this.. some sort of lookup table thing?
for (var i = 0; i < this._buffers.length; i++) {
var buffer = this._buffers[i];
// If the position is not in the current buffer, skip the current buffer
if (position >= buffer.length) {
position -= buffer.length;
} else {
return buffer.getInt8(position);
}
}
}
}, {
key: "getFloat64",
value: function getFloat64(position) {
// At some point, a more efficient impl. For now, we copy the 8 bytes
// we want to read and depend on the platform impl of IEEE 754.
var b = alloc(8);
for (var i = 0; i < 8; i++) {
b.putUInt8(i, this.getUInt8(position + i));
};
return b.getFloat64(0);
}
}]);
return CombinedBuffer;
}(BaseBuffer);
/**
* Buffer used in a Node.js environment
* @access private
*/
var NodeBuffer = function (_BaseBuffer4) {
(0, _inherits3.default)(NodeBuffer, _BaseBuffer4);
function NodeBuffer(arg) {
(0, _classCallCheck3.default)(this, NodeBuffer);
var buffer = arg instanceof _node.Buffer ? arg : newNodeJSBuffer(arg);
var _this4 = (0, _possibleConstructorReturn3.default)(this, (NodeBuffer.__proto__ || (0, _getPrototypeOf2.default)(NodeBuffer)).call(this, buffer.length));
_this4._buffer = buffer;
return _this4;
}
(0, _createClass3.default)(NodeBuffer, [{
key: "getUInt8",
value: function getUInt8(position) {
return this._buffer.readUInt8(position);
}
}, {
key: "getInt8",
value: function getInt8(position) {
return this._buffer.readInt8(position);
}
}, {
key: "getFloat64",
value: function getFloat64(position) {
return this._buffer.readDoubleBE(position);
}
}, {
key: "putUInt8",
value: function putUInt8(position, val) {
this._buffer.writeUInt8(val, position);
}
}, {
key: "putInt8",
value: function putInt8(position, val) {
this._buffer.writeInt8(val, position);
}
}, {
key: "putFloat64",
value: function putFloat64(position, val) {
this._buffer.writeDoubleBE(val, position);
}
}, {
key: "putBytes",
value: function putBytes(position, val) {
if (val instanceof NodeBuffer) {
var bytesToCopy = Math.min(val.length - val.position, this.length - position);
val._buffer.copy(this._buffer, position, val.position, val.position + bytesToCopy);
val.position += bytesToCopy;
} else {
(0, _get3.default)(NodeBuffer.prototype.__proto__ || (0, _getPrototypeOf2.default)(NodeBuffer.prototype), "putBytes", this).call(this, position, val);
}
}
}, {
key: "getSlice",
value: function getSlice(start, length) {
return new NodeBuffer(this._buffer.slice(start, start + length));
}
}]);
return NodeBuffer;
}(BaseBuffer);
function newNodeJSBuffer(arg) {
if (typeof arg === 'number' && typeof _node.Buffer.alloc === 'function') {
// use static factory function present in newer NodeJS versions to allocate new buffer with specified size
return _node.Buffer.alloc(arg);
} else {
// fallback to the old, potentially deprecated constructor
return new _node.Buffer(arg);
}
}
// Use HeapBuffer by default, unless Buffer API is available, see below
var _DefaultBuffer = HeapBuffer;
try {
// This will throw an exception if we're not running on NodeJS or equivalent
require.resolve("buffer");
_DefaultBuffer = NodeBuffer;
} catch (e) {}
/**
* Allocate a new buffer using whatever mechanism is most sensible for the
* current platform
* @access private
* @param {Integer} size
* @return new buffer
*/
function alloc(size) {
return new _DefaultBuffer(size);
}
exports.BaseBuffer = BaseBuffer;
exports.HeapBuffer = HeapBuffer;
exports.SliceBuffer = SliceBuffer;
exports.CombinedBuffer = CombinedBuffer;
exports.NodeBuffer = NodeBuffer;
exports.alloc = alloc;

101
node_modules/neo4j-driver/lib/v1/internal/ch-config.js generated vendored Normal file
View File

@@ -0,0 +1,101 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _features = require('./features');
var _features2 = _interopRequireDefault(_features);
var _error = require('../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_CONNECTION_TIMEOUT_MILLIS = 5000; // 5 seconds by default
var ChannelConfig =
/**
* @constructor
* @param {Url} url the URL for the channel to connect to.
* @param {object} driverConfig the driver config provided by the user when driver is created.
* @param {string} connectionErrorCode the default error code to use on connection errors.
*/
function ChannelConfig(url, driverConfig, connectionErrorCode) {
(0, _classCallCheck3.default)(this, ChannelConfig);
this.url = url;
this.encrypted = extractEncrypted(driverConfig);
this.trust = extractTrust(driverConfig);
this.trustedCertificates = extractTrustedCertificates(driverConfig);
this.knownHostsPath = extractKnownHostsPath(driverConfig);
this.connectionErrorCode = connectionErrorCode || _error.SERVICE_UNAVAILABLE;
this.connectionTimeout = extractConnectionTimeout(driverConfig);
};
exports.default = ChannelConfig;
function extractEncrypted(driverConfig) {
// check if encryption was configured by the user, use explicit null check because we permit boolean value
var encryptionConfigured = driverConfig.encrypted == null;
// default to using encryption if trust-all-certificates is available
return encryptionConfigured ? (0, _features2.default)('trust_all_certificates') : driverConfig.encrypted;
}
function extractTrust(driverConfig) {
if (driverConfig.trust) {
return driverConfig.trust;
}
// default to using TRUST_ALL_CERTIFICATES if it is available
return (0, _features2.default)('trust_all_certificates') ? 'TRUST_ALL_CERTIFICATES' : 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES';
}
function extractTrustedCertificates(driverConfig) {
return driverConfig.trustedCertificates || [];
}
function extractKnownHostsPath(driverConfig) {
return driverConfig.knownHosts || null;
}
function extractConnectionTimeout(driverConfig) {
var configuredTimeout = parseInt(driverConfig.connectionTimeout, 10);
if (configuredTimeout === 0) {
// timeout explicitly configured to 0
return null;
} else if (configuredTimeout && configuredTimeout < 0) {
// timeout explicitly configured to a negative value
return null;
} else if (!configuredTimeout) {
// timeout not configured, use default value
return DEFAULT_CONNECTION_TIMEOUT_MILLIS;
} else {
// timeout configured, use the provided value
return configuredTimeout;
}
}

101
node_modules/neo4j-driver/lib/v1/internal/ch-dummy.js generated vendored Normal file
View File

@@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.observer = exports.channel = undefined;
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
var _buf = require("./buf");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var observer = {
instance: null,
updateInstance: function updateInstance(instance) {
observer.instance = instance;
}
}; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DummyChannel = function () {
/**
* @constructor
* @param {ChannelConfig} config - configuration for the new channel.
*/
function DummyChannel(config) {
(0, _classCallCheck3.default)(this, DummyChannel);
this.written = [];
}
(0, _createClass3.default)(DummyChannel, [{
key: "isEncrypted",
value: function isEncrypted() {
return false;
}
}, {
key: "write",
value: function write(buf) {
this.written.push(buf);
observer.updateInstance(this);
}
}, {
key: "toHex",
value: function toHex() {
var out = "";
for (var i = 0; i < this.written.length; i++) {
out += this.written[i].toHex();
}
return out;
}
}, {
key: "toBuffer",
value: function toBuffer() {
return new _buf.CombinedBuffer(this.written);
}
}, {
key: "close",
value: function close(cb) {
this.clear();
if (cb) {
return cb();
}
}
}, {
key: "clear",
value: function clear() {
this.written = [];
}
}]);
return DummyChannel;
}();
var channel = DummyChannel;
exports.channel = channel;
exports.observer = observer;

430
node_modules/neo4j-driver/lib/v1/internal/ch-node.js generated vendored Normal file
View File

@@ -0,0 +1,430 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _net = require('net');
var _net2 = _interopRequireDefault(_net);
var _tls = require('tls');
var _tls2 = _interopRequireDefault(_tls);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _os = require('os');
var _buf = require('./buf');
var _util = require('./util');
var _error = require('./../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var _CONNECTION_IDGEN = 0;
function userHome() {
// For some reason, Browserify chokes on shimming `process`. This code
// will never get executed on the browser anyway, to just hack around it
var getOutOfHereBrowserifyYoureDrunk = require;
var process = getOutOfHereBrowserifyYoureDrunk('process');
return process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME'];
}
function mkFullPath(pathToCreate) {
try {
_fs2.default.mkdirSync(pathToCreate);
} catch (e) {
if (e.code === 'ENOENT') {
// Create parent dir
mkFullPath(_path2.default.dirname(pathToCreate));
// And now try again
mkFullPath(pathToCreate);
return;
}
if (e.code === 'EEXIST') {
return;
}
throw e;
}
}
function loadFingerprint(serverId, knownHostsPath, cb) {
try {
_fs2.default.accessSync(knownHostsPath);
} catch (e) {
return cb(null);
}
var found = false;
require('readline').createInterface({
input: _fs2.default.createReadStream(knownHostsPath)
}).on('line', function (line) {
if (!found && line.startsWith(serverId)) {
found = true;
cb(line.split(" ")[1]);
}
}).on('close', function () {
if (!found) {
cb(null);
}
});
}
var _lockFingerprintFromAppending = {};
function storeFingerprint(serverId, knownHostsPath, fingerprint, cb) {
// we check if the serverId has been appended
if (!!_lockFingerprintFromAppending[serverId]) {
// if it has, we ignore it
return cb(null);
}
// we make the line as appended
// ( 1 is more efficient to store than true because true is an oddball )
_lockFingerprintFromAppending[serverId] = 1;
// If file doesn't exist, create full path to it
try {
_fs2.default.accessSync(knownHostsPath);
} catch (_) {
mkFullPath(_path2.default.dirname(knownHostsPath));
}
_fs2.default.appendFile(knownHostsPath, serverId + " " + fingerprint + _os.EOL, "utf8", function (err) {
delete _lockFingerprintFromAppending[serverId];
if (err) {
console.log(err);
}
return cb(err);
});
}
var TrustStrategy = {
/**
* @deprecated Since version 1.0. Will be deleted in a future version. {@link #TRUST_CUSTOM_CA_SIGNED_CERTIFICATES}.
*/
TRUST_SIGNED_CERTIFICATES: function TRUST_SIGNED_CERTIFICATES(config, onSuccess, onFailure) {
console.warn('`TRUST_SIGNED_CERTIFICATES` has been deprecated as option and will be removed in a future version of ' + "the driver. Please use `TRUST_CUSTOM_CA_SIGNED_CERTIFICATES` instead.");
return TrustStrategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure);
},
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES: function TRUST_CUSTOM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure) {
if (!config.trustedCertificates || config.trustedCertificates.length === 0) {
onFailure((0, _error.newError)("You are using TRUST_CUSTOM_CA_SIGNED_CERTIFICATES as the method " + "to verify trust for encrypted connections, but have not configured any " + "trustedCertificates. You must specify the path to at least one trusted " + "X.509 certificate for this to work. Two other alternatives is to use " + "TRUST_ALL_CERTIFICATES or to disable encryption by setting encrypted=\"" + _util.ENCRYPTION_OFF + "\"" + "in your driver configuration."));
return;
}
var tlsOpts = {
ca: config.trustedCertificates.map(function (f) {
return _fs2.default.readFileSync(f);
}),
// Because we manually check for this in the connect callback, to give
// a more helpful error to the user
rejectUnauthorized: false
};
var socket = _tls2.default.connect(config.url.port, config.url.host, tlsOpts, function () {
if (!socket.authorized) {
onFailure((0, _error.newError)("Server certificate is not trusted. If you trust the database you are connecting to, add" + " the signing certificate, or the server certificate, to the list of certificates trusted by this driver" + " using `neo4j.v1.driver(.., { trustedCertificates:['path/to/certificate.crt']}). This " + " is a security measure to protect against man-in-the-middle attacks. If you are just trying " + " Neo4j out and are not concerned about encryption, simply disable it using `encrypted=\"" + _util.ENCRYPTION_OFF + "\"`" + " in the driver options. Socket responded with: " + socket.authorizationError));
} else {
onSuccess();
}
});
socket.on('error', onFailure);
return socket;
},
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES: function TRUST_SYSTEM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure) {
var tlsOpts = {
// Because we manually check for this in the connect callback, to give
// a more helpful error to the user
rejectUnauthorized: false
};
var socket = _tls2.default.connect(config.url.port, config.url.host, tlsOpts, function () {
if (!socket.authorized) {
onFailure((0, _error.newError)("Server certificate is not trusted. If you trust the database you are connecting to, use " + "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES and add" + " the signing certificate, or the server certificate, to the list of certificates trusted by this driver" + " using `neo4j.v1.driver(.., { trustedCertificates:['path/to/certificate.crt']}). This " + " is a security measure to protect against man-in-the-middle attacks. If you are just trying " + " Neo4j out and are not concerned about encryption, simply disable it using `encrypted=\"" + _util.ENCRYPTION_OFF + "\"`" + " in the driver options. Socket responded with: " + socket.authorizationError));
} else {
onSuccess();
}
});
socket.on('error', onFailure);
return socket;
},
/**
* @deprecated in 1.1 in favour of {@link #TRUST_ALL_CERTIFICATES}. Will be deleted in a future version.
*/
TRUST_ON_FIRST_USE: function TRUST_ON_FIRST_USE(config, onSuccess, onFailure) {
console.warn('`TRUST_ON_FIRST_USE` has been deprecated as option and will be removed in a future version of ' + "the driver. Please use `TRUST_ALL_CERTIFICATES` instead.");
var tlsOpts = {
// Because we manually verify the certificate against known_hosts
rejectUnauthorized: false
};
var socket = _tls2.default.connect(config.url.port, config.url.host, tlsOpts, function () {
var serverCert = socket.getPeerCertificate( /*raw=*/true);
if (!serverCert.raw) {
// If `raw` is not available, we're on an old version of NodeJS, and
// the raw cert cannot be accessed (or, at least I couldn't find a way to)
// therefore, we can't generate a SHA512 fingerprint, meaning we can't
// do TOFU, and the safe approach is to fail.
onFailure((0, _error.newError)("You are using a version of NodeJS that does not " + "support trust-on-first use encryption. You can either upgrade NodeJS to " + "a newer version, use `trust:TRUST_CUSTOM_CA_SIGNED_CERTIFICATES` in your driver " + "config instead, or disable encryption using `encrypted:\"" + _util.ENCRYPTION_OFF + "\"`."));
return;
}
var serverFingerprint = require('crypto').createHash('sha512').update(serverCert.raw).digest("hex");
var knownHostsPath = config.knownHostsPath || _path2.default.join(userHome(), ".neo4j", "known_hosts");
var serverId = config.url.hostAndPort;
loadFingerprint(serverId, knownHostsPath, function (knownFingerprint) {
if (knownFingerprint === serverFingerprint) {
onSuccess();
} else if (knownFingerprint == null) {
storeFingerprint(serverId, knownHostsPath, serverFingerprint, function (err) {
if (err) {
return onFailure(err);
}
return onSuccess();
});
} else {
onFailure((0, _error.newError)("Database encryption certificate has changed, and no longer " + "matches the certificate stored for " + serverId + " in `" + knownHostsPath + "`. As a security precaution, this driver will not automatically trust the new " + "certificate, because doing so would allow an attacker to pretend to be the Neo4j " + "instance we want to connect to. The certificate provided by the server looks like: " + serverCert + ". If you trust that this certificate is valid, simply remove the line " + "starting with " + serverId + " in `" + knownHostsPath + "`, and the driver will " + "update the file with the new certificate. You can configure which file the driver " + "should use to store this information by setting `knownHosts` to another path in " + "your driver configuration - and you can disable encryption there as well using " + "`encrypted:\"" + _util.ENCRYPTION_OFF + "\"`."));
}
});
});
socket.on('error', onFailure);
return socket;
},
TRUST_ALL_CERTIFICATES: function TRUST_ALL_CERTIFICATES(config, onSuccess, onFailure) {
var tlsOpts = {
rejectUnauthorized: false
};
var socket = _tls2.default.connect(config.url.port, config.url.host, tlsOpts, function () {
var certificate = socket.getPeerCertificate();
if ((0, _util.isEmptyObjectOrNull)(certificate)) {
onFailure((0, _error.newError)("Secure connection was successful but server did not return any valid " + "certificates. Such connection can not be trusted. If you are just trying " + " Neo4j out and are not concerned about encryption, simply disable it using " + "`encrypted=\"" + _util.ENCRYPTION_OFF + "\"` in the driver options. " + "Socket responded with: " + socket.authorizationError));
} else {
onSuccess();
}
});
socket.on('error', onFailure);
return socket;
}
};
/**
* Connect using node socket.
* @param {ChannelConfig} config - configuration of this channel.
* @param {function} onSuccess - callback to execute on connection success.
* @param {function} onFailure - callback to execute on connection failure.
* @return {*} socket connection.
*/
function connect(config, onSuccess) {
var onFailure = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {
return null;
};
//still allow boolean for backwards compatibility
if (config.encrypted === false || config.encrypted === _util.ENCRYPTION_OFF) {
var conn = _net2.default.connect(config.url.port, config.url.host, onSuccess);
conn.on('error', onFailure);
return conn;
} else if (TrustStrategy[config.trust]) {
return TrustStrategy[config.trust](config, onSuccess, onFailure);
} else {
onFailure((0, _error.newError)("Unknown trust strategy: " + config.trust + ". Please use either " + "trust:'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' or trust:'TRUST_ALL_CERTIFICATES' in your driver " + "configuration. Alternatively, you can disable encryption by setting " + "`encrypted:\"" + _util.ENCRYPTION_OFF + "\"`. There is no mechanism to use encryption without trust verification, " + "because this incurs the overhead of encryption without improving security. If " + "the driver does not verify that the peer it is connected to is really Neo4j, it " + "is very easy for an attacker to bypass the encryption by pretending to be Neo4j."));
}
}
/**
* In a Node.js environment the 'net' module is used
* as transport.
* @access private
*/
var NodeChannel = function () {
/**
* Create new instance
* @param {ChannelConfig} config - configuration for this channel.
*/
function NodeChannel(config) {
(0, _classCallCheck3.default)(this, NodeChannel);
var self = this;
this.id = _CONNECTION_IDGEN++;
this.available = true;
this._pending = [];
this._open = true;
this._error = null;
this._handleConnectionError = this._handleConnectionError.bind(this);
this._handleConnectionTerminated = this._handleConnectionTerminated.bind(this);
this._connectionErrorCode = config.connectionErrorCode;
this._encrypted = config.encrypted;
this._conn = connect(config, function () {
if (!self._open) {
return;
}
self._conn.on('data', function (buffer) {
if (self.onmessage) {
self.onmessage(new _buf.NodeBuffer(buffer));
}
});
self._conn.on('error', self._handleConnectionError);
self._conn.on('end', self._handleConnectionTerminated);
// Drain all pending messages
var pending = self._pending;
self._pending = null;
for (var i = 0; i < pending.length; i++) {
self.write(pending[i]);
}
}, this._handleConnectionError);
this._setupConnectionTimeout(config, this._conn);
}
(0, _createClass3.default)(NodeChannel, [{
key: '_handleConnectionError',
value: function _handleConnectionError(err) {
var msg = err.message || 'Failed to connect to server';
this._error = (0, _error.newError)(msg, this._connectionErrorCode);
if (this.onerror) {
this.onerror(this._error);
}
}
}, {
key: '_handleConnectionTerminated',
value: function _handleConnectionTerminated() {
this._error = (0, _error.newError)('Connection was closed by server', this._connectionErrorCode);
if (this.onerror) {
this.onerror(this._error);
}
}
/**
* Setup connection timeout on the socket, if configured.
* @param {ChannelConfig} config - configuration of this channel.
* @param {object} socket - `net.Socket` or `tls.TLSSocket` object.
* @private
*/
}, {
key: '_setupConnectionTimeout',
value: function _setupConnectionTimeout(config, socket) {
var timeout = config.connectionTimeout;
if (timeout) {
socket.on('connect', function () {
// connected - clear connection timeout
socket.setTimeout(0);
});
socket.on('timeout', function () {
// timeout fired - not connected within configured time. cancel timeout and destroy socket
socket.setTimeout(0);
socket.destroy((0, _error.newError)('Failed to establish connection in ' + timeout + 'ms', config.connectionErrorCode));
});
socket.setTimeout(timeout);
}
}
}, {
key: 'isEncrypted',
value: function isEncrypted() {
return this._encrypted;
}
/**
* Write the passed in buffer to connection
* @param {NodeBuffer} buffer - Buffer to write
*/
}, {
key: 'write',
value: function write(buffer) {
// If there is a pending queue, push this on that queue. This means
// we are not yet connected, so we queue things locally.
if (this._pending !== null) {
this._pending.push(buffer);
} else if (buffer instanceof _buf.NodeBuffer) {
// console.log( "[Conn#"+this.id+"] SEND: ", buffer.toString() );
this._conn.write(buffer._buffer);
} else {
throw (0, _error.newError)("Don't know how to write: " + buffer);
}
}
/**
* Close the connection
* @param {function} cb - Function to call on close.
*/
}, {
key: 'close',
value: function close() {
var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
return null;
};
this._open = false;
if (this._conn) {
this._conn.end();
this._conn.removeListener('end', this._handleConnectionTerminated);
this._conn.on('end', cb);
} else {
cb();
}
}
}]);
return NodeChannel;
}();
var _nodeChannelModule = { channel: NodeChannel, available: true };
try {
// Only define this module if 'net' is available
require.resolve("net");
} catch (e) {
_nodeChannelModule = { available: false };
}
exports.default = _nodeChannelModule;

View File

@@ -0,0 +1,269 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _buf = require('./buf');
var _error = require('./../error');
var _util = require('./util');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a new WebSocketChannel to be used in web browsers.
* @access private
*/
var WebSocketChannel = function () {
/**
* Create new instance
* @param {ChannelConfig} config - configuration for this channel.
*/
function WebSocketChannel(config) {
(0, _classCallCheck3.default)(this, WebSocketChannel);
this._open = true;
this._pending = [];
this._error = null;
this._handleConnectionError = this._handleConnectionError.bind(this);
this._config = config;
var scheme = "ws";
//Allow boolean for backwards compatibility
if (config.encrypted === true || config.encrypted === _util.ENCRYPTION_ON) {
if (!config.trust || config.trust === 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES') {
scheme = "wss";
} else {
this._error = (0, _error.newError)("The browser version of this driver only supports one trust " + 'strategy, \'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES\'. ' + config.trust + ' is not supported. Please ' + "either use TRUST_CUSTOM_CA_SIGNED_CERTIFICATES or disable encryption by setting " + "`encrypted:\"" + _util.ENCRYPTION_OFF + "\"` in the driver configuration.");
return;
}
}
this._ws = createWebSocket(scheme, config.url);
this._ws.binaryType = "arraybuffer";
var self = this;
//All connection errors are not sent to the error handler
//we must also check for dirty close calls
this._ws.onclose = function (e) {
if (!e.wasClean) {
self._handleConnectionError();
}
};
this._ws.onopen = function () {
// Connected! Cancel the connection timeout
self._clearConnectionTimeout();
// Drain all pending messages
var pending = self._pending;
self._pending = null;
for (var i = 0; i < pending.length; i++) {
self.write(pending[i]);
}
};
this._ws.onmessage = function (event) {
if (self.onmessage) {
var b = new _buf.HeapBuffer(event.data);
self.onmessage(b);
}
};
this._ws.onerror = this._handleConnectionError;
this._connectionTimeoutFired = false;
this._connectionTimeoutId = this._setupConnectionTimeout();
}
(0, _createClass3.default)(WebSocketChannel, [{
key: '_handleConnectionError',
value: function _handleConnectionError() {
if (this._connectionTimeoutFired) {
// timeout fired - not connected within configured time
this._error = (0, _error.newError)('Failed to establish connection in ' + this._config.connectionTimeout + 'ms', this._config.connectionErrorCode);
if (this.onerror) {
this.onerror(this._error);
}
return;
}
// onerror triggers on websocket close as well.. don't get me started.
if (this._open) {
// http://stackoverflow.com/questions/25779831/how-to-catch-websocket-connection-to-ws-xxxnn-failed-connection-closed-be
this._error = (0, _error.newError)("WebSocket connection failure. Due to security " + "constraints in your web browser, the reason for the failure is not available " + "to this Neo4j Driver. Please use your browsers development console to determine " + "the root cause of the failure. Common reasons include the database being " + "unavailable, using the wrong connection URL or temporary network problems. " + "If you have enabled encryption, ensure your browser is configured to trust the " + 'certificate Neo4j is configured to use. WebSocket `readyState` is: ' + this._ws.readyState, this._config.connectionErrorCode);
if (this.onerror) {
this.onerror(this._error);
}
}
}
}, {
key: 'isEncrypted',
value: function isEncrypted() {
return this._config.encrypted;
}
/**
* Write the passed in buffer to connection
* @param {HeapBuffer} buffer - Buffer to write
*/
}, {
key: 'write',
value: function write(buffer) {
// If there is a pending queue, push this on that queue. This means
// we are not yet connected, so we queue things locally.
if (this._pending !== null) {
this._pending.push(buffer);
} else if (buffer instanceof _buf.HeapBuffer) {
this._ws.send(buffer._buffer);
} else {
throw (0, _error.newError)("Don't know how to send buffer: " + buffer);
}
}
/**
* Close the connection
* @param {function} cb - Function to call on close.
*/
}, {
key: 'close',
value: function close() {
var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
return null;
};
this._open = false;
this._clearConnectionTimeout();
this._ws.close();
this._ws.onclose = cb;
}
/**
* Set connection timeout on the given WebSocket, if configured.
* @return {number} the timeout id or null.
* @private
*/
}, {
key: '_setupConnectionTimeout',
value: function _setupConnectionTimeout() {
var _this = this;
var timeout = this._config.connectionTimeout;
if (timeout) {
var webSocket = this._ws;
return setTimeout(function () {
if (webSocket.readyState !== WebSocket.OPEN) {
_this._connectionTimeoutFired = true;
webSocket.close();
}
}, timeout);
}
return null;
}
/**
* Remove active connection timeout, if any.
* @private
*/
}, {
key: '_clearConnectionTimeout',
value: function _clearConnectionTimeout() {
var timeoutId = this._connectionTimeoutId;
if (timeoutId || timeoutId === 0) {
this._connectionTimeoutFired = false;
this._connectionTimeoutId = null;
clearTimeout(timeoutId);
}
}
}]);
return WebSocketChannel;
}(); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var available = typeof WebSocket !== 'undefined';
var _websocketChannelModule = { channel: WebSocketChannel, available: available };
function createWebSocket(scheme, parsedUrl) {
var url = scheme + '://' + parsedUrl.hostAndPort;
try {
return new WebSocket(url);
} catch (error) {
if (isIPv6AddressIssueOnWindows(error, parsedUrl)) {
// WebSocket in IE and Edge browsers on Windows do not support regular IPv6 address syntax because they contain ':'.
// It's an invalid character for UNC (https://en.wikipedia.org/wiki/IPv6_address#Literal_IPv6_addresses_in_UNC_path_names)
// and Windows requires IPv6 to be changes in the following way:
// 1) replace all ':' with '-'
// 2) replace '%' with 's' for link-local address
// 3) append '.ipv6-literal.net' suffix
// only then resulting string can be considered a valid IPv6 address. Yes, this is extremely weird!
// For more details see:
// https://social.msdn.microsoft.com/Forums/ie/en-US/06cca73b-63c2-4bf9-899b-b229c50449ff/whether-ie10-websocket-support-ipv6?forum=iewebdevelopment
// https://www.itdojo.com/ipv6-addresses-and-unc-path-names-overcoming-illegal/
// Creation of WebSocket with unconverted address results in SyntaxError without message or stacktrace.
// That is why here we "catch" SyntaxError and rewrite IPv6 address if needed.
var windowsFriendlyUrl = asWindowsFriendlyIPv6Address(scheme, parsedUrl);
return new WebSocket(windowsFriendlyUrl);
} else {
throw error;
}
}
}
function isIPv6AddressIssueOnWindows(error, parsedUrl) {
return error.name === 'SyntaxError' && isIPv6Address(parsedUrl);
}
function isIPv6Address(parsedUrl) {
var hostAndPort = parsedUrl.hostAndPort;
return hostAndPort.charAt(0) === '[' && hostAndPort.indexOf(']') !== -1;
}
function asWindowsFriendlyIPv6Address(scheme, parsedUrl) {
// replace all ':' with '-'
var hostWithoutColons = parsedUrl.host.replace(new RegExp(':', 'g'), '-');
// replace '%' with 's' for link-local IPv6 address like 'fe80::1%lo0'
var hostWithoutPercent = hostWithoutColons.replace('%', 's');
// append magic '.ipv6-literal.net' suffix
var ipv6Host = hostWithoutPercent + '.ipv6-literal.net';
return scheme + '://' + ipv6Host + ':' + parsedUrl.port;
}
exports.default = _websocketChannelModule;

265
node_modules/neo4j-driver/lib/v1/internal/chunking.js generated vendored Normal file
View File

@@ -0,0 +1,265 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Dechunker = exports.Chunker = undefined;
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _buf = require('./buf');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _CHUNK_HEADER_SIZE = 2,
_MESSAGE_BOUNDARY = 0x00,
_DEFAULT_BUFFER_SIZE = 1400; // http://stackoverflow.com/questions/2613734/maximum-packet-size-for-a-tcp-connection
/**
* Looks like a writable buffer, chunks output transparently into a channel below.
* @access private
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Chunker = function (_BaseBuffer) {
(0, _inherits3.default)(Chunker, _BaseBuffer);
function Chunker(channel, bufferSize) {
(0, _classCallCheck3.default)(this, Chunker);
var _this = (0, _possibleConstructorReturn3.default)(this, (Chunker.__proto__ || (0, _getPrototypeOf2.default)(Chunker)).call(this, 0));
_this._bufferSize = bufferSize || _DEFAULT_BUFFER_SIZE;
_this._ch = channel;
_this._buffer = (0, _buf.alloc)(_this._bufferSize);
_this._currentChunkStart = 0;
_this._chunkOpen = false;
return _this;
}
(0, _createClass3.default)(Chunker, [{
key: 'putUInt8',
value: function putUInt8(position, val) {
this._ensure(1);
this._buffer.writeUInt8(val);
}
}, {
key: 'putInt8',
value: function putInt8(position, val) {
this._ensure(1);
this._buffer.writeInt8(val);
}
}, {
key: 'putFloat64',
value: function putFloat64(position, val) {
this._ensure(8);
this._buffer.writeFloat64(val);
}
}, {
key: 'putBytes',
value: function putBytes(position, data) {
// TODO: If data is larger than our chunk size or so, we're very likely better off just passing this buffer on
// rather than doing the copy here TODO: *however* note that we need some way to find out when the data has been
// written (and thus the buffer can be re-used) if we take that approach
while (data.remaining() > 0) {
// Ensure there is an open chunk, and that it has at least one byte of space left
this._ensure(1);
if (this._buffer.remaining() > data.remaining()) {
this._buffer.writeBytes(data);
} else {
this._buffer.writeBytes(data.readSlice(this._buffer.remaining()));
}
}
return this;
}
}, {
key: 'flush',
value: function flush() {
if (this._buffer.position > 0) {
this._closeChunkIfOpen();
// Local copy and clear the buffer field. This ensures that the buffer is not re-released if the flush call fails
var out = this._buffer;
this._buffer = null;
this._ch.write(out.getSlice(0, out.position));
// Alloc a new output buffer. We assume we're using NodeJS's buffer pooling under the hood here!
this._buffer = (0, _buf.alloc)(this._bufferSize);
this._chunkOpen = false;
}
return this;
}
/**
* Bolt messages are encoded in one or more chunks, and the boundary between two messages
* is encoded as a 0-length chunk, `00 00`. This inserts such a message boundary, closing
* any currently open chunk as needed
*/
}, {
key: 'messageBoundary',
value: function messageBoundary() {
this._closeChunkIfOpen();
if (this._buffer.remaining() < _CHUNK_HEADER_SIZE) {
this.flush();
}
// Write message boundary
this._buffer.writeInt16(_MESSAGE_BOUNDARY);
}
/** Ensure at least the given size is available for writing */
}, {
key: '_ensure',
value: function _ensure(size) {
var toWriteSize = this._chunkOpen ? size : size + _CHUNK_HEADER_SIZE;
if (this._buffer.remaining() < toWriteSize) {
this.flush();
}
if (!this._chunkOpen) {
this._currentChunkStart = this._buffer.position;
this._buffer.position = this._buffer.position + _CHUNK_HEADER_SIZE;
this._chunkOpen = true;
}
}
}, {
key: '_closeChunkIfOpen',
value: function _closeChunkIfOpen() {
if (this._chunkOpen) {
var chunkSize = this._buffer.position - (this._currentChunkStart + _CHUNK_HEADER_SIZE);
this._buffer.putUInt16(this._currentChunkStart, chunkSize);
this._chunkOpen = false;
}
}
}]);
return Chunker;
}(_buf.BaseBuffer);
/**
* Combines chunks until a complete message is gathered up, and then forwards that
* message to an 'onmessage' listener.
* @access private
*/
var Dechunker = function () {
function Dechunker() {
(0, _classCallCheck3.default)(this, Dechunker);
this._currentMessage = [];
this._partialChunkHeader = 0;
this._state = this.AWAITING_CHUNK;
}
(0, _createClass3.default)(Dechunker, [{
key: 'AWAITING_CHUNK',
value: function AWAITING_CHUNK(buf) {
if (buf.remaining() >= 2) {
// Whole header available, read that
return this._onHeader(buf.readUInt16());
} else {
// Only one byte available, read that and wait for the second byte
this._partialChunkHeader = buf.readUInt8() << 8;
return this.IN_HEADER;
}
}
}, {
key: 'IN_HEADER',
value: function IN_HEADER(buf) {
// First header byte read, now we read the next one
return this._onHeader((this._partialChunkHeader | buf.readUInt8()) & 0xFFFF);
}
}, {
key: 'IN_CHUNK',
value: function IN_CHUNK(buf) {
if (this._chunkSize <= buf.remaining()) {
// Current packet is larger than current chunk, or same size:
this._currentMessage.push(buf.readSlice(this._chunkSize));
return this.AWAITING_CHUNK;
} else {
// Current packet is smaller than the chunk we're reading, split the current chunk itself up
this._chunkSize -= buf.remaining();
this._currentMessage.push(buf.readSlice(buf.remaining()));
return this.IN_CHUNK;
}
}
}, {
key: 'CLOSED',
value: function CLOSED(buf) {}
// no-op
/** Called when a complete chunk header has been received */
}, {
key: '_onHeader',
value: function _onHeader(header) {
if (header == 0) {
// Message boundary
var message = void 0;
if (this._currentMessage.length == 1) {
message = this._currentMessage[0];
} else {
message = new _buf.CombinedBuffer(this._currentMessage);
}
this._currentMessage = [];
this.onmessage(message);
return this.AWAITING_CHUNK;
} else {
this._chunkSize = header;
return this.IN_CHUNK;
}
}
}, {
key: 'write',
value: function write(buf) {
while (buf.hasRemaining()) {
this._state = this._state(buf);
}
}
}]);
return Dechunker;
}();
exports.Chunker = Chunker;
exports.Dechunker = Dechunker;

View File

@@ -0,0 +1,203 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EMPTY_CONNECTION_HOLDER = undefined;
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _error = require('../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Utility to lazily initialize connections and return them back to the pool when unused.
*/
var ConnectionHolder = function () {
/**
* @constructor
* @param {string} mode - the access mode for new connection holder.
* @param {ConnectionProvider} connectionProvider - the connection provider to acquire connections from.
*/
function ConnectionHolder(mode, connectionProvider) {
(0, _classCallCheck3.default)(this, ConnectionHolder);
this._mode = mode;
this._connectionProvider = connectionProvider;
this._referenceCount = 0;
this._connectionPromise = _promise2.default.resolve(null);
}
/**
* Make this holder initialize new connection if none exists already.
* @return {undefined}
*/
(0, _createClass3.default)(ConnectionHolder, [{
key: 'initializeConnection',
value: function initializeConnection() {
if (this._referenceCount === 0) {
this._connectionPromise = this._connectionProvider.acquireConnection(this._mode);
}
this._referenceCount++;
}
/**
* Get the current connection promise.
* @param {StreamObserver} streamObserver an observer for this connection.
* @return {Promise<Connection>} promise resolved with the current connection.
*/
}, {
key: 'getConnection',
value: function getConnection(streamObserver) {
return this._connectionPromise.then(function (connection) {
streamObserver.resolveConnection(connection);
return connection.initializationCompleted();
});
}
/**
* Notify this holder that single party does not require current connection any more.
* @return {Promise<Connection>} promise resolved with the current connection, never a rejected promise.
*/
}, {
key: 'releaseConnection',
value: function releaseConnection() {
if (this._referenceCount === 0) {
return this._connectionPromise;
}
this._referenceCount--;
if (this._referenceCount === 0) {
return this._releaseConnection();
}
return this._connectionPromise;
}
/**
* Closes this holder and releases current connection (if any) despite any existing users.
* @return {Promise<Connection>} promise resolved when current connection is released to the pool.
*/
}, {
key: 'close',
value: function close() {
if (this._referenceCount === 0) {
return this._connectionPromise;
}
this._referenceCount = 0;
return this._releaseConnection();
}
/**
* Return the current pooled connection instance to the connection pool.
* We don't pool Session instances, to avoid users using the Session after they've called close.
* The `Session` object is just a thin wrapper around Connection anyway, so it makes little difference.
* @return {Promise} - promise resolved then connection is returned to the pool.
* @private
*/
}, {
key: '_releaseConnection',
value: function _releaseConnection() {
this._connectionPromise = this._connectionPromise.then(function (connection) {
if (connection) {
return connection.resetAndFlush().catch(ignoreError).then(function () {
return connection._release();
});
} else {
return _promise2.default.resolve();
}
}).catch(ignoreError);
return this._connectionPromise;
}
}]);
return ConnectionHolder;
}(); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = ConnectionHolder;
var EmptyConnectionHolder = function (_ConnectionHolder) {
(0, _inherits3.default)(EmptyConnectionHolder, _ConnectionHolder);
function EmptyConnectionHolder() {
(0, _classCallCheck3.default)(this, EmptyConnectionHolder);
return (0, _possibleConstructorReturn3.default)(this, (EmptyConnectionHolder.__proto__ || (0, _getPrototypeOf2.default)(EmptyConnectionHolder)).apply(this, arguments));
}
(0, _createClass3.default)(EmptyConnectionHolder, [{
key: 'initializeConnection',
value: function initializeConnection() {
// nothing to initialize
}
}, {
key: 'getConnection',
value: function getConnection(streamObserver) {
return _promise2.default.reject((0, _error.newError)('This connection holder does not serve connections'));
}
}, {
key: 'releaseConnection',
value: function releaseConnection() {
return _promise2.default.resolve();
}
}, {
key: 'close',
value: function close() {
return _promise2.default.resolve();
}
}]);
return EmptyConnectionHolder;
}(ConnectionHolder);
function ignoreError(error) {}
/**
* Connection holder that does not manage any connections.
* @type {ConnectionHolder}
*/
var EMPTY_CONNECTION_HOLDER = exports.EMPTY_CONNECTION_HOLDER = new EmptyConnectionHolder();

View File

@@ -0,0 +1,379 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SingleConnectionProvider = exports.LoadBalancer = exports.DirectConnectionProvider = undefined;
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _error = require('../error');
var _driver = require('../driver');
var _session = require('../session');
var _session2 = _interopRequireDefault(_session);
var _routingTable = require('./routing-table');
var _routingTable2 = _interopRequireDefault(_routingTable);
var _rediscovery = require('./rediscovery');
var _rediscovery2 = _interopRequireDefault(_rediscovery);
var _features = require('./features');
var _features2 = _interopRequireDefault(_features);
var _hostNameResolvers = require('./host-name-resolvers');
var _routingUtil = require('./routing-util');
var _routingUtil2 = _interopRequireDefault(_routingUtil);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ConnectionProvider = function () {
function ConnectionProvider() {
(0, _classCallCheck3.default)(this, ConnectionProvider);
}
(0, _createClass3.default)(ConnectionProvider, [{
key: 'acquireConnection',
value: function acquireConnection(mode) {
throw new Error('Abstract function');
}
}, {
key: '_withAdditionalOnErrorCallback',
value: function _withAdditionalOnErrorCallback(connectionPromise, driverOnErrorCallback) {
// install error handler from the driver on the connection promise; this callback is installed separately
// so that it does not handle errors, instead it is just an additional error reporting facility.
connectionPromise.catch(function (error) {
driverOnErrorCallback(error);
});
// return the original connection promise
return connectionPromise;
}
}]);
return ConnectionProvider;
}();
var DirectConnectionProvider = exports.DirectConnectionProvider = function (_ConnectionProvider) {
(0, _inherits3.default)(DirectConnectionProvider, _ConnectionProvider);
function DirectConnectionProvider(hostPort, connectionPool, driverOnErrorCallback) {
(0, _classCallCheck3.default)(this, DirectConnectionProvider);
var _this = (0, _possibleConstructorReturn3.default)(this, (DirectConnectionProvider.__proto__ || (0, _getPrototypeOf2.default)(DirectConnectionProvider)).call(this));
_this._hostPort = hostPort;
_this._connectionPool = connectionPool;
_this._driverOnErrorCallback = driverOnErrorCallback;
return _this;
}
(0, _createClass3.default)(DirectConnectionProvider, [{
key: 'acquireConnection',
value: function acquireConnection(mode) {
var connectionPromise = this._connectionPool.acquire(this._hostPort);
return this._withAdditionalOnErrorCallback(connectionPromise, this._driverOnErrorCallback);
}
}]);
return DirectConnectionProvider;
}(ConnectionProvider);
var LoadBalancer = exports.LoadBalancer = function (_ConnectionProvider2) {
(0, _inherits3.default)(LoadBalancer, _ConnectionProvider2);
function LoadBalancer(hostPort, routingContext, connectionPool, loadBalancingStrategy, driverOnErrorCallback) {
(0, _classCallCheck3.default)(this, LoadBalancer);
var _this2 = (0, _possibleConstructorReturn3.default)(this, (LoadBalancer.__proto__ || (0, _getPrototypeOf2.default)(LoadBalancer)).call(this));
_this2._seedRouter = hostPort;
_this2._routingTable = new _routingTable2.default([_this2._seedRouter]);
_this2._rediscovery = new _rediscovery2.default(new _routingUtil2.default(routingContext));
_this2._connectionPool = connectionPool;
_this2._driverOnErrorCallback = driverOnErrorCallback;
_this2._hostNameResolver = LoadBalancer._createHostNameResolver();
_this2._loadBalancingStrategy = loadBalancingStrategy;
_this2._useSeedRouter = false;
return _this2;
}
(0, _createClass3.default)(LoadBalancer, [{
key: 'acquireConnection',
value: function acquireConnection(accessMode) {
var _this3 = this;
var connectionPromise = this._freshRoutingTable(accessMode).then(function (routingTable) {
if (accessMode === _driver.READ) {
var address = _this3._loadBalancingStrategy.selectReader(routingTable.readers);
return _this3._acquireConnectionToServer(address, 'read');
} else if (accessMode === _driver.WRITE) {
var _address = _this3._loadBalancingStrategy.selectWriter(routingTable.writers);
return _this3._acquireConnectionToServer(_address, 'write');
} else {
throw (0, _error.newError)('Illegal mode ' + accessMode);
}
});
return this._withAdditionalOnErrorCallback(connectionPromise, this._driverOnErrorCallback);
}
}, {
key: 'forget',
value: function forget(address) {
this._routingTable.forget(address);
this._connectionPool.purge(address);
}
}, {
key: 'forgetWriter',
value: function forgetWriter(address) {
this._routingTable.forgetWriter(address);
}
}, {
key: '_acquireConnectionToServer',
value: function _acquireConnectionToServer(address, serverName) {
if (!address) {
return _promise2.default.reject((0, _error.newError)('Failed to obtain connection towards ' + serverName + ' server. Known routing table is: ' + this._routingTable, _error.SESSION_EXPIRED));
}
return this._connectionPool.acquire(address);
}
}, {
key: '_freshRoutingTable',
value: function _freshRoutingTable(accessMode) {
var currentRoutingTable = this._routingTable;
if (!currentRoutingTable.isStaleFor(accessMode)) {
return _promise2.default.resolve(currentRoutingTable);
}
return this._refreshRoutingTable(currentRoutingTable);
}
}, {
key: '_refreshRoutingTable',
value: function _refreshRoutingTable(currentRoutingTable) {
var knownRouters = currentRoutingTable.routers;
if (this._useSeedRouter) {
return this._fetchRoutingTableFromSeedRouterFallbackToKnownRouters(knownRouters, currentRoutingTable);
}
return this._fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(knownRouters, currentRoutingTable);
}
}, {
key: '_fetchRoutingTableFromSeedRouterFallbackToKnownRouters',
value: function _fetchRoutingTableFromSeedRouterFallbackToKnownRouters(knownRouters, currentRoutingTable) {
var _this4 = this;
// we start with seed router, no routers were probed before
var seenRouters = [];
return this._fetchRoutingTableUsingSeedRouter(seenRouters, this._seedRouter).then(function (newRoutingTable) {
if (newRoutingTable) {
_this4._useSeedRouter = false;
return newRoutingTable;
}
// seed router did not return a valid routing table - try to use other known routers
return _this4._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable);
}).then(function (newRoutingTable) {
_this4._applyRoutingTableIfPossible(newRoutingTable);
return newRoutingTable;
});
}
}, {
key: '_fetchRoutingTableFromKnownRoutersFallbackToSeedRouter',
value: function _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(knownRouters, currentRoutingTable) {
var _this5 = this;
return this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable).then(function (newRoutingTable) {
if (newRoutingTable) {
return newRoutingTable;
}
// none of the known routers returned a valid routing table - try to use seed router address for rediscovery
return _this5._fetchRoutingTableUsingSeedRouter(knownRouters, _this5._seedRouter);
}).then(function (newRoutingTable) {
_this5._applyRoutingTableIfPossible(newRoutingTable);
return newRoutingTable;
});
}
}, {
key: '_fetchRoutingTableUsingKnownRouters',
value: function _fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable) {
return this._fetchRoutingTable(knownRouters, currentRoutingTable).then(function (newRoutingTable) {
if (newRoutingTable) {
// one of the known routers returned a valid routing table - use it
return newRoutingTable;
}
// returned routing table was undefined, this means a connection error happened and the last known
// router did not return a valid routing table, so we need to forget it
var lastRouterIndex = knownRouters.length - 1;
LoadBalancer._forgetRouter(currentRoutingTable, knownRouters, lastRouterIndex);
return null;
});
}
}, {
key: '_fetchRoutingTableUsingSeedRouter',
value: function _fetchRoutingTableUsingSeedRouter(seenRouters, seedRouter) {
var _this6 = this;
return this._hostNameResolver.resolve(seedRouter).then(function (resolvedRouterAddresses) {
// filter out all addresses that we've already tried
var newAddresses = resolvedRouterAddresses.filter(function (address) {
return seenRouters.indexOf(address) < 0;
});
return _this6._fetchRoutingTable(newAddresses, null);
});
}
}, {
key: '_fetchRoutingTable',
value: function _fetchRoutingTable(routerAddresses, routingTable) {
var _this7 = this;
return routerAddresses.reduce(function (refreshedTablePromise, currentRouter, currentIndex) {
return refreshedTablePromise.then(function (newRoutingTable) {
if (newRoutingTable) {
// valid routing table was fetched - just return it, try next router otherwise
return newRoutingTable;
} else {
// returned routing table was undefined, this means a connection error happened and we need to forget the
// previous router and try the next one
var previousRouterIndex = currentIndex - 1;
LoadBalancer._forgetRouter(routingTable, routerAddresses, previousRouterIndex);
}
// try next router
return _this7._createSessionForRediscovery(currentRouter).then(function (session) {
return _this7._rediscovery.lookupRoutingTableOnRouter(session, currentRouter);
});
});
}, _promise2.default.resolve(null));
}
}, {
key: '_createSessionForRediscovery',
value: function _createSessionForRediscovery(routerAddress) {
return this._connectionPool.acquire(routerAddress).then(function (connection) {
// initialized connection is required for routing procedure call
// server version needs to be known to decide which routing procedure to use
var initializedConnectionPromise = connection.initializationCompleted();
var connectionProvider = new SingleConnectionProvider(initializedConnectionPromise);
return new _session2.default(_driver.READ, connectionProvider);
});
}
}, {
key: '_applyRoutingTableIfPossible',
value: function _applyRoutingTableIfPossible(newRoutingTable) {
if (!newRoutingTable) {
// none of routing servers returned valid routing table, throw exception
throw (0, _error.newError)('Could not perform discovery. No routing servers available. Known routing table: ' + this._routingTable, _error.SERVICE_UNAVAILABLE);
}
if (newRoutingTable.writers.length === 0) {
// use seed router next time. this is important when cluster is partitioned. it tries to make sure driver
// does not always get routing table without writers because it talks exclusively to a minority partition
this._useSeedRouter = true;
}
this._updateRoutingTable(newRoutingTable);
}
}, {
key: '_updateRoutingTable',
value: function _updateRoutingTable(newRoutingTable) {
var _this8 = this;
var currentRoutingTable = this._routingTable;
// close old connections to servers not present in the new routing table
var staleServers = currentRoutingTable.serversDiff(newRoutingTable);
staleServers.forEach(function (server) {
return _this8._connectionPool.purge(server);
});
// make this driver instance aware of the new table
this._routingTable = newRoutingTable;
}
}], [{
key: '_forgetRouter',
value: function _forgetRouter(routingTable, routersArray, routerIndex) {
var address = routersArray[routerIndex];
if (routingTable && address) {
routingTable.forgetRouter(address);
}
}
}, {
key: '_createHostNameResolver',
value: function _createHostNameResolver() {
if ((0, _features2.default)('dns_lookup')) {
return new _hostNameResolvers.DnsHostNameResolver();
}
return new _hostNameResolvers.DummyHostNameResolver();
}
}]);
return LoadBalancer;
}(ConnectionProvider);
var SingleConnectionProvider = exports.SingleConnectionProvider = function (_ConnectionProvider3) {
(0, _inherits3.default)(SingleConnectionProvider, _ConnectionProvider3);
function SingleConnectionProvider(connectionPromise) {
(0, _classCallCheck3.default)(this, SingleConnectionProvider);
var _this9 = (0, _possibleConstructorReturn3.default)(this, (SingleConnectionProvider.__proto__ || (0, _getPrototypeOf2.default)(SingleConnectionProvider)).call(this));
_this9._connectionPromise = connectionPromise;
return _this9;
}
(0, _createClass3.default)(SingleConnectionProvider, [{
key: 'acquireConnection',
value: function acquireConnection(mode) {
var connectionPromise = this._connectionPromise;
this._connectionPromise = null;
return connectionPromise;
}
}]);
return SingleConnectionProvider;
}(ConnectionProvider);

View File

@@ -0,0 +1,107 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _connectionHolder = require('./connection-holder');
var _connectionHolder2 = _interopRequireDefault(_connectionHolder);
var _driver = require('../driver');
var _streamObserver = require('./stream-observer');
var _streamObserver2 = _interopRequireDefault(_streamObserver);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Verifies connectivity using the given connection provider.
*/
var ConnectivityVerifier = function () {
/**
* @constructor
* @param {ConnectionProvider} connectionProvider the provider to obtain connections from.
* @param {function} successCallback a callback to invoke when verification succeeds.
*/
function ConnectivityVerifier(connectionProvider, successCallback) {
(0, _classCallCheck3.default)(this, ConnectivityVerifier);
this._connectionProvider = connectionProvider;
this._successCallback = successCallback;
}
(0, _createClass3.default)(ConnectivityVerifier, [{
key: 'verify',
value: function verify() {
var _this = this;
acquireAndReleaseDummyConnection(this._connectionProvider).then(function (serverInfo) {
if (_this._successCallback) {
_this._successCallback(serverInfo);
}
}).catch(function (ignoredError) {});
}
}]);
return ConnectivityVerifier;
}();
/**
* @private
* @param {ConnectionProvider} connectionProvider the provider to obtain connections from.
* @return {Promise<object>} promise resolved with server info or rejected with error.
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = ConnectivityVerifier;
function acquireAndReleaseDummyConnection(connectionProvider) {
var connectionHolder = new _connectionHolder2.default(_driver.READ, connectionProvider);
connectionHolder.initializeConnection();
var dummyObserver = new _streamObserver2.default();
var connectionPromise = connectionHolder.getConnection(dummyObserver);
return connectionPromise.then(function (connection) {
// able to establish a connection
return connectionHolder.close().then(function () {
return connection.server;
});
}).catch(function (error) {
// failed to establish a connection
return connectionHolder.close().catch(function (ignoredError) {
// ignore connection release error
}).then(function () {
return _promise2.default.reject(error);
});
});
}

727
node_modules/neo4j-driver/lib/v1/internal/connector.js generated vendored Normal file
View File

@@ -0,0 +1,727 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Connection = exports.connect = undefined;
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _chWebsocket = require('./ch-websocket');
var _chWebsocket2 = _interopRequireDefault(_chWebsocket);
var _chNode = require('./ch-node');
var _chNode2 = _interopRequireDefault(_chNode);
var _chunking = require('./chunking');
var _packstreamUtil = require('./packstream-util');
var _packstreamUtil2 = _interopRequireDefault(_packstreamUtil);
var _buf = require('./buf');
var _error = require('./../error');
var _chConfig = require('./ch-config');
var _chConfig2 = _interopRequireDefault(_chConfig);
var _urlUtil = require('./url-util');
var _urlUtil2 = _interopRequireDefault(_urlUtil);
var _streamObserver = require('./stream-observer');
var _streamObserver2 = _interopRequireDefault(_streamObserver);
var _serverVersion = require('./server-version');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Channel = void 0;
if (_chNode2.default.available) {
Channel = _chNode2.default.channel;
} else if (_chWebsocket2.default.available) {
Channel = _chWebsocket2.default.channel;
} else {
throw (0, _error.newError)("Fatal: No compatible transport available. Need to run on a platform with the WebSocket API.");
}
var
// Signature bytes for each message type
INIT = 0x01,
// 0000 0001 // INIT <user_agent>
ACK_FAILURE = 0x0E,
// 0000 1110 // ACK_FAILURE
RESET = 0x0F,
// 0000 1111 // RESET
RUN = 0x10,
// 0001 0000 // RUN <statement> <parameters>
DISCARD_ALL = 0x2F,
// 0010 1111 // DISCARD *
PULL_ALL = 0x3F,
// 0011 1111 // PULL *
SUCCESS = 0x70,
// 0111 0000 // SUCCESS <metadata>
RECORD = 0x71,
// 0111 0001 // RECORD <value>
IGNORED = 0x7E,
// 0111 1110 // IGNORED <metadata>
FAILURE = 0x7F,
// 0111 1111 // FAILURE <metadata>
//sent before version negotiation
MAGIC_PREAMBLE = 0x6060B017,
DEBUG = false;
/**
* Very rudimentary log handling, should probably be replaced by something proper at some point.
* @param actor the part that sent the message, 'S' for server and 'C' for client
* @param msg the bolt message
*/
function log(actor, msg) {
if (DEBUG) {
for (var i = 2; i < arguments.length; i++) {
msg += " " + (0, _stringify2.default)(arguments[i]);
}
console.log(actor + ":" + msg);
}
}
function NO_OP() {}
var NO_OP_OBSERVER = {
onNext: NO_OP,
onCompleted: NO_OP,
onError: NO_OP
};
/**
* A connection manages sending and receiving messages over a channel. A
* connector is very closely tied to the Bolt protocol, it implements the
* same message structure with very little frills. This means Connectors are
* naturally tied to a specific version of the protocol, and we expect
* another layer will be needed to support multiple versions.
*
* The connector tries to batch outbound messages by requiring its users
* to call 'sync' when messages need to be sent, and it routes response
* messages back to the originators of the requests that created those
* response messages.
* @access private
*/
var Connection = function () {
/**
* @constructor
* @param {NodeChannel|WebSocketChannel} channel - channel with a 'write' function and a 'onmessage' callback property.
* @param {string} hostPort - the hostname and port to connect to.
* @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers.
*/
function Connection(channel, hostPort) {
var _this = this;
var disableLosslessIntegers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
(0, _classCallCheck3.default)(this, Connection);
/**
* An ordered queue of observers, each exchange response (zero or more
* RECORD messages followed by a SUCCESS message) we receive will be routed
* to the next pending observer.
*/
this.hostPort = hostPort;
this.server = { address: hostPort };
this.creationTimestamp = Date.now();
this._disableLosslessIntegers = disableLosslessIntegers;
this._pendingObservers = [];
this._currentObserver = undefined;
this._ch = channel;
this._dechunker = new _chunking.Dechunker();
this._chunker = new _chunking.Chunker(channel);
// initially assume that database supports latest Bolt version, create latest packer and unpacker
this._packer = _packstreamUtil2.default.createLatestPacker(this._chunker);
this._unpacker = _packstreamUtil2.default.createLatestUnpacker(disableLosslessIntegers);
this._ackFailureMuted = false;
this._currentFailure = null;
this._state = new ConnectionState(this);
// Set to true on fatal errors, to get this out of session pool.
this._isBroken = false;
// TODO: Using `onmessage` and `onerror` came from the WebSocket API,
// it reads poorly and has several annoying drawbacks. Swap to having
// Channel extend EventEmitter instead, then we can use `on('data',..)`
this._ch.onmessage = function (buf) {
var proposed = buf.readInt32();
if (proposed == 1 || proposed == 2) {
_this._initializeProtocol(proposed, buf);
} else if (proposed == 1213486160) {
//server responded 1213486160 == 0x48545450 == "HTTP"
_this._handleFatalError((0, _error.newError)('Server responded HTTP. Make sure you are not trying to connect to the http endpoint ' + '(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)'));
} else {
_this._handleFatalError((0, _error.newError)('Unknown Bolt protocol version: ' + proposed));
}
};
// Listen to connection errors. Important note though;
// In some cases we will get a channel that is already broken (for instance,
// if the user passes invalid configuration options). In this case, onerror
// will have "already triggered" before we add out listener here. So the line
// below also checks that the channel is not already failed. This could be nicely
// encapsulated into Channel if we used `on('error', ..)` rather than `onerror=..`
// as outlined in the comment about `onmessage` further up in this file.
this._ch.onerror = this._handleFatalError.bind(this);
if (this._ch._error) {
this._handleFatalError(this._ch._error);
}
this._dechunker.onmessage = function (buf) {
_this._handleMessage(_this._unpacker.unpack(buf));
};
var handshake = (0, _buf.alloc)(5 * 4);
//magic preamble
handshake.writeInt32(MAGIC_PREAMBLE);
//proposed versions
handshake.writeInt32(2);
handshake.writeInt32(1);
handshake.writeInt32(0);
handshake.writeInt32(0);
handshake.reset();
this._ch.write(handshake);
}
/**
* Complete protocol initialization.
* @param {number} version the selected protocol version.
* @param {BaseBuffer} buffer the handshake response buffer.
* @private
*/
(0, _createClass3.default)(Connection, [{
key: '_initializeProtocol',
value: function _initializeProtocol(version, buffer) {
var _this2 = this;
// re-create packer and unpacker because version might be lower than we initially assumed
this._packer = _packstreamUtil2.default.createPackerForProtocolVersion(version, this._chunker);
this._unpacker = _packstreamUtil2.default.createUnpackerForProtocolVersion(version, this._disableLosslessIntegers);
// Ok, protocol running. Simply forward all messages to the dechunker
this._ch.onmessage = function (buf) {
return _this2._dechunker.write(buf);
};
if (buffer.hasRemaining()) {
this._dechunker.write(buffer.readSlice(buffer.remaining()));
}
}
/**
* "Fatal" means the connection is dead. Only call this if something
* happens that cannot be recovered from. This will lead to all subscribers
* failing, and the connection getting ejected from the session pool.
*
* @param err an error object, forwarded to all current and future subscribers
* @protected
*/
}, {
key: '_handleFatalError',
value: function _handleFatalError(err) {
this._isBroken = true;
this._error = err;
if (this._currentObserver && this._currentObserver.onError) {
this._currentObserver.onError(err);
}
while (this._pendingObservers.length > 0) {
var observer = this._pendingObservers.shift();
if (observer && observer.onError) {
observer.onError(err);
}
}
}
}, {
key: '_handleMessage',
value: function _handleMessage(msg) {
if (this._isBroken) {
// ignore all incoming messages when this connection is broken. all previously pending observers failed
// with the fatal error. all future observers will fail with same fatal error.
return;
}
var payload = msg.fields[0];
switch (msg.signature) {
case RECORD:
log("S", "RECORD", msg);
this._currentObserver.onNext(payload);
break;
case SUCCESS:
log("S", "SUCCESS", msg);
try {
this._currentObserver.onCompleted(payload);
} finally {
this._updateCurrentObserver();
}
break;
case FAILURE:
log("S", "FAILURE", msg);
try {
this._currentFailure = (0, _error.newError)(payload.message, payload.code);
this._currentObserver.onError(this._currentFailure);
} finally {
this._updateCurrentObserver();
// Things are now broken. Pending observers will get FAILURE messages routed until we are done handling this failure.
this._ackFailureIfNeeded();
}
break;
case IGNORED:
log("S", "IGNORED", msg);
try {
if (this._currentFailure && this._currentObserver.onError) this._currentObserver.onError(this._currentFailure);else if (this._currentObserver.onError) this._currentObserver.onError((0, _error.newError)('Ignored either because of an error or RESET'));
} finally {
this._updateCurrentObserver();
}
break;
default:
this._handleFatalError((0, _error.newError)("Unknown Bolt protocol message: " + msg));
}
}
/** Queue an INIT-message to be sent to the database */
}, {
key: 'initialize',
value: function initialize(clientName, token, observer) {
var _this3 = this;
log("C", "INIT", clientName, token);
var initObserver = this._state.wrap(observer);
var queued = this._queueObserver(initObserver);
if (queued) {
this._packer.packStruct(INIT, [this._packable(clientName), this._packable(token)], function (err) {
return _this3._handleFatalError(err);
});
this._chunker.messageBoundary();
this.sync();
}
}
/** Queue a RUN-message to be sent to the database */
}, {
key: 'run',
value: function run(statement, params, observer) {
var _this4 = this;
log("C", "RUN", statement, params);
var queued = this._queueObserver(observer);
if (queued) {
this._packer.packStruct(RUN, [this._packable(statement), this._packable(params)], function (err) {
return _this4._handleFatalError(err);
});
this._chunker.messageBoundary();
}
}
/** Queue a PULL_ALL-message to be sent to the database */
}, {
key: 'pullAll',
value: function pullAll(observer) {
var _this5 = this;
log("C", "PULL_ALL");
var queued = this._queueObserver(observer);
if (queued) {
this._packer.packStruct(PULL_ALL, [], function (err) {
return _this5._handleFatalError(err);
});
this._chunker.messageBoundary();
}
}
/** Queue a DISCARD_ALL-message to be sent to the database */
}, {
key: 'discardAll',
value: function discardAll(observer) {
var _this6 = this;
log("C", "DISCARD_ALL");
var queued = this._queueObserver(observer);
if (queued) {
this._packer.packStruct(DISCARD_ALL, [], function (err) {
return _this6._handleFatalError(err);
});
this._chunker.messageBoundary();
}
}
/**
* Send a RESET-message to the database. Mutes failure handling.
* Message is immediately flushed to the network. Separate {@link Connection#sync()} call is not required.
* @return {Promise<void>} promise resolved when SUCCESS-message response arrives, or failed when other response messages arrives.
*/
}, {
key: 'resetAndFlush',
value: function resetAndFlush() {
var _this7 = this;
log('C', 'RESET');
this._ackFailureMuted = true;
return new _promise2.default(function (resolve, reject) {
var observer = {
onNext: function onNext(record) {
var neo4jError = _this7._handleProtocolError('Received RECORD as a response for RESET: ' + (0, _stringify2.default)(record));
reject(neo4jError);
},
onError: function onError(error) {
if (_this7._isBroken) {
// handling a fatal error, no need to raise a protocol violation
reject(error);
} else {
var neo4jError = _this7._handleProtocolError('Received FAILURE as a response for RESET: ' + error);
reject(neo4jError);
}
},
onCompleted: function onCompleted() {
_this7._ackFailureMuted = false;
resolve();
}
};
var queued = _this7._queueObserver(observer);
if (queued) {
_this7._packer.packStruct(RESET, [], function (err) {
return _this7._handleFatalError(err);
});
_this7._chunker.messageBoundary();
_this7.sync();
}
});
}
}, {
key: '_ackFailureIfNeeded',
value: function _ackFailureIfNeeded() {
var _this8 = this;
if (this._ackFailureMuted) {
return;
}
log('C', 'ACK_FAILURE');
var observer = {
onNext: function onNext(record) {
_this8._handleProtocolError('Received RECORD as a response for ACK_FAILURE: ' + (0, _stringify2.default)(record));
},
onError: function onError(error) {
if (!_this8._isBroken && !_this8._ackFailureMuted) {
// not handling a fatal error and RESET did not cause the given error - looks like a protocol violation
_this8._handleProtocolError('Received FAILURE as a response for ACK_FAILURE: ' + error);
} else {
_this8._currentFailure = null;
}
},
onCompleted: function onCompleted() {
_this8._currentFailure = null;
}
};
var queued = this._queueObserver(observer);
if (queued) {
this._packer.packStruct(ACK_FAILURE, [], function (err) {
return _this8._handleFatalError(err);
});
this._chunker.messageBoundary();
this.sync();
}
}
}, {
key: '_queueObserver',
value: function _queueObserver(observer) {
if (this._isBroken) {
if (observer && observer.onError) {
observer.onError(this._error);
}
return false;
}
observer = observer || NO_OP_OBSERVER;
observer.onCompleted = observer.onCompleted || NO_OP;
observer.onError = observer.onError || NO_OP;
observer.onNext = observer.onNext || NO_OP;
if (this._currentObserver === undefined) {
this._currentObserver = observer;
} else {
this._pendingObservers.push(observer);
}
return true;
}
/**
* Get promise resolved when connection initialization succeed or rejected when it fails.
* Connection is initialized using {@link initialize} function.
* @return {Promise<Connection>} the result of connection initialization.
*/
}, {
key: 'initializationCompleted',
value: function initializationCompleted() {
return this._state.initializationCompleted();
}
/*
* Pop next pending observer form the list of observers and make it current observer.
* @protected
*/
}, {
key: '_updateCurrentObserver',
value: function _updateCurrentObserver() {
this._currentObserver = this._pendingObservers.shift();
}
/**
* Synchronize - flush all queued outgoing messages and route their responses
* to their respective handlers.
*/
}, {
key: 'sync',
value: function sync() {
this._chunker.flush();
}
/** Check if this connection is in working condition */
}, {
key: 'isOpen',
value: function isOpen() {
return !this._isBroken && this._ch._open;
}
}, {
key: 'isEncrypted',
value: function isEncrypted() {
return this._ch.isEncrypted();
}
/**
* Call close on the channel.
* @param {function} cb - Function to call on close.
*/
}, {
key: 'close',
value: function close(cb) {
this._ch.close(cb);
}
}, {
key: '_packable',
value: function _packable(value) {
var _this9 = this;
return this._packer.packable(value, function (err) {
return _this9._handleFatalError(err);
});
}
/**
* @protected
*/
}, {
key: '_markInitialized',
value: function _markInitialized(metadata) {
var serverVersion = metadata ? metadata.server : null;
if (!this.server.version) {
this.server.version = serverVersion;
var version = _serverVersion.ServerVersion.fromString(serverVersion);
if (version.compareTo(_serverVersion.VERSION_3_2_0) < 0) {
this._packer.disableByteArrays();
}
}
}
}, {
key: '_handleProtocolError',
value: function _handleProtocolError(message) {
this._ackFailureMuted = false;
this._currentFailure = null;
this._updateCurrentObserver();
var error = (0, _error.newError)(message, _error.PROTOCOL_ERROR);
this._handleFatalError(error);
return error;
}
}]);
return Connection;
}();
var ConnectionState = function () {
/**
* @constructor
* @param {Connection} connection the connection to track state for.
*/
function ConnectionState(connection) {
var _this10 = this;
(0, _classCallCheck3.default)(this, ConnectionState);
this._connection = connection;
this._initRequested = false;
this._initError = null;
this._resolveInitPromise = null;
this._rejectInitPromise = null;
this._initPromise = new _promise2.default(function (resolve, reject) {
_this10._resolveInitPromise = resolve;
_this10._rejectInitPromise = reject;
});
}
/**
* Wrap the given observer to track connection's initialization state. Connection is closed by the server if
* processing of INIT message fails so returned observer will handle initialization failure as a fatal error.
* @param {StreamObserver} observer the observer used for INIT message.
* @return {StreamObserver} updated observer.
*/
(0, _createClass3.default)(ConnectionState, [{
key: 'wrap',
value: function wrap(observer) {
var _this11 = this;
return {
onNext: function onNext(record) {
if (observer && observer.onNext) {
observer.onNext(record);
}
},
onError: function onError(error) {
_this11._processFailure(error);
_this11._connection._updateCurrentObserver(); // make sure this same observer will not be called again
try {
if (observer && observer.onError) {
observer.onError(error);
}
} finally {
_this11._connection._handleFatalError(error);
}
},
onCompleted: function onCompleted(metaData) {
_this11._connection._markInitialized(metaData);
_this11._resolveInitPromise(_this11._connection);
if (observer && observer.onCompleted) {
observer.onCompleted(metaData);
}
}
};
}
/**
* Get promise resolved when connection initialization succeed or rejected when it fails.
* @return {Promise<Connection>} the result of connection initialization.
*/
}, {
key: 'initializationCompleted',
value: function initializationCompleted() {
this._initRequested = true;
if (this._initError) {
var error = this._initError;
this._initError = null; // to reject initPromise only once
this._rejectInitPromise(error);
}
return this._initPromise;
}
/**
* @private
*/
}, {
key: '_processFailure',
value: function _processFailure(error) {
if (this._initRequested) {
// someone is waiting for initialization to complete, reject the promise
this._rejectInitPromise(error);
} else {
// no one is waiting for initialization, memorize the error but do not reject the promise
// to avoid unnecessary unhandled promise rejection warnings
this._initError = error;
}
}
}]);
return ConnectionState;
}();
/**
* Crete new connection to the provided address.
* @access private
* @param {string} hostPort - the Bolt endpoint to connect to
* @param {object} config - this driver configuration
* @param {string=null} connectionErrorCode - error code for errors raised on connection errors
* @return {Connection} - New connection
*/
function connect(hostPort) {
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var connectionErrorCode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var Ch = config.channel || Channel;
var parsedAddress = _urlUtil2.default.parseDatabaseUrl(hostPort);
var channelConfig = new _chConfig2.default(parsedAddress, config, connectionErrorCode);
return new Connection(new Ch(channelConfig), parsedAddress.hostAndPort, config.disableLosslessIntegers);
}
exports.connect = connect;
exports.Connection = Connection;

66
node_modules/neo4j-driver/lib/v1/internal/features.js generated vendored Normal file
View File

@@ -0,0 +1,66 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Central place to detect feature support for the current platform,
// expand as needed.
var FEATURES = {
trust_on_first_use: function trust_on_first_use() {
try {
// This is insane. We are verifying that we have a version of getPeerCertificate
// that supports reading the whole certificate, eg this commit:
// https://github.com/nodejs/node/commit/345c40b6
var getPeerCertificateFunction = require('tls').TLSSocket.prototype.getPeerCertificate;
var numberOfParameters = getPeerCertificateFunction.length;
return numberOfParameters >= 1;
} catch (e) {
return false;
}
},
trust_all_certificates: function trust_all_certificates() {
try {
var getPeerCertificateFunction = require('tls').TLSSocket.prototype.getPeerCertificate;
return true;
} catch (e) {
return false;
}
},
dns_lookup: function dns_lookup() {
try {
var lookupFunction = require('dns').lookup;
if (lookupFunction && typeof lookupFunction === 'function') {
return true;
}
return false;
} catch (e) {
return false;
}
}
};
function hasFeature(name) {
return FEATURES[name] && FEATURES[name]();
}
exports.default = hasFeature;

View File

@@ -0,0 +1,135 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DnsHostNameResolver = exports.DummyHostNameResolver = undefined;
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _urlUtil = require('./url-util');
var _urlUtil2 = _interopRequireDefault(_urlUtil);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var HostNameResolver = function () {
function HostNameResolver() {
(0, _classCallCheck3.default)(this, HostNameResolver);
}
(0, _createClass3.default)(HostNameResolver, [{
key: 'resolve',
value: function resolve() {
throw new Error('Abstract function');
}
}]);
return HostNameResolver;
}(); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DummyHostNameResolver = exports.DummyHostNameResolver = function (_HostNameResolver) {
(0, _inherits3.default)(DummyHostNameResolver, _HostNameResolver);
function DummyHostNameResolver() {
(0, _classCallCheck3.default)(this, DummyHostNameResolver);
return (0, _possibleConstructorReturn3.default)(this, (DummyHostNameResolver.__proto__ || (0, _getPrototypeOf2.default)(DummyHostNameResolver)).apply(this, arguments));
}
(0, _createClass3.default)(DummyHostNameResolver, [{
key: 'resolve',
value: function resolve(seedRouter) {
return resolveToItself(seedRouter);
}
}]);
return DummyHostNameResolver;
}(HostNameResolver);
var DnsHostNameResolver = exports.DnsHostNameResolver = function (_HostNameResolver2) {
(0, _inherits3.default)(DnsHostNameResolver, _HostNameResolver2);
function DnsHostNameResolver() {
(0, _classCallCheck3.default)(this, DnsHostNameResolver);
var _this2 = (0, _possibleConstructorReturn3.default)(this, (DnsHostNameResolver.__proto__ || (0, _getPrototypeOf2.default)(DnsHostNameResolver)).call(this));
_this2._dns = require('dns');
return _this2;
}
(0, _createClass3.default)(DnsHostNameResolver, [{
key: 'resolve',
value: function resolve(seedRouter) {
var _this3 = this;
var parsedAddress = _urlUtil2.default.parseDatabaseUrl(seedRouter);
return new _promise2.default(function (resolve) {
_this3._dns.lookup(parsedAddress.host, { all: true }, function (error, addresses) {
if (error) {
resolve(resolveToItself(seedRouter));
} else {
var addressesWithPorts = addresses.map(function (address) {
return addressWithPort(address, parsedAddress.port);
});
resolve(addressesWithPorts);
}
});
});
}
}]);
return DnsHostNameResolver;
}(HostNameResolver);
function resolveToItself(address) {
return _promise2.default.resolve([address]);
}
function addressWithPort(addressObject, port) {
var address = addressObject.address;
var addressFamily = addressObject.family;
if (!port) {
return address;
}
return addressFamily === 6 ? _urlUtil2.default.formatIPv6Address(address, port) : _urlUtil2.default.formatIPv4Address(address, port);
}

View File

@@ -0,0 +1,84 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _driver = require('../../driver');
var _driver2 = _interopRequireDefault(_driver);
var _httpSession = require('./http-session');
var _httpSession2 = _interopRequireDefault(_httpSession);
var _httpSessionTracker = require('./http-session-tracker');
var _httpSessionTracker2 = _interopRequireDefault(_httpSessionTracker);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var HttpDriver = function (_Driver) {
(0, _inherits3.default)(HttpDriver, _Driver);
function HttpDriver(hostPort, userAgent, token, config) {
(0, _classCallCheck3.default)(this, HttpDriver);
var _this = (0, _possibleConstructorReturn3.default)(this, (HttpDriver.__proto__ || (0, _getPrototypeOf2.default)(HttpDriver)).call(this, hostPort, userAgent, token, config));
_this._sessionTracker = new _httpSessionTracker2.default();
return _this;
}
(0, _createClass3.default)(HttpDriver, [{
key: 'session',
value: function session() {
return new _httpSession2.default(this._hostPort, this._token, this._config, this._sessionTracker);
}
}, {
key: 'close',
value: function close() {
return this._sessionTracker.close();
}
}]);
return HttpDriver;
}(_driver2.default); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = HttpDriver;

View File

@@ -0,0 +1,254 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _streamObserver = require('../stream-observer');
var _streamObserver2 = _interopRequireDefault(_streamObserver);
var _httpResponseConverter = require('./http-response-converter');
var _httpResponseConverter2 = _interopRequireDefault(_httpResponseConverter);
var _error = require('../../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var HttpRequestRunner = function () {
function HttpRequestRunner(url, authToken) {
(0, _classCallCheck3.default)(this, HttpRequestRunner);
this._url = url;
this._authToken = authToken;
this._converter = new _httpResponseConverter2.default();
}
/**
* Send a HTTP request to begin a transaction.
* @return {Promise<number>} promise resolved with the transaction id or rejected with an error.
*/
(0, _createClass3.default)(HttpRequestRunner, [{
key: 'beginTransaction',
value: function beginTransaction() {
var _this = this;
var url = beginTransactionUrl(this._url);
return sendRequest('POST', url, null, this._authToken).then(function (responseJson) {
var neo4jError = _this._converter.extractError(responseJson);
if (neo4jError) {
throw neo4jError;
}
return _this._converter.extractTransactionId(responseJson);
});
}
/**
* Send a HTTP request to commit a transaction.
* @param {number} transactionId id of the transaction to commit.
* @return {Promise<void>} promise resolved if transaction got committed or rejected when commit failed.
*/
}, {
key: 'commitTransaction',
value: function commitTransaction(transactionId) {
var _this2 = this;
var url = commitTransactionUrl(this._url, transactionId);
return sendRequest('POST', url, null, this._authToken).then(function (responseJson) {
var neo4jError = _this2._converter.extractError(responseJson);
if (neo4jError) {
throw neo4jError;
}
});
}
/**
* Send a HTTP request to rollback a transaction.
* @param {number} transactionId id of the transaction to rollback.
* @return {Promise<void>} promise resolved if transaction got rolled back or rejected when rollback failed.
*/
}, {
key: 'rollbackTransaction',
value: function rollbackTransaction(transactionId) {
var _this3 = this;
var url = transactionUrl(this._url, transactionId);
return sendRequest('DELETE', url, null, this._authToken).then(function (responseJson) {
var neo4jError = _this3._converter.extractError(responseJson);
if (neo4jError) {
throw neo4jError;
}
});
}
/**
* Send a HTTP request to execute a query in a transaction with the given id.
* @param {number} transactionId the transaction id.
* @param {string} statement the cypher query.
* @param {object} parameters the cypher query parameters.
* @return {Promise<StreamObserver>} a promise resolved with {@link StreamObserver} containing either records or error.
*/
}, {
key: 'runQuery',
value: function runQuery(transactionId, statement, parameters) {
var _this4 = this;
var streamObserver = new _streamObserver2.default();
var url = transactionUrl(this._url, transactionId);
var body = createStatementJson(statement, parameters, this._converter, streamObserver);
if (!body) {
// unable to encode given statement and parameters, return a failed stream observer
return _promise2.default.resolve(streamObserver);
}
return sendRequest('POST', url, body, this._authToken).then(function (responseJson) {
processResponseJson(responseJson, _this4._converter, streamObserver);
}).catch(function (error) {
streamObserver.onError(error);
}).then(function () {
return streamObserver;
});
}
}]);
return HttpRequestRunner;
}(); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = HttpRequestRunner;
function sendRequest(method, url, bodyString, authToken) {
try {
var options = {
method: method,
headers: createHttpHeaders(authToken),
body: bodyString
};
return new _promise2.default(function (resolve, reject) {
fetch(url, options).then(function (response) {
return response.json();
}).then(function (responseJson) {
return resolve(responseJson);
}).catch(function (error) {
return reject(new _error.Neo4jError(error.message, _error.SERVICE_UNAVAILABLE));
});
});
} catch (e) {
return _promise2.default.reject(e);
}
}
function createHttpHeaders(authToken) {
var headers = new Headers();
headers.append('Accept', 'application/json; charset=UTF-8');
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Basic ' + btoa(authToken.principal + ':' + authToken.credentials));
return headers;
}
function createStatementJson(statement, parameters, converter, streamObserver) {
try {
return createStatementJsonOrThrow(statement, parameters, converter);
} catch (e) {
streamObserver.onError(e);
return null;
}
}
function createStatementJsonOrThrow(statement, parameters, converter) {
var encodedParameters = converter.encodeStatementParameters(parameters);
return (0, _stringify2.default)({
statements: [{
statement: statement,
parameters: encodedParameters,
resultDataContents: ['row', 'graph'],
includeStats: true
}]
});
}
function processResponseJson(responseJson, converter, streamObserver) {
if (!responseJson) {
// request failed and there is no response
return;
}
try {
processResponseJsonOrThrow(responseJson, converter, streamObserver);
} catch (e) {
streamObserver.onError(e);
}
}
function processResponseJsonOrThrow(responseJson, converter, streamObserver) {
var neo4jError = converter.extractError(responseJson);
if (neo4jError) {
streamObserver.onError(neo4jError);
} else {
var recordMetadata = converter.extractRecordMetadata(responseJson);
streamObserver.onCompleted(recordMetadata);
var rawRecords = converter.extractRawRecords(responseJson);
rawRecords.forEach(function (rawRecord) {
return streamObserver.onNext(rawRecord);
});
var statementMetadata = converter.extractStatementMetadata(responseJson);
streamObserver.onCompleted(statementMetadata);
}
}
function beginTransactionUrl(baseUrl) {
return createUrl(baseUrl, '/db/data/transaction');
}
function commitTransactionUrl(baseUrl, transactionId) {
return transactionUrl(baseUrl, transactionId) + '/commit';
}
function transactionUrl(baseUrl, transactionId) {
return beginTransactionUrl(baseUrl) + '/' + transactionId;
}
function createUrl(baseUrl, path) {
return baseUrl.scheme + '://' + baseUrl.host + ':' + baseUrl.port + path;
}

View File

@@ -0,0 +1,461 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _integer = require('../../integer');
var _graphTypes = require('../../graph-types');
var _error = require('../../error');
var _spatialTypes = require('../../spatial-types');
var _temporalTypes = require('../../temporal-types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CREDENTIALS_EXPIRED_CODE = 'Neo.ClientError.Security.CredentialsExpired'; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var HttpResponseConverter = function () {
function HttpResponseConverter() {
(0, _classCallCheck3.default)(this, HttpResponseConverter);
}
(0, _createClass3.default)(HttpResponseConverter, [{
key: 'encodeStatementParameters',
value: function encodeStatementParameters(parameters) {
return encodeQueryParameters(parameters);
}
/**
* Attempts to extract error from transactional cypher endpoint response and convert it to {@link Neo4jError}.
* @param {object} response the response.
* @return {Neo4jError|null} new driver friendly error, if exists.
*/
}, {
key: 'extractError',
value: function extractError(response) {
var errors = response.errors;
if (errors) {
var error = errors[0];
if (error) {
// endpoint returns 'Neo.ClientError.Security.Forbidden' code and 'password_change' that points to another endpoint
// this is different from code returned via Bolt and less descriptive
// make code same as in Bolt, if password change is required
var code = response.password_change ? CREDENTIALS_EXPIRED_CODE : error.code;
var message = error.message;
return new _error.Neo4jError(message, code);
}
}
return null;
}
/**
* Extracts transaction id from the db/data/transaction endpoint response.
* @param {object} response the response.
* @return {number} the transaction id.
*/
}, {
key: 'extractTransactionId',
value: function extractTransactionId(response) {
var commitUrl = response.commit;
if (commitUrl) {
// extract id 42 from commit url like 'http://localhost:7474/db/data/transaction/42/commit'
var url = commitUrl.replace('/commit', '');
var transactionIdString = url.substring(url.lastIndexOf('/') + 1);
var transactionId = parseInt(transactionIdString, 10);
if (transactionId || transactionId === 0) {
return transactionId;
}
}
throw new _error.Neo4jError('Unable to extract transaction id from the response JSON: ' + (0, _stringify2.default)(response));
}
/**
* Extracts record metadata (array of column names) from transactional cypher endpoint response.
* @param {object} response the response.
* @return {object} new metadata object.
*/
}, {
key: 'extractRecordMetadata',
value: function extractRecordMetadata(response) {
var result = extractResult(response);
var fields = result ? result.columns : [];
return { fields: fields };
}
/**
* Extracts raw records (each raw record is just an array of value) from transactional cypher endpoint response.
* @param {object} response the response.
* @return {object[][]} raw records from the response.
*/
}, {
key: 'extractRawRecords',
value: function extractRawRecords(response) {
var result = extractResult(response);
if (result) {
var data = result.data;
if (data) {
return data.map(function (element) {
return extractRawRecord(element);
});
}
}
return [];
}
/**
* Extracts metadata for a completed statement.
* @param {object} response the response.
* @return {object} metadata as object.
*/
}, {
key: 'extractStatementMetadata',
value: function extractStatementMetadata(response) {
var result = extractResult(response);
if (result) {
var stats = result.stats;
if (stats) {
var convertedStats = (0, _keys2.default)(stats).reduce(function (newStats, key) {
if (key === 'contains_updates') {
// skip because such key does not exist in bolt
return newStats;
}
// fix key name for future parsing by StatementStatistics class
var newKey = (key === 'relationship_deleted' ? 'relationships_deleted' : key).replace('_', '-');
newStats[newKey] = stats[key];
return newStats;
}, {});
return { stats: convertedStats };
}
}
return {};
}
}]);
return HttpResponseConverter;
}();
exports.default = HttpResponseConverter;
function encodeQueryParameters(parameters) {
if (parameters && (typeof parameters === 'undefined' ? 'undefined' : (0, _typeof3.default)(parameters)) === 'object') {
return (0, _keys2.default)(parameters).reduce(function (result, key) {
result[key] = encodeQueryParameter(parameters[key]);
return result;
}, {});
}
return parameters;
}
function encodeQueryParameter(value) {
if (value instanceof _graphTypes.Node) {
throw new _error.Neo4jError('It is not allowed to pass nodes in query parameters', _error.PROTOCOL_ERROR);
} else if (value instanceof _graphTypes.Relationship) {
throw new _error.Neo4jError('It is not allowed to pass relationships in query parameters', _error.PROTOCOL_ERROR);
} else if (value instanceof _graphTypes.Path) {
throw new _error.Neo4jError('It is not allowed to pass paths in query parameters', _error.PROTOCOL_ERROR);
} else if ((0, _spatialTypes.isPoint)(value)) {
throw newUnsupportedParameterError('points');
} else if ((0, _temporalTypes.isDate)(value)) {
throw newUnsupportedParameterError('dates');
} else if ((0, _temporalTypes.isDateTime)(value)) {
throw newUnsupportedParameterError('date-time');
} else if ((0, _temporalTypes.isDuration)(value)) {
throw newUnsupportedParameterError('durations');
} else if ((0, _temporalTypes.isLocalDateTime)(value)) {
throw newUnsupportedParameterError('local date-time');
} else if ((0, _temporalTypes.isLocalTime)(value)) {
throw newUnsupportedParameterError('local time');
} else if ((0, _temporalTypes.isTime)(value)) {
throw newUnsupportedParameterError('time');
} else if ((0, _integer.isInt)(value)) {
return value.toNumber();
} else if (Array.isArray(value)) {
return value.map(function (element) {
return encodeQueryParameter(element);
});
} else if ((typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object') {
return encodeQueryParameters(value);
} else {
return value;
}
}
function newUnsupportedParameterError(name) {
return new _error.Neo4jError('It is not allowed to pass ' + name + ' in query parameters when using HTTP endpoint. ' + ('Please consider using Cypher functions to create ' + name + ' so that query parameters are plain objects.'), _error.PROTOCOL_ERROR);
}
function extractResult(response) {
var results = response.results;
if (results) {
var result = results[0];
if (result) {
return result;
}
}
return null;
}
function extractRawRecord(data) {
var row = data.row;
var nodesById = indexNodesById(data);
var relationshipsById = indexRelationshipsById(data);
if (row) {
return row.map(function (ignore, index) {
return extractRawRecordElement(index, data, nodesById, relationshipsById);
});
}
return [];
}
function indexNodesById(data) {
var graph = data.graph;
if (graph) {
var nodes = graph.nodes;
if (nodes) {
return nodes.reduce(function (result, node) {
var identity = convertNumber(node.id);
var labels = node.labels;
var properties = convertPrimitiveValue(node.properties);
result[node.id] = new _graphTypes.Node(identity, labels, properties);
return result;
}, {});
}
}
return {};
}
function indexRelationshipsById(data) {
var graph = data.graph;
if (graph) {
var relationships = graph.relationships;
if (relationships) {
return relationships.reduce(function (result, relationship) {
var identity = convertNumber(relationship.id);
var startNode = convertNumber(relationship.startNode);
var endNode = convertNumber(relationship.endNode);
var type = relationship.type;
var properties = convertPrimitiveValue(relationship.properties);
result[relationship.id] = new _graphTypes.Relationship(identity, startNode, endNode, type, properties);
return result;
}, {});
}
}
return {};
}
function extractRawRecordElement(index, data, nodesById, relationshipsById) {
var element = data.row ? data.row[index] : null;
var elementMetadata = data.meta ? data.meta[index] : null;
if (elementMetadata) {
// element is either a graph, spatial or temporal type
return convertComplexValue(element, elementMetadata, nodesById, relationshipsById);
} else {
// element is a primitive, like number, string, array or object
return convertPrimitiveValue(element);
}
}
function convertComplexValue(element, elementMetadata, nodesById, relationshipsById) {
if (isNodeMetadata(elementMetadata)) {
return nodesById[elementMetadata.id];
} else if (isRelationshipMetadata(elementMetadata)) {
return relationshipsById[elementMetadata.id];
} else if (isPathMetadata(elementMetadata)) {
return convertPath(elementMetadata, nodesById, relationshipsById);
} else if (isPointMetadata(elementMetadata)) {
return convertPoint(element);
} else {
return element;
}
}
function convertPath(metadata, nodesById, relationshipsById) {
var startNode = null;
var relationship = null;
var pathSegments = [];
for (var i = 0; i < metadata.length; i++) {
var element = metadata[i];
var elementId = element.id;
var elementType = element.type;
var nodeExpected = startNode === null && relationship === null || startNode !== null && relationship !== null;
if (nodeExpected && elementType !== 'node') {
throw new _error.Neo4jError('Unable to parse path, node expected but got: ' + (0, _stringify2.default)(element) + ' in ' + (0, _stringify2.default)(metadata));
}
if (!nodeExpected && elementType === 'node') {
throw new _error.Neo4jError('Unable to parse path, relationship expected but got: ' + (0, _stringify2.default)(element) + ' in ' + (0, _stringify2.default)(metadata));
}
if (nodeExpected) {
var node = nodesById[elementId];
if (startNode === null) {
startNode = node;
} else if (startNode !== null && relationship !== null) {
var pathSegment = new _graphTypes.PathSegment(startNode, relationship, node);
pathSegments.push(pathSegment);
startNode = node;
relationship = null;
} else {
throw new _error.Neo4jError('Unable to parse path, illegal node configuration: ' + (0, _stringify2.default)(metadata));
}
} else {
if (relationship === null) {
relationship = relationshipsById[elementId];
} else {
throw new _error.Neo4jError('Unable to parse path, illegal relationship configuration: ' + (0, _stringify2.default)(metadata));
}
}
}
var lastPathSegment = pathSegments[pathSegments.length - 1];
if (lastPathSegment && lastPathSegment.end !== startNode || relationship !== null) {
throw new _error.Neo4jError('Unable to parse path: ' + (0, _stringify2.default)(metadata));
}
return createPath(pathSegments);
}
function createPath(pathSegments) {
var pathStartNode = pathSegments[0].start;
var pathEndNode = pathSegments[pathSegments.length - 1].end;
return new _graphTypes.Path(pathStartNode, pathEndNode, pathSegments);
}
function convertPoint(element) {
var type = element.type;
if (type !== 'Point') {
throw new _error.Neo4jError('Unexpected Point type received: ' + (0, _stringify2.default)(element));
}
var coordinates = element.coordinates;
if (!Array.isArray(coordinates) && (coordinates.length !== 2 || coordinates.length !== 3)) {
throw new _error.Neo4jError('Unexpected Point coordinates received: ' + (0, _stringify2.default)(element));
}
var srid = convertCrsToId(element);
return new (Function.prototype.bind.apply(_spatialTypes.Point, [null].concat([srid], (0, _toConsumableArray3.default)(coordinates))))();
}
function convertCrsToId(element) {
var crs = element.crs;
if (!crs || !crs.name) {
throw new _error.Neo4jError('Unexpected Point crs received: ' + (0, _stringify2.default)(element));
}
var name = crs.name.toLowerCase();
if (name === 'wgs-84') {
return 4326;
} else if (name === 'wgs-84-3d') {
return 4979;
} else if (name === 'cartesian') {
return 7203;
} else if (name === 'cartesian-3d') {
return 9157;
} else {
throw new _error.Neo4jError('Unexpected Point crs received: ' + (0, _stringify2.default)(element));
}
}
function convertPrimitiveValue(element) {
if (element == null || element === undefined) {
return null;
} else if (typeof element === 'number') {
return convertNumber(element);
} else if (Array.isArray(element)) {
return element.map(function (element) {
return convertPrimitiveValue(element);
});
} else if ((typeof element === 'undefined' ? 'undefined' : (0, _typeof3.default)(element)) === 'object') {
return (0, _keys2.default)(element).reduce(function (result, key) {
result[key] = convertPrimitiveValue(element[key]);
return result;
}, {});
} else {
return element;
}
}
function convertNumber(value) {
return typeof value === 'number' ? value : Number(value);
}
function isNodeMetadata(metadata) {
return isMetadataForType('node', metadata);
}
function isRelationshipMetadata(metadata) {
return isMetadataForType('relationship', metadata);
}
function isPointMetadata(metadata) {
return isMetadataForType('point', metadata);
}
function isMetadataForType(name, metadata) {
return !Array.isArray(metadata) && (typeof metadata === 'undefined' ? 'undefined' : (0, _typeof3.default)(metadata)) === 'object' && metadata.type === name;
}
function isPathMetadata(metadata) {
return Array.isArray(metadata);
}

View File

@@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = require("babel-runtime/core-js/promise");
var _promise2 = _interopRequireDefault(_promise);
var _from = require("babel-runtime/core-js/array/from");
var _from2 = _interopRequireDefault(_from);
var _set = require("babel-runtime/core-js/set");
var _set2 = _interopRequireDefault(_set);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var HttpSessionTracker = function () {
function HttpSessionTracker() {
(0, _classCallCheck3.default)(this, HttpSessionTracker);
this._openSessions = new _set2.default();
}
/**
* Record given session as open.
* @param {HttpSession} session the newly open session.
*/
(0, _createClass3.default)(HttpSessionTracker, [{
key: "sessionOpened",
value: function sessionOpened(session) {
this._openSessions.add(session);
}
/**
* Record given session as close.
* @param {HttpSession} session the just closed session.
*/
}, {
key: "sessionClosed",
value: function sessionClosed(session) {
this._openSessions.delete(session);
}
/**
* Close this tracker and all open sessions.
*/
}, {
key: "close",
value: function close() {
var sessions = (0, _from2.default)(this._openSessions);
this._openSessions.clear();
return _promise2.default.all(sessions.map(function (session) {
return closeSession(session);
}));
}
}]);
return HttpSessionTracker;
}();
/**
* Close given session and get a promise back.
* @param {HttpSession} session the session to close.
* @return {Promise<void>} promise resolved when session is closed.
*/
exports.default = HttpSessionTracker;
function closeSession(session) {
return new _promise2.default(function (resolve) {
session.close(function () {
resolve();
});
});
}

View File

@@ -0,0 +1,188 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _driver = require('../../driver');
var _session = require('../../session');
var _session2 = _interopRequireDefault(_session);
var _util = require('../util');
var _error = require('../../error');
var _httpRequestRunner = require('./http-request-runner');
var _httpRequestRunner2 = _interopRequireDefault(_httpRequestRunner);
var _connectionHolder = require('../connection-holder');
var _result = require('../../result');
var _result2 = _interopRequireDefault(_result);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var HttpSession = function (_Session) {
(0, _inherits3.default)(HttpSession, _Session);
function HttpSession(url, authToken, config, sessionTracker) {
(0, _classCallCheck3.default)(this, HttpSession);
var _this = (0, _possibleConstructorReturn3.default)(this, (HttpSession.__proto__ || (0, _getPrototypeOf2.default)(HttpSession)).call(this, _driver.WRITE, null, null, config));
_this._ongoingTransactionIds = [];
_this._serverInfoSupplier = createServerInfoSupplier(url);
_this._requestRunner = new _httpRequestRunner2.default(url, authToken);
_this._sessionTracker = sessionTracker;
_this._sessionTracker.sessionOpened(_this);
return _this;
}
(0, _createClass3.default)(HttpSession, [{
key: 'run',
value: function run(statement) {
var _this2 = this;
var parameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _validateStatementAnd = (0, _util.validateStatementAndParameters)(statement, parameters),
query = _validateStatementAnd.query,
params = _validateStatementAnd.params;
return this._requestRunner.beginTransaction().then(function (transactionId) {
_this2._ongoingTransactionIds.push(transactionId);
var queryPromise = _this2._requestRunner.runQuery(transactionId, query, params);
return queryPromise.then(function (streamObserver) {
if (streamObserver.hasFailed()) {
return rollbackTransactionAfterQueryFailure(transactionId, streamObserver, _this2._requestRunner);
} else {
return commitTransactionAfterQuerySuccess(transactionId, streamObserver, _this2._requestRunner);
}
}).then(function (streamObserver) {
_this2._ongoingTransactionIds = _this2._ongoingTransactionIds.filter(function (id) {
return id !== transactionId;
});
return new _result2.default(streamObserver, query, params, _this2._serverInfoSupplier, _connectionHolder.EMPTY_CONNECTION_HOLDER);
});
});
}
}, {
key: 'beginTransaction',
value: function beginTransaction() {
throwTransactionsNotSupported();
}
}, {
key: 'readTransaction',
value: function readTransaction() {
throwTransactionsNotSupported();
}
}, {
key: 'writeTransaction',
value: function writeTransaction() {
throwTransactionsNotSupported();
}
}, {
key: 'lastBookmark',
value: function lastBookmark() {
throw new _error.Neo4jError('Experimental HTTP driver does not support bookmarks and routing');
}
}, {
key: 'close',
value: function close() {
var _this3 = this;
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
return null;
};
var rollbackAllOngoingTransactions = this._ongoingTransactionIds.map(function (transactionId) {
return rollbackTransactionSilently(transactionId, _this3._requestRunner);
});
_promise2.default.all(rollbackAllOngoingTransactions).then(function () {
_this3._sessionTracker.sessionClosed(_this3);
callback();
});
}
}]);
return HttpSession;
}(_session2.default); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = HttpSession;
function rollbackTransactionAfterQueryFailure(transactionId, streamObserver, requestRunner) {
return rollbackTransactionSilently(transactionId, requestRunner).then(function () {
return streamObserver;
});
}
function commitTransactionAfterQuerySuccess(transactionId, streamObserver, requestRunner) {
return requestRunner.commitTransaction(transactionId).catch(function (error) {
streamObserver.onError(error);
}).then(function () {
return streamObserver;
});
}
function rollbackTransactionSilently(transactionId, requestRunner) {
return requestRunner.rollbackTransaction(transactionId).catch(function (error) {
// ignore all rollback errors
});
}
function createServerInfoSupplier(url) {
return function () {
return { server: { address: url.hostAndPort } };
};
}
function throwTransactionsNotSupported() {
throw new _error.Neo4jError('Experimental HTTP driver does not support transactions');
}

View File

@@ -0,0 +1,139 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LEAST_CONNECTED_STRATEGY_NAME = undefined;
var _maxSafeInteger = require('babel-runtime/core-js/number/max-safe-integer');
var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _roundRobinArrayIndex = require('./round-robin-array-index');
var _roundRobinArrayIndex2 = _interopRequireDefault(_roundRobinArrayIndex);
var _loadBalancingStrategy = require('./load-balancing-strategy');
var _loadBalancingStrategy2 = _interopRequireDefault(_loadBalancingStrategy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var LEAST_CONNECTED_STRATEGY_NAME = exports.LEAST_CONNECTED_STRATEGY_NAME = 'least_connected';
var LeastConnectedLoadBalancingStrategy = function (_LoadBalancingStrateg) {
(0, _inherits3.default)(LeastConnectedLoadBalancingStrategy, _LoadBalancingStrateg);
/**
* @constructor
* @param {Pool} connectionPool the connection pool of this driver.
*/
function LeastConnectedLoadBalancingStrategy(connectionPool) {
(0, _classCallCheck3.default)(this, LeastConnectedLoadBalancingStrategy);
var _this = (0, _possibleConstructorReturn3.default)(this, (LeastConnectedLoadBalancingStrategy.__proto__ || (0, _getPrototypeOf2.default)(LeastConnectedLoadBalancingStrategy)).call(this));
_this._readersIndex = new _roundRobinArrayIndex2.default();
_this._writersIndex = new _roundRobinArrayIndex2.default();
_this._connectionPool = connectionPool;
return _this;
}
/**
* @inheritDoc
*/
(0, _createClass3.default)(LeastConnectedLoadBalancingStrategy, [{
key: 'selectReader',
value: function selectReader(knownReaders) {
return this._select(knownReaders, this._readersIndex);
}
/**
* @inheritDoc
*/
}, {
key: 'selectWriter',
value: function selectWriter(knownWriters) {
return this._select(knownWriters, this._writersIndex);
}
}, {
key: '_select',
value: function _select(addresses, roundRobinIndex) {
var length = addresses.length;
if (length === 0) {
return null;
}
// choose start index for iteration in round-robin fashion
var startIndex = roundRobinIndex.next(length);
var index = startIndex;
var leastConnectedAddress = null;
var leastActiveConnections = _maxSafeInteger2.default;
// iterate over the array to find least connected address
do {
var address = addresses[index];
var activeConnections = this._connectionPool.activeResourceCount(address);
if (activeConnections < leastActiveConnections) {
leastConnectedAddress = address;
leastActiveConnections = activeConnections;
}
// loop over to the start of the array when end is reached
if (index === length - 1) {
index = 0;
} else {
index++;
}
} while (index !== startIndex);
return leastConnectedAddress;
}
}]);
return LeastConnectedLoadBalancingStrategy;
}(_loadBalancingStrategy2.default);
exports.default = LeastConnectedLoadBalancingStrategy;

View File

@@ -0,0 +1,72 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A facility to select most appropriate reader or writer among the given addresses for request processing.
*/
var LoadBalancingStrategy = function () {
function LoadBalancingStrategy() {
(0, _classCallCheck3.default)(this, LoadBalancingStrategy);
}
(0, _createClass3.default)(LoadBalancingStrategy, [{
key: 'selectReader',
/**
* Select next most appropriate reader from the list of given readers.
* @param {string[]} knownReaders an array of currently known readers to select from.
* @return {string} most appropriate reader or <code>null</code> if given array is empty.
*/
value: function selectReader(knownReaders) {
throw new Error('Abstract function');
}
/**
* Select next most appropriate writer from the list of given writers.
* @param {string[]} knownWriters an array of currently known writers to select from.
* @return {string} most appropriate writer or <code>null</code> if given array is empty.
*/
}, {
key: 'selectWriter',
value: function selectWriter(knownWriters) {
throw new Error('Abstract function');
}
}]);
return LoadBalancingStrategy;
}();
exports.default = LoadBalancingStrategy;

View File

@@ -0,0 +1,68 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _packstreamV = require('./packstream-v1');
var v1 = _interopRequireWildcard(_packstreamV);
var _packstreamV2 = require('./packstream-v2');
var v2 = _interopRequireWildcard(_packstreamV2);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var PACKER_CONSTRUCTORS_BY_VERSION = [null, v1.Packer, v2.Packer];
var UNPACKER_CONSTRUCTORS_BY_VERSION = [null, v1.Unpacker, v2.Unpacker];
function createLatestPacker(chunker) {
return createPackerForProtocolVersion(PACKER_CONSTRUCTORS_BY_VERSION.length - 1, chunker);
}
function createLatestUnpacker(disableLosslessIntegers) {
return createUnpackerForProtocolVersion(UNPACKER_CONSTRUCTORS_BY_VERSION.length - 1, disableLosslessIntegers);
}
function createPackerForProtocolVersion(version, chunker) {
var packerConstructor = PACKER_CONSTRUCTORS_BY_VERSION[version];
if (!packerConstructor) {
throw new Error('Packer can\'t be created for protocol version ' + version);
}
return new packerConstructor(chunker);
}
function createUnpackerForProtocolVersion(version, disableLosslessIntegers) {
var unpackerConstructor = UNPACKER_CONSTRUCTORS_BY_VERSION[version];
if (!unpackerConstructor) {
throw new Error('Unpacker can\'t be created for protocol version ' + version);
}
return new unpackerConstructor(disableLosslessIntegers);
}
exports.default = {
createLatestPacker: createLatestPacker,
createLatestUnpacker: createLatestUnpacker,
createPackerForProtocolVersion: createPackerForProtocolVersion,
createUnpackerForProtocolVersion: createUnpackerForProtocolVersion
};

View File

@@ -0,0 +1,777 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Structure = exports.Unpacker = exports.Packer = undefined;
var _iterator = require('babel-runtime/core-js/symbol/iterator');
var _iterator2 = _interopRequireDefault(_iterator);
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _utf = require('./utf8');
var _utf2 = _interopRequireDefault(_utf);
var _integer = require('../integer');
var _integer2 = _interopRequireDefault(_integer);
var _error = require('./../error');
var _chunking = require('./chunking');
var _graphTypes = require('../graph-types');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TINY_STRING = 0x80; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var TINY_LIST = 0x90;
var TINY_MAP = 0xA0;
var TINY_STRUCT = 0xB0;
var NULL = 0xC0;
var FLOAT_64 = 0xC1;
var FALSE = 0xC2;
var TRUE = 0xC3;
var INT_8 = 0xC8;
var INT_16 = 0xC9;
var INT_32 = 0xCA;
var INT_64 = 0xCB;
var STRING_8 = 0xD0;
var STRING_16 = 0xD1;
var STRING_32 = 0xD2;
var LIST_8 = 0xD4;
var LIST_16 = 0xD5;
var LIST_32 = 0xD6;
var BYTES_8 = 0xCC;
var BYTES_16 = 0xCD;
var BYTES_32 = 0xCE;
var MAP_8 = 0xD8;
var MAP_16 = 0xD9;
var MAP_32 = 0xDA;
var STRUCT_8 = 0xDC;
var STRUCT_16 = 0xDD;
var NODE = 0x4E;
var NODE_STRUCT_SIZE = 3;
var RELATIONSHIP = 0x52;
var RELATIONSHIP_STRUCT_SIZE = 5;
var UNBOUND_RELATIONSHIP = 0x72;
var UNBOUND_RELATIONSHIP_STRUCT_SIZE = 3;
var PATH = 0x50;
var PATH_STRUCT_SIZE = 3;
/**
* A Structure have a signature and fields.
* @access private
*/
var Structure = function () {
/**
* Create new instance
*/
function Structure(signature, fields) {
(0, _classCallCheck3.default)(this, Structure);
this.signature = signature;
this.fields = fields;
}
(0, _createClass3.default)(Structure, [{
key: 'toString',
value: function toString() {
var fieldStr = "";
for (var i = 0; i < this.fields.length; i++) {
if (i > 0) {
fieldStr += ", ";
}
fieldStr += this.fields[i];
}
return "Structure(" + this.signature + ", [" + this.fields + "])";
}
}]);
return Structure;
}();
/**
* Class to pack
* @access private
*/
var Packer = function () {
/**
* @constructor
* @param {Chunker} channel the chunker backed by a network channel.
*/
function Packer(channel) {
(0, _classCallCheck3.default)(this, Packer);
this._ch = channel;
this._byteArraysSupported = true;
}
/**
* Creates a packable function out of the provided value
* @param x the value to pack
* @param onError callback for the case when value cannot be packed
* @returns Function
*/
(0, _createClass3.default)(Packer, [{
key: 'packable',
value: function packable(x, onError) {
var _this = this;
if (x === null) {
return function () {
return _this._ch.writeUInt8(NULL);
};
} else if (x === true) {
return function () {
return _this._ch.writeUInt8(TRUE);
};
} else if (x === false) {
return function () {
return _this._ch.writeUInt8(FALSE);
};
} else if (typeof x == "number") {
return function () {
return _this.packFloat(x);
};
} else if (typeof x == "string") {
return function () {
return _this.packString(x, onError);
};
} else if ((0, _integer.isInt)(x)) {
return function () {
return _this.packInteger(x);
};
} else if (x instanceof Int8Array) {
return function () {
return _this.packBytes(x, onError);
};
} else if (x instanceof Array) {
return function () {
_this.packListHeader(x.length, onError);
for (var _i = 0; _i < x.length; _i++) {
_this.packable(x[_i] === undefined ? null : x[_i], onError)();
}
};
} else if (isIterable(x)) {
return this.packableIterable(x, onError);
} else if (x instanceof _graphTypes.Node) {
return this._nonPackableValue('It is not allowed to pass nodes in query parameters, given: ' + x, onError);
} else if (x instanceof _graphTypes.Relationship) {
return this._nonPackableValue('It is not allowed to pass relationships in query parameters, given: ' + x, onError);
} else if (x instanceof _graphTypes.Path) {
return this._nonPackableValue('It is not allowed to pass paths in query parameters, given: ' + x, onError);
} else if (x instanceof Structure) {
var packableFields = [];
for (var i = 0; i < x.fields.length; i++) {
packableFields[i] = this.packable(x.fields[i], onError);
}
return function () {
return _this.packStruct(x.signature, packableFields);
};
} else if ((typeof x === 'undefined' ? 'undefined' : (0, _typeof3.default)(x)) == "object") {
return function () {
var keys = (0, _keys2.default)(x);
var count = 0;
for (var _i2 = 0; _i2 < keys.length; _i2++) {
if (x[keys[_i2]] !== undefined) {
count++;
}
}
_this.packMapHeader(count, onError);
for (var _i3 = 0; _i3 < keys.length; _i3++) {
var key = keys[_i3];
if (x[key] !== undefined) {
_this.packString(key);
_this.packable(x[key], onError)();
}
}
};
} else {
return this._nonPackableValue('Unable to pack the given value: ' + x, onError);
}
}
}, {
key: 'packableIterable',
value: function packableIterable(iterable, onError) {
try {
var array = (0, _from2.default)(iterable);
return this.packable(array, onError);
} catch (e) {
// handle errors from iterable to array conversion
onError((0, _error.newError)('Cannot pack given iterable, ' + e.message + ': ' + iterable));
}
}
/**
* Packs a struct
* @param signature the signature of the struct
* @param packableFields the fields of the struct, make sure you call `packable on all fields`
*/
}, {
key: 'packStruct',
value: function packStruct(signature, packableFields, onError) {
packableFields = packableFields || [];
this.packStructHeader(packableFields.length, signature, onError);
for (var i = 0; i < packableFields.length; i++) {
packableFields[i]();
}
}
}, {
key: 'packInteger',
value: function packInteger(x) {
var high = x.high,
low = x.low;
if (x.greaterThanOrEqual(-0x10) && x.lessThan(0x80)) {
this._ch.writeInt8(low);
} else if (x.greaterThanOrEqual(-0x80) && x.lessThan(-0x10)) {
this._ch.writeUInt8(INT_8);
this._ch.writeInt8(low);
} else if (x.greaterThanOrEqual(-0x8000) && x.lessThan(0x8000)) {
this._ch.writeUInt8(INT_16);
this._ch.writeInt16(low);
} else if (x.greaterThanOrEqual(-0x80000000) && x.lessThan(0x80000000)) {
this._ch.writeUInt8(INT_32);
this._ch.writeInt32(low);
} else {
this._ch.writeUInt8(INT_64);
this._ch.writeInt32(high);
this._ch.writeInt32(low);
}
}
}, {
key: 'packFloat',
value: function packFloat(x) {
this._ch.writeUInt8(FLOAT_64);
this._ch.writeFloat64(x);
}
}, {
key: 'packString',
value: function packString(x, onError) {
var bytes = _utf2.default.encode(x);
var size = bytes.length;
if (size < 0x10) {
this._ch.writeUInt8(TINY_STRING | size);
this._ch.writeBytes(bytes);
} else if (size < 0x100) {
this._ch.writeUInt8(STRING_8);
this._ch.writeUInt8(size);
this._ch.writeBytes(bytes);
} else if (size < 0x10000) {
this._ch.writeUInt8(STRING_16);
this._ch.writeUInt8(size / 256 >> 0);
this._ch.writeUInt8(size % 256);
this._ch.writeBytes(bytes);
} else if (size < 0x100000000) {
this._ch.writeUInt8(STRING_32);
this._ch.writeUInt8((size / 16777216 >> 0) % 256);
this._ch.writeUInt8((size / 65536 >> 0) % 256);
this._ch.writeUInt8((size / 256 >> 0) % 256);
this._ch.writeUInt8(size % 256);
this._ch.writeBytes(bytes);
} else {
onError((0, _error.newError)("UTF-8 strings of size " + size + " are not supported"));
}
}
}, {
key: 'packListHeader',
value: function packListHeader(size, onError) {
if (size < 0x10) {
this._ch.writeUInt8(TINY_LIST | size);
} else if (size < 0x100) {
this._ch.writeUInt8(LIST_8);
this._ch.writeUInt8(size);
} else if (size < 0x10000) {
this._ch.writeUInt8(LIST_16);
this._ch.writeUInt8((size / 256 >> 0) % 256);
this._ch.writeUInt8(size % 256);
} else if (size < 0x100000000) {
this._ch.writeUInt8(LIST_32);
this._ch.writeUInt8((size / 16777216 >> 0) % 256);
this._ch.writeUInt8((size / 65536 >> 0) % 256);
this._ch.writeUInt8((size / 256 >> 0) % 256);
this._ch.writeUInt8(size % 256);
} else {
onError((0, _error.newError)("Lists of size " + size + " are not supported"));
}
}
}, {
key: 'packBytes',
value: function packBytes(array, onError) {
if (this._byteArraysSupported) {
this.packBytesHeader(array.length, onError);
for (var i = 0; i < array.length; i++) {
this._ch.writeInt8(array[i]);
}
} else {
onError((0, _error.newError)("Byte arrays are not supported by the database this driver is connected to"));
}
}
}, {
key: 'packBytesHeader',
value: function packBytesHeader(size, onError) {
if (size < 0x100) {
this._ch.writeUInt8(BYTES_8);
this._ch.writeUInt8(size);
} else if (size < 0x10000) {
this._ch.writeUInt8(BYTES_16);
this._ch.writeUInt8((size / 256 >> 0) % 256);
this._ch.writeUInt8(size % 256);
} else if (size < 0x100000000) {
this._ch.writeUInt8(BYTES_32);
this._ch.writeUInt8((size / 16777216 >> 0) % 256);
this._ch.writeUInt8((size / 65536 >> 0) % 256);
this._ch.writeUInt8((size / 256 >> 0) % 256);
this._ch.writeUInt8(size % 256);
} else {
onError((0, _error.newError)('Byte arrays of size ' + size + ' are not supported'));
}
}
}, {
key: 'packMapHeader',
value: function packMapHeader(size, onError) {
if (size < 0x10) {
this._ch.writeUInt8(TINY_MAP | size);
} else if (size < 0x100) {
this._ch.writeUInt8(MAP_8);
this._ch.writeUInt8(size);
} else if (size < 0x10000) {
this._ch.writeUInt8(MAP_16);
this._ch.writeUInt8(size / 256 >> 0);
this._ch.writeUInt8(size % 256);
} else if (size < 0x100000000) {
this._ch.writeUInt8(MAP_32);
this._ch.writeUInt8((size / 16777216 >> 0) % 256);
this._ch.writeUInt8((size / 65536 >> 0) % 256);
this._ch.writeUInt8((size / 256 >> 0) % 256);
this._ch.writeUInt8(size % 256);
} else {
onError((0, _error.newError)("Maps of size " + size + " are not supported"));
}
}
}, {
key: 'packStructHeader',
value: function packStructHeader(size, signature, onError) {
if (size < 0x10) {
this._ch.writeUInt8(TINY_STRUCT | size);
this._ch.writeUInt8(signature);
} else if (size < 0x100) {
this._ch.writeUInt8(STRUCT_8);
this._ch.writeUInt8(size);
this._ch.writeUInt8(signature);
} else if (size < 0x10000) {
this._ch.writeUInt8(STRUCT_16);
this._ch.writeUInt8(size / 256 >> 0);
this._ch.writeUInt8(size % 256);
} else {
onError((0, _error.newError)("Structures of size " + size + " are not supported"));
}
}
}, {
key: 'disableByteArrays',
value: function disableByteArrays() {
this._byteArraysSupported = false;
}
}, {
key: '_nonPackableValue',
value: function _nonPackableValue(message, onError) {
if (onError) {
onError((0, _error.newError)(message, _error.PROTOCOL_ERROR));
}
return function () {
return undefined;
};
}
}]);
return Packer;
}();
/**
* Class to unpack
* @access private
*/
var Unpacker = function () {
/**
* @constructor
* @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers.
*/
function Unpacker() {
var disableLosslessIntegers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
(0, _classCallCheck3.default)(this, Unpacker);
this._disableLosslessIntegers = disableLosslessIntegers;
}
(0, _createClass3.default)(Unpacker, [{
key: 'unpack',
value: function unpack(buffer) {
var marker = buffer.readUInt8();
var markerHigh = marker & 0xF0;
var markerLow = marker & 0x0F;
if (marker == NULL) {
return null;
}
var boolean = this._unpackBoolean(marker);
if (boolean !== null) {
return boolean;
}
var numberOrInteger = this._unpackNumberOrInteger(marker, buffer);
if (numberOrInteger !== null) {
if (this._disableLosslessIntegers && (0, _integer.isInt)(numberOrInteger)) {
return numberOrInteger.toNumberOrInfinity();
}
return numberOrInteger;
}
var string = this._unpackString(marker, markerHigh, markerLow, buffer);
if (string !== null) {
return string;
}
var list = this._unpackList(marker, markerHigh, markerLow, buffer);
if (list !== null) {
return list;
}
var byteArray = this._unpackByteArray(marker, buffer);
if (byteArray !== null) {
return byteArray;
}
var map = this._unpackMap(marker, markerHigh, markerLow, buffer);
if (map !== null) {
return map;
}
var struct = this._unpackStruct(marker, markerHigh, markerLow, buffer);
if (struct !== null) {
return struct;
}
throw (0, _error.newError)('Unknown packed value with marker ' + marker.toString(16));
}
}, {
key: 'unpackInteger',
value: function unpackInteger(buffer) {
var marker = buffer.readUInt8();
var result = this._unpackInteger(marker, buffer);
if (result == null) {
throw (0, _error.newError)('Unable to unpack integer value with marker ' + marker.toString(16));
}
return result;
}
}, {
key: '_unpackBoolean',
value: function _unpackBoolean(marker) {
if (marker == TRUE) {
return true;
} else if (marker == FALSE) {
return false;
} else {
return null;
}
}
}, {
key: '_unpackNumberOrInteger',
value: function _unpackNumberOrInteger(marker, buffer) {
if (marker == FLOAT_64) {
return buffer.readFloat64();
} else {
return this._unpackInteger(marker, buffer);
}
}
}, {
key: '_unpackInteger',
value: function _unpackInteger(marker, buffer) {
if (marker >= 0 && marker < 128) {
return (0, _integer.int)(marker);
} else if (marker >= 240 && marker < 256) {
return (0, _integer.int)(marker - 256);
} else if (marker == INT_8) {
return (0, _integer.int)(buffer.readInt8());
} else if (marker == INT_16) {
return (0, _integer.int)(buffer.readInt16());
} else if (marker == INT_32) {
var b = buffer.readInt32();
return (0, _integer.int)(b);
} else if (marker == INT_64) {
var high = buffer.readInt32();
var low = buffer.readInt32();
return new _integer2.default(low, high);
} else {
return null;
}
}
}, {
key: '_unpackString',
value: function _unpackString(marker, markerHigh, markerLow, buffer) {
if (markerHigh == TINY_STRING) {
return _utf2.default.decode(buffer, markerLow);
} else if (marker == STRING_8) {
return _utf2.default.decode(buffer, buffer.readUInt8());
} else if (marker == STRING_16) {
return _utf2.default.decode(buffer, buffer.readUInt16());
} else if (marker == STRING_32) {
return _utf2.default.decode(buffer, buffer.readUInt32());
} else {
return null;
}
}
}, {
key: '_unpackList',
value: function _unpackList(marker, markerHigh, markerLow, buffer) {
if (markerHigh == TINY_LIST) {
return this._unpackListWithSize(markerLow, buffer);
} else if (marker == LIST_8) {
return this._unpackListWithSize(buffer.readUInt8(), buffer);
} else if (marker == LIST_16) {
return this._unpackListWithSize(buffer.readUInt16(), buffer);
} else if (marker == LIST_32) {
return this._unpackListWithSize(buffer.readUInt32(), buffer);
} else {
return null;
}
}
}, {
key: '_unpackListWithSize',
value: function _unpackListWithSize(size, buffer) {
var value = [];
for (var i = 0; i < size; i++) {
value.push(this.unpack(buffer));
}
return value;
}
}, {
key: '_unpackByteArray',
value: function _unpackByteArray(marker, buffer) {
if (marker == BYTES_8) {
return this._unpackByteArrayWithSize(buffer.readUInt8(), buffer);
} else if (marker == BYTES_16) {
return this._unpackByteArrayWithSize(buffer.readUInt16(), buffer);
} else if (marker == BYTES_32) {
return this._unpackByteArrayWithSize(buffer.readUInt32(), buffer);
} else {
return null;
}
}
}, {
key: '_unpackByteArrayWithSize',
value: function _unpackByteArrayWithSize(size, buffer) {
var value = new Int8Array(size);
for (var i = 0; i < size; i++) {
value[i] = buffer.readInt8();
}
return value;
}
}, {
key: '_unpackMap',
value: function _unpackMap(marker, markerHigh, markerLow, buffer) {
if (markerHigh == TINY_MAP) {
return this._unpackMapWithSize(markerLow, buffer);
} else if (marker == MAP_8) {
return this._unpackMapWithSize(buffer.readUInt8(), buffer);
} else if (marker == MAP_16) {
return this._unpackMapWithSize(buffer.readUInt16(), buffer);
} else if (marker == MAP_32) {
return this._unpackMapWithSize(buffer.readUInt32(), buffer);
} else {
return null;
}
}
}, {
key: '_unpackMapWithSize',
value: function _unpackMapWithSize(size, buffer) {
var value = {};
for (var i = 0; i < size; i++) {
var key = this.unpack(buffer);
value[key] = this.unpack(buffer);
}
return value;
}
}, {
key: '_unpackStruct',
value: function _unpackStruct(marker, markerHigh, markerLow, buffer) {
if (markerHigh == TINY_STRUCT) {
return this._unpackStructWithSize(markerLow, buffer);
} else if (marker == STRUCT_8) {
return this._unpackStructWithSize(buffer.readUInt8(), buffer);
} else if (marker == STRUCT_16) {
return this._unpackStructWithSize(buffer.readUInt16(), buffer);
} else {
return null;
}
}
}, {
key: '_unpackStructWithSize',
value: function _unpackStructWithSize(structSize, buffer) {
var signature = buffer.readUInt8();
if (signature == NODE) {
return this._unpackNode(structSize, buffer);
} else if (signature == RELATIONSHIP) {
return this._unpackRelationship(structSize, buffer);
} else if (signature == UNBOUND_RELATIONSHIP) {
return this._unpackUnboundRelationship(structSize, buffer);
} else if (signature == PATH) {
return this._unpackPath(structSize, buffer);
} else {
return this._unpackUnknownStruct(signature, structSize, buffer);
}
}
}, {
key: '_unpackNode',
value: function _unpackNode(structSize, buffer) {
this._verifyStructSize('Node', NODE_STRUCT_SIZE, structSize);
return new _graphTypes.Node(this.unpack(buffer), // Identity
this.unpack(buffer), // Labels
this.unpack(buffer) // Properties
);
}
}, {
key: '_unpackRelationship',
value: function _unpackRelationship(structSize, buffer) {
this._verifyStructSize('Relationship', RELATIONSHIP_STRUCT_SIZE, structSize);
return new _graphTypes.Relationship(this.unpack(buffer), // Identity
this.unpack(buffer), // Start Node Identity
this.unpack(buffer), // End Node Identity
this.unpack(buffer), // Type
this.unpack(buffer) // Properties
);
}
}, {
key: '_unpackUnboundRelationship',
value: function _unpackUnboundRelationship(structSize, buffer) {
this._verifyStructSize('UnboundRelationship', UNBOUND_RELATIONSHIP_STRUCT_SIZE, structSize);
return new _graphTypes.UnboundRelationship(this.unpack(buffer), // Identity
this.unpack(buffer), // Type
this.unpack(buffer) // Properties
);
}
}, {
key: '_unpackPath',
value: function _unpackPath(structSize, buffer) {
this._verifyStructSize('Path', PATH_STRUCT_SIZE, structSize);
var nodes = this.unpack(buffer);
var rels = this.unpack(buffer);
var sequence = this.unpack(buffer);
var segments = [];
var prevNode = nodes[0];
for (var i = 0; i < sequence.length; i += 2) {
var nextNode = nodes[sequence[i + 1]];
var relIndex = sequence[i];
var rel = void 0;
if (relIndex > 0) {
rel = rels[relIndex - 1];
if (rel instanceof _graphTypes.UnboundRelationship) {
// To avoid duplication, relationships in a path do not contain
// information about their start and end nodes, that's instead
// inferred from the path sequence. This is us inferring (and,
// for performance reasons remembering) the start/end of a rel.
rels[relIndex - 1] = rel = rel.bind(prevNode.identity, nextNode.identity);
}
} else {
rel = rels[-relIndex - 1];
if (rel instanceof _graphTypes.UnboundRelationship) {
// See above
rels[-relIndex - 1] = rel = rel.bind(nextNode.identity, prevNode.identity);
}
}
// Done hydrating one path segment.
segments.push(new _graphTypes.PathSegment(prevNode, rel, nextNode));
prevNode = nextNode;
}
return new _graphTypes.Path(nodes[0], nodes[nodes.length - 1], segments);
}
}, {
key: '_unpackUnknownStruct',
value: function _unpackUnknownStruct(signature, structSize, buffer) {
var result = new Structure(signature, []);
for (var i = 0; i < structSize; i++) {
result.fields.push(this.unpack(buffer));
}
return result;
}
}, {
key: '_verifyStructSize',
value: function _verifyStructSize(structName, expectedSize, actualSize) {
if (expectedSize !== actualSize) {
throw (0, _error.newError)('Wrong struct size for ' + structName + ', expected ' + expectedSize + ' but was ' + actualSize, _error.PROTOCOL_ERROR);
}
}
}]);
return Unpacker;
}();
function isIterable(obj) {
if (obj == null) {
return false;
}
return typeof obj[_iterator2.default] === 'function';
}
exports.Packer = Packer;
exports.Unpacker = Unpacker;
exports.Structure = Structure;

View File

@@ -0,0 +1,528 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Unpacker = exports.Packer = undefined;
var _freeze = require('babel-runtime/core-js/object/freeze');
var _freeze2 = _interopRequireDefault(_freeze);
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _get2 = require('babel-runtime/helpers/get');
var _get3 = _interopRequireDefault(_get2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _packstreamV = require('./packstream-v1');
var v1 = _interopRequireWildcard(_packstreamV);
var _spatialTypes = require('../spatial-types');
var _temporalTypes = require('../temporal-types');
var _integer = require('../integer');
var _temporalUtil = require('../internal/temporal-util');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var POINT_2D = 0x58; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var POINT_2D_STRUCT_SIZE = 3;
var POINT_3D = 0x59;
var POINT_3D_STRUCT_SIZE = 4;
var DURATION = 0x45;
var DURATION_STRUCT_SIZE = 4;
var LOCAL_TIME = 0x74;
var LOCAL_TIME_STRUCT_SIZE = 1;
var TIME = 0x54;
var TIME_STRUCT_SIZE = 2;
var DATE = 0x44;
var DATE_STRUCT_SIZE = 1;
var LOCAL_DATE_TIME = 0x64;
var LOCAL_DATE_TIME_STRUCT_SIZE = 2;
var DATE_TIME_WITH_ZONE_OFFSET = 0x46;
var DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE = 3;
var DATE_TIME_WITH_ZONE_ID = 0x66;
var DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE = 3;
var Packer = exports.Packer = function (_v1$Packer) {
(0, _inherits3.default)(Packer, _v1$Packer);
/**
* @constructor
* @param {Chunker} chunker the chunker backed by a network channel.
*/
function Packer(chunker) {
(0, _classCallCheck3.default)(this, Packer);
return (0, _possibleConstructorReturn3.default)(this, (Packer.__proto__ || (0, _getPrototypeOf2.default)(Packer)).call(this, chunker));
}
(0, _createClass3.default)(Packer, [{
key: 'disableByteArrays',
value: function disableByteArrays() {
throw new Error('Bolt V2 should always support byte arrays');
}
}, {
key: 'packable',
value: function packable(obj, onError) {
var _this2 = this;
if ((0, _spatialTypes.isPoint)(obj)) {
return function () {
return packPoint(obj, _this2, onError);
};
} else if ((0, _temporalTypes.isDuration)(obj)) {
return function () {
return packDuration(obj, _this2, onError);
};
} else if ((0, _temporalTypes.isLocalTime)(obj)) {
return function () {
return packLocalTime(obj, _this2, onError);
};
} else if ((0, _temporalTypes.isTime)(obj)) {
return function () {
return packTime(obj, _this2, onError);
};
} else if ((0, _temporalTypes.isDate)(obj)) {
return function () {
return packDate(obj, _this2, onError);
};
} else if ((0, _temporalTypes.isLocalDateTime)(obj)) {
return function () {
return packLocalDateTime(obj, _this2, onError);
};
} else if ((0, _temporalTypes.isDateTime)(obj)) {
return function () {
return packDateTime(obj, _this2, onError);
};
} else {
return (0, _get3.default)(Packer.prototype.__proto__ || (0, _getPrototypeOf2.default)(Packer.prototype), 'packable', this).call(this, obj, onError);
}
}
}]);
return Packer;
}(v1.Packer);
var Unpacker = exports.Unpacker = function (_v1$Unpacker) {
(0, _inherits3.default)(Unpacker, _v1$Unpacker);
/**
* @constructor
* @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers.
*/
function Unpacker() {
var disableLosslessIntegers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
(0, _classCallCheck3.default)(this, Unpacker);
return (0, _possibleConstructorReturn3.default)(this, (Unpacker.__proto__ || (0, _getPrototypeOf2.default)(Unpacker)).call(this, disableLosslessIntegers));
}
(0, _createClass3.default)(Unpacker, [{
key: '_unpackUnknownStruct',
value: function _unpackUnknownStruct(signature, structSize, buffer) {
if (signature == POINT_2D) {
return unpackPoint2D(this, structSize, buffer);
} else if (signature == POINT_3D) {
return unpackPoint3D(this, structSize, buffer);
} else if (signature == DURATION) {
return unpackDuration(this, structSize, buffer);
} else if (signature == LOCAL_TIME) {
return unpackLocalTime(this, structSize, buffer, this._disableLosslessIntegers);
} else if (signature == TIME) {
return unpackTime(this, structSize, buffer, this._disableLosslessIntegers);
} else if (signature == DATE) {
return unpackDate(this, structSize, buffer, this._disableLosslessIntegers);
} else if (signature == LOCAL_DATE_TIME) {
return unpackLocalDateTime(this, structSize, buffer, this._disableLosslessIntegers);
} else if (signature == DATE_TIME_WITH_ZONE_OFFSET) {
return unpackDateTimeWithZoneOffset(this, structSize, buffer, this._disableLosslessIntegers);
} else if (signature == DATE_TIME_WITH_ZONE_ID) {
return unpackDateTimeWithZoneId(this, structSize, buffer, this._disableLosslessIntegers);
} else {
return (0, _get3.default)(Unpacker.prototype.__proto__ || (0, _getPrototypeOf2.default)(Unpacker.prototype), '_unpackUnknownStruct', this).call(this, signature, structSize, buffer, this._disableLosslessIntegers);
}
}
}]);
return Unpacker;
}(v1.Unpacker);
/**
* Pack given 2D or 3D point.
* @param {Point} point the point value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packPoint(point, packer, onError) {
var is2DPoint = point.z === null || point.z === undefined;
if (is2DPoint) {
packPoint2D(point, packer, onError);
} else {
packPoint3D(point, packer, onError);
}
}
/**
* Pack given 2D point.
* @param {Point} point the point value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packPoint2D(point, packer, onError) {
var packableStructFields = [packer.packable((0, _integer.int)(point.srid), onError), packer.packable(point.x, onError), packer.packable(point.y, onError)];
packer.packStruct(POINT_2D, packableStructFields, onError);
}
/**
* Pack given 3D point.
* @param {Point} point the point value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packPoint3D(point, packer, onError) {
var packableStructFields = [packer.packable((0, _integer.int)(point.srid), onError), packer.packable(point.x, onError), packer.packable(point.y, onError), packer.packable(point.z, onError)];
packer.packStruct(POINT_3D, packableStructFields, onError);
}
/**
* Unpack 2D point value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @return {Point} the unpacked 2D point value.
*/
function unpackPoint2D(unpacker, structSize, buffer) {
unpacker._verifyStructSize('Point2D', POINT_2D_STRUCT_SIZE, structSize);
return new _spatialTypes.Point(unpacker.unpack(buffer), // srid
unpacker.unpack(buffer), // x
unpacker.unpack(buffer), // y
undefined // z
);
}
/**
* Unpack 3D point value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @return {Point} the unpacked 3D point value.
*/
function unpackPoint3D(unpacker, structSize, buffer) {
unpacker._verifyStructSize('Point3D', POINT_3D_STRUCT_SIZE, structSize);
return new _spatialTypes.Point(unpacker.unpack(buffer), // srid
unpacker.unpack(buffer), // x
unpacker.unpack(buffer), // y
unpacker.unpack(buffer) // z
);
}
/**
* Pack given duration.
* @param {Duration} value the duration value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packDuration(value, packer, onError) {
var months = (0, _integer.int)(value.months);
var days = (0, _integer.int)(value.days);
var seconds = (0, _integer.int)(value.seconds);
var nanoseconds = (0, _integer.int)(value.nanoseconds);
var packableStructFields = [packer.packable(months, onError), packer.packable(days, onError), packer.packable(seconds, onError), packer.packable(nanoseconds, onError)];
packer.packStruct(DURATION, packableStructFields, onError);
}
/**
* Unpack duration value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @return {Duration} the unpacked duration value.
*/
function unpackDuration(unpacker, structSize, buffer) {
unpacker._verifyStructSize('Duration', DURATION_STRUCT_SIZE, structSize);
var months = unpacker.unpack(buffer);
var days = unpacker.unpack(buffer);
var seconds = unpacker.unpack(buffer);
var nanoseconds = unpacker.unpack(buffer);
return new _temporalTypes.Duration(months, days, seconds, nanoseconds);
}
/**
* Pack given local time.
* @param {LocalTime} value the local time value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packLocalTime(value, packer, onError) {
var nanoOfDay = (0, _temporalUtil.localTimeToNanoOfDay)(value.hour, value.minute, value.second, value.nanosecond);
var packableStructFields = [packer.packable(nanoOfDay, onError)];
packer.packStruct(LOCAL_TIME, packableStructFields, onError);
}
/**
* Unpack local time value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @param {boolean} disableLosslessIntegers if integer properties in the result local time should be native JS numbers.
* @return {LocalTime} the unpacked local time value.
*/
function unpackLocalTime(unpacker, structSize, buffer, disableLosslessIntegers) {
unpacker._verifyStructSize('LocalTime', LOCAL_TIME_STRUCT_SIZE, structSize);
var nanoOfDay = unpacker.unpackInteger(buffer);
var result = (0, _temporalUtil.nanoOfDayToLocalTime)(nanoOfDay);
return convertIntegerPropsIfNeeded(result, disableLosslessIntegers);
}
/**
* Pack given time.
* @param {Time} value the time value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packTime(value, packer, onError) {
var nanoOfDay = (0, _temporalUtil.localTimeToNanoOfDay)(value.hour, value.minute, value.second, value.nanosecond);
var offsetSeconds = (0, _integer.int)(value.timeZoneOffsetSeconds);
var packableStructFields = [packer.packable(nanoOfDay, onError), packer.packable(offsetSeconds, onError)];
packer.packStruct(TIME, packableStructFields, onError);
}
/**
* Unpack time value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @param {boolean} disableLosslessIntegers if integer properties in the result time should be native JS numbers.
* @return {Time} the unpacked time value.
*/
function unpackTime(unpacker, structSize, buffer, disableLosslessIntegers) {
unpacker._verifyStructSize('Time', TIME_STRUCT_SIZE, structSize);
var nanoOfDay = unpacker.unpackInteger(buffer);
var offsetSeconds = unpacker.unpackInteger(buffer);
var localTime = (0, _temporalUtil.nanoOfDayToLocalTime)(nanoOfDay);
var result = new _temporalTypes.Time(localTime.hour, localTime.minute, localTime.second, localTime.nanosecond, offsetSeconds);
return convertIntegerPropsIfNeeded(result, disableLosslessIntegers);
}
/**
* Pack given neo4j date.
* @param {Date} value the date value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packDate(value, packer, onError) {
var epochDay = (0, _temporalUtil.dateToEpochDay)(value.year, value.month, value.day);
var packableStructFields = [packer.packable(epochDay, onError)];
packer.packStruct(DATE, packableStructFields, onError);
}
/**
* Unpack neo4j date value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @param {boolean} disableLosslessIntegers if integer properties in the result date should be native JS numbers.
* @return {Date} the unpacked neo4j date value.
*/
function unpackDate(unpacker, structSize, buffer, disableLosslessIntegers) {
unpacker._verifyStructSize('Date', DATE_STRUCT_SIZE, structSize);
var epochDay = unpacker.unpackInteger(buffer);
var result = (0, _temporalUtil.epochDayToDate)(epochDay);
return convertIntegerPropsIfNeeded(result, disableLosslessIntegers);
}
/**
* Pack given local date time.
* @param {LocalDateTime} value the local date time value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packLocalDateTime(value, packer, onError) {
var epochSecond = (0, _temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
var nano = (0, _integer.int)(value.nanosecond);
var packableStructFields = [packer.packable(epochSecond, onError), packer.packable(nano, onError)];
packer.packStruct(LOCAL_DATE_TIME, packableStructFields, onError);
}
/**
* Unpack local date time value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @param {boolean} disableLosslessIntegers if integer properties in the result local date-time should be native JS numbers.
* @return {LocalDateTime} the unpacked local date time value.
*/
function unpackLocalDateTime(unpacker, structSize, buffer, disableLosslessIntegers) {
unpacker._verifyStructSize('LocalDateTime', LOCAL_DATE_TIME_STRUCT_SIZE, structSize);
var epochSecond = unpacker.unpackInteger(buffer);
var nano = unpacker.unpackInteger(buffer);
var result = (0, _temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
return convertIntegerPropsIfNeeded(result, disableLosslessIntegers);
}
/**
* Pack given date time.
* @param {DateTime} value the date time value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packDateTime(value, packer, onError) {
if (value.timeZoneId) {
packDateTimeWithZoneId(value, packer, onError);
} else {
packDateTimeWithZoneOffset(value, packer, onError);
}
}
/**
* Pack given date time with zone offset.
* @param {DateTime} value the date time value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packDateTimeWithZoneOffset(value, packer, onError) {
var epochSecond = (0, _temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
var nano = (0, _integer.int)(value.nanosecond);
var timeZoneOffsetSeconds = (0, _integer.int)(value.timeZoneOffsetSeconds);
var packableStructFields = [packer.packable(epochSecond, onError), packer.packable(nano, onError), packer.packable(timeZoneOffsetSeconds, onError)];
packer.packStruct(DATE_TIME_WITH_ZONE_OFFSET, packableStructFields, onError);
}
/**
* Unpack date time with zone offset value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @param {boolean} disableLosslessIntegers if integer properties in the result date-time should be native JS numbers.
* @return {DateTime} the unpacked date time with zone offset value.
*/
function unpackDateTimeWithZoneOffset(unpacker, structSize, buffer, disableLosslessIntegers) {
unpacker._verifyStructSize('DateTimeWithZoneOffset', DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE, structSize);
var epochSecond = unpacker.unpackInteger(buffer);
var nano = unpacker.unpackInteger(buffer);
var timeZoneOffsetSeconds = unpacker.unpackInteger(buffer);
var localDateTime = (0, _temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
var result = new _temporalTypes.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, timeZoneOffsetSeconds, null);
return convertIntegerPropsIfNeeded(result, disableLosslessIntegers);
}
/**
* Pack given date time with zone id.
* @param {DateTime} value the date time value to pack.
* @param {Packer} packer the packer to use.
* @param {function} onError the error callback.
*/
function packDateTimeWithZoneId(value, packer, onError) {
var epochSecond = (0, _temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
var nano = (0, _integer.int)(value.nanosecond);
var timeZoneId = value.timeZoneId;
var packableStructFields = [packer.packable(epochSecond, onError), packer.packable(nano, onError), packer.packable(timeZoneId, onError)];
packer.packStruct(DATE_TIME_WITH_ZONE_ID, packableStructFields, onError);
}
/**
* Unpack date time with zone id value using the given unpacker.
* @param {Unpacker} unpacker the unpacker to use.
* @param {number} structSize the retrieved struct size.
* @param {BaseBuffer} buffer the buffer to unpack from.
* @param {boolean} disableLosslessIntegers if integer properties in the result date-time should be native JS numbers.
* @return {DateTime} the unpacked date time with zone id value.
*/
function unpackDateTimeWithZoneId(unpacker, structSize, buffer, disableLosslessIntegers) {
unpacker._verifyStructSize('DateTimeWithZoneId', DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE, structSize);
var epochSecond = unpacker.unpackInteger(buffer);
var nano = unpacker.unpackInteger(buffer);
var timeZoneId = unpacker.unpack(buffer);
var localDateTime = (0, _temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
var result = new _temporalTypes.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, null, timeZoneId);
return convertIntegerPropsIfNeeded(result, disableLosslessIntegers);
}
function convertIntegerPropsIfNeeded(obj, disableLosslessIntegers) {
if (!disableLosslessIntegers) {
return obj;
}
var clone = (0, _create2.default)((0, _getPrototypeOf2.default)(obj));
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var value = obj[prop];
clone[prop] = (0, _integer.isInt)(value) ? value.toNumberOrInfinity() : value;
}
}
(0, _freeze2.default)(clone);
return clone;
}

View File

@@ -0,0 +1,93 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULT_ACQUISITION_TIMEOUT = exports.DEFAULT_MAX_SIZE = undefined;
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_MAX_SIZE = 100;
var DEFAULT_ACQUISITION_TIMEOUT = 60 * 1000; // 60 seconds
var PoolConfig = function () {
function PoolConfig(maxSize, acquisitionTimeout) {
(0, _classCallCheck3.default)(this, PoolConfig);
this.maxSize = valueOrDefault(maxSize, DEFAULT_MAX_SIZE);
this.acquisitionTimeout = valueOrDefault(acquisitionTimeout, DEFAULT_ACQUISITION_TIMEOUT);
}
(0, _createClass3.default)(PoolConfig, null, [{
key: 'defaultConfig',
value: function defaultConfig() {
return new PoolConfig(DEFAULT_MAX_SIZE, DEFAULT_ACQUISITION_TIMEOUT);
}
}, {
key: 'fromDriverConfig',
value: function fromDriverConfig(config) {
var maxIdleSizeConfigured = isConfigured(config.connectionPoolSize);
var maxSizeConfigured = isConfigured(config.maxConnectionPoolSize);
var maxSize = void 0;
if (maxSizeConfigured) {
// correct size setting is set - use it's value
maxSize = config.maxConnectionPoolSize;
} else if (maxIdleSizeConfigured) {
// deprecated size setting is set - use it's value
console.warn('WARNING: neo4j-driver setting "connectionPoolSize" is deprecated, please use "maxConnectionPoolSize" instead');
maxSize = config.connectionPoolSize;
} else {
maxSize = DEFAULT_MAX_SIZE;
}
var acquisitionTimeoutConfigured = isConfigured(config.connectionAcquisitionTimeout);
var acquisitionTimeout = acquisitionTimeoutConfigured ? config.connectionAcquisitionTimeout : DEFAULT_ACQUISITION_TIMEOUT;
return new PoolConfig(maxSize, acquisitionTimeout);
}
}]);
return PoolConfig;
}();
exports.default = PoolConfig;
function valueOrDefault(value, defaultValue) {
return value === 0 || value ? value : defaultValue;
}
function isConfigured(value) {
return value === 0 || value;
}
exports.DEFAULT_MAX_SIZE = DEFAULT_MAX_SIZE;
exports.DEFAULT_ACQUISITION_TIMEOUT = DEFAULT_ACQUISITION_TIMEOUT;

290
node_modules/neo4j-driver/lib/v1/internal/pool.js generated vendored Normal file
View File

@@ -0,0 +1,290 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _poolConfig = require('./pool-config');
var _poolConfig2 = _interopRequireDefault(_poolConfig);
var _error = require('../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Pool = function () {
/**
* @param {function} create an allocation function that creates a new resource. It's given
* a single argument, a function that will return the resource to
* the pool if invoked, which is meant to be called on .dispose
* or .close or whatever mechanism the resource uses to finalize.
* @param {function} destroy called with the resource when it is evicted from this pool
* @param {function} validate called at various times (like when an instance is acquired and
* when it is returned). If this returns false, the resource will
* be evicted
* @param {PoolConfig} config configuration for the new driver.
*/
function Pool(create) {
var destroy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
return true;
};
var validate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {
return true;
};
var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _poolConfig2.default.defaultConfig();
(0, _classCallCheck3.default)(this, Pool);
this._create = create;
this._destroy = destroy;
this._validate = validate;
this._maxSize = config.maxSize;
this._acquisitionTimeout = config.acquisitionTimeout;
this._pools = {};
this._acquireRequests = {};
this._activeResourceCounts = {};
this._release = this._release.bind(this);
}
/**
* Acquire and idle resource fom the pool or create a new one.
* @param {string} key the resource key.
* @return {object} resource that is ready to use.
*/
(0, _createClass3.default)(Pool, [{
key: 'acquire',
value: function acquire(key) {
var _this = this;
var resource = this._acquire(key);
if (resource) {
resourceAcquired(key, this._activeResourceCounts);
return _promise2.default.resolve(resource);
}
// We're out of resources and will try to acquire later on when an existing resource is released.
var allRequests = this._acquireRequests;
var requests = allRequests[key];
if (!requests) {
allRequests[key] = [];
}
return new _promise2.default(function (resolve, reject) {
var request = void 0;
var timeoutId = setTimeout(function () {
allRequests[key] = allRequests[key].filter(function (item) {
return item !== request;
});
reject((0, _error.newError)('Connection acquisition timed out in ' + _this._acquisitionTimeout + ' ms.'));
}, _this._acquisitionTimeout);
request = new PendingRequest(resolve, timeoutId);
allRequests[key].push(request);
});
}
/**
* Destroy all idle resources for the given key.
* @param {string} key the resource key to purge.
*/
}, {
key: 'purge',
value: function purge(key) {
var pool = this._pools[key] || [];
while (pool.length) {
var resource = pool.pop();
this._destroy(resource);
}
delete this._pools[key];
}
/**
* Destroy all idle resources in this pool.
*/
}, {
key: 'purgeAll',
value: function purgeAll() {
var _this2 = this;
(0, _keys2.default)(this._pools).forEach(function (key) {
return _this2.purge(key);
});
}
/**
* Check if this pool contains resources for the given key.
* @param {string} key the resource key to check.
* @return {boolean} <code>true</code> when pool contains entries for the given key, <code>false</code> otherwise.
*/
}, {
key: 'has',
value: function has(key) {
return key in this._pools;
}
/**
* Get count of active (checked out of the pool) resources for the given key.
* @param {string} key the resource key to check.
* @return {number} count of resources acquired by clients.
*/
}, {
key: 'activeResourceCount',
value: function activeResourceCount(key) {
return this._activeResourceCounts[key] || 0;
}
}, {
key: '_acquire',
value: function _acquire(key) {
var pool = this._pools[key];
if (!pool) {
pool = [];
this._pools[key] = pool;
}
while (pool.length) {
var resource = pool.pop();
if (this._validate(resource)) {
// idle resource is valid and can be acquired
return resource;
} else {
this._destroy(resource);
}
}
if (this._maxSize && this.activeResourceCount(key) >= this._maxSize) {
return null;
}
// there exist no idle valid resources, create a new one for acquisition
return this._create(key, this._release);
}
}, {
key: '_release',
value: function _release(key, resource) {
var pool = this._pools[key];
if (pool) {
// there exist idle connections for the given key
if (!this._validate(resource)) {
this._destroy(resource);
} else {
pool.push(resource);
}
} else {
// key has been purged, don't put it back, just destroy the resource
this._destroy(resource);
}
resourceReleased(key, this._activeResourceCounts);
// check if there are any pending requests
var requests = this._acquireRequests[key];
if (requests) {
var pending = requests[0];
if (pending) {
var _resource = this._acquire(key);
if (_resource) {
// managed to acquire a valid resource from the pool to satisfy the pending acquire request
resourceAcquired(key, this._activeResourceCounts); // increment the active counter
requests.shift(); // forget the pending request
pending.resolve(_resource); // resolve the pending request with the acquired resource
}
} else {
delete this._acquireRequests[key];
}
}
}
}]);
return Pool;
}();
/**
* Increment active (checked out of the pool) resource counter.
* @param {string} key the resource group identifier (server address for connections).
* @param {Object.<string, number>} activeResourceCounts the object holding active counts per key.
*/
function resourceAcquired(key, activeResourceCounts) {
var currentCount = activeResourceCounts[key] || 0;
activeResourceCounts[key] = currentCount + 1;
}
/**
* Decrement active (checked out of the pool) resource counter.
* @param {string} key the resource group identifier (server address for connections).
* @param {Object.<string, number>} activeResourceCounts the object holding active counts per key.
*/
function resourceReleased(key, activeResourceCounts) {
var currentCount = activeResourceCounts[key] || 0;
var nextCount = currentCount - 1;
if (nextCount > 0) {
activeResourceCounts[key] = nextCount;
} else {
delete activeResourceCounts[key];
}
}
var PendingRequest = function () {
function PendingRequest(resolve, timeoutId) {
(0, _classCallCheck3.default)(this, PendingRequest);
this._resolve = resolve;
this._timeoutId = timeoutId;
}
(0, _createClass3.default)(PendingRequest, [{
key: 'resolve',
value: function resolve(resource) {
clearTimeout(this._timeoutId);
this._resolve(resource);
}
}]);
return PendingRequest;
}();
exports.default = Pool;

View File

@@ -0,0 +1,109 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _routingTable = require('./routing-table');
var _routingTable2 = _interopRequireDefault(_routingTable);
var _error = require('../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Rediscovery = function () {
/**
* @constructor
* @param {RoutingUtil} routingUtil the util to use.
*/
function Rediscovery(routingUtil) {
(0, _classCallCheck3.default)(this, Rediscovery);
this._routingUtil = routingUtil;
}
/**
* Try to fetch new routing table from the given router.
* @param {Session} session the session to use.
* @param {string} routerAddress the URL of the router.
* @return {Promise<RoutingTable>} promise resolved with new routing table or null when connection error happened.
*/
(0, _createClass3.default)(Rediscovery, [{
key: 'lookupRoutingTableOnRouter',
value: function lookupRoutingTableOnRouter(session, routerAddress) {
var _this = this;
return this._routingUtil.callRoutingProcedure(session, routerAddress).then(function (records) {
if (records === null) {
// connection error happened, unable to retrieve routing table from this router, next one should be queried
return null;
}
if (records.length !== 1) {
throw (0, _error.newError)('Illegal response from router "' + routerAddress + '". ' + 'Received ' + records.length + ' records but expected only one.\n' + (0, _stringify2.default)(records), _error.PROTOCOL_ERROR);
}
var record = records[0];
var expirationTime = _this._routingUtil.parseTtl(record, routerAddress);
var _routingUtil$parseSer = _this._routingUtil.parseServers(record, routerAddress),
routers = _routingUtil$parseSer.routers,
readers = _routingUtil$parseSer.readers,
writers = _routingUtil$parseSer.writers;
Rediscovery._assertNonEmpty(routers, 'routers', routerAddress);
Rediscovery._assertNonEmpty(readers, 'readers', routerAddress);
// case with no writers is processed higher in the promise chain because only RoutingDriver knows
// how to deal with such table and how to treat router that returned such table
return new _routingTable2.default(routers, readers, writers, expirationTime);
});
}
}], [{
key: '_assertNonEmpty',
value: function _assertNonEmpty(serverAddressesArray, serversName, routerAddress) {
if (serverAddressesArray.length === 0) {
throw (0, _error.newError)('Received no ' + serversName + ' from router ' + routerAddress, _error.PROTOCOL_ERROR);
}
}
}]);
return Rediscovery;
}();
exports.default = Rediscovery;

View File

@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _maxSafeInteger = require("babel-runtime/core-js/number/max-safe-integer");
var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var RoundRobinArrayIndex = function () {
/**
* @constructor
* @param {number} [initialOffset=0] the initial offset for round robin.
*/
function RoundRobinArrayIndex(initialOffset) {
(0, _classCallCheck3.default)(this, RoundRobinArrayIndex);
this._offset = initialOffset || 0;
}
/**
* Get next index for an array with given length.
* @param {number} arrayLength the array length.
* @return {number} index in the array.
*/
(0, _createClass3.default)(RoundRobinArrayIndex, [{
key: "next",
value: function next(arrayLength) {
if (arrayLength === 0) {
return -1;
}
var nextOffset = this._offset;
this._offset += 1;
if (this._offset === _maxSafeInteger2.default) {
this._offset = 0;
}
return nextOffset % arrayLength;
}
}]);
return RoundRobinArrayIndex;
}();
exports.default = RoundRobinArrayIndex;

View File

@@ -0,0 +1,106 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ROUND_ROBIN_STRATEGY_NAME = undefined;
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _roundRobinArrayIndex = require('./round-robin-array-index');
var _roundRobinArrayIndex2 = _interopRequireDefault(_roundRobinArrayIndex);
var _loadBalancingStrategy = require('./load-balancing-strategy');
var _loadBalancingStrategy2 = _interopRequireDefault(_loadBalancingStrategy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ROUND_ROBIN_STRATEGY_NAME = exports.ROUND_ROBIN_STRATEGY_NAME = 'round_robin';
var RoundRobinLoadBalancingStrategy = function (_LoadBalancingStrateg) {
(0, _inherits3.default)(RoundRobinLoadBalancingStrategy, _LoadBalancingStrateg);
function RoundRobinLoadBalancingStrategy() {
(0, _classCallCheck3.default)(this, RoundRobinLoadBalancingStrategy);
var _this = (0, _possibleConstructorReturn3.default)(this, (RoundRobinLoadBalancingStrategy.__proto__ || (0, _getPrototypeOf2.default)(RoundRobinLoadBalancingStrategy)).call(this));
_this._readersIndex = new _roundRobinArrayIndex2.default();
_this._writersIndex = new _roundRobinArrayIndex2.default();
return _this;
}
/**
* @inheritDoc
*/
(0, _createClass3.default)(RoundRobinLoadBalancingStrategy, [{
key: 'selectReader',
value: function selectReader(knownReaders) {
return this._select(knownReaders, this._readersIndex);
}
/**
* @inheritDoc
*/
}, {
key: 'selectWriter',
value: function selectWriter(knownWriters) {
return this._select(knownWriters, this._writersIndex);
}
}, {
key: '_select',
value: function _select(addresses, roundRobinIndex) {
var length = addresses.length;
if (length === 0) {
return null;
}
var index = roundRobinIndex.next(length);
return addresses[index];
}
}]);
return RoundRobinLoadBalancingStrategy;
}(_loadBalancingStrategy2.default);
exports.default = RoundRobinLoadBalancingStrategy;

View File

@@ -0,0 +1,133 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
var _set = require('babel-runtime/core-js/set');
var _set2 = _interopRequireDefault(_set);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _integer = require('../integer');
var _driver = require('../driver');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var MIN_ROUTERS = 1;
var RoutingTable = function () {
function RoutingTable(routers, readers, writers, expirationTime) {
(0, _classCallCheck3.default)(this, RoutingTable);
this.routers = routers || [];
this.readers = readers || [];
this.writers = writers || [];
this.expirationTime = expirationTime || (0, _integer.int)(0);
}
(0, _createClass3.default)(RoutingTable, [{
key: 'forget',
value: function forget(address) {
// Don't remove it from the set of routers, since that might mean we lose our ability to re-discover,
// just remove it from the set of readers and writers, so that we don't use it for actual work without
// performing discovery first.
this.readers = removeFromArray(this.readers, address);
this.writers = removeFromArray(this.writers, address);
}
}, {
key: 'forgetRouter',
value: function forgetRouter(address) {
this.routers = removeFromArray(this.routers, address);
}
}, {
key: 'forgetWriter',
value: function forgetWriter(address) {
this.writers = removeFromArray(this.writers, address);
}
}, {
key: 'serversDiff',
value: function serversDiff(otherRoutingTable) {
var oldServers = new _set2.default(this._allServers());
var newServers = otherRoutingTable._allServers();
newServers.forEach(function (newServer) {
return oldServers.delete(newServer);
});
return (0, _from2.default)(oldServers);
}
/**
* Check if this routing table is fresh to perform the required operation.
* @param {string} accessMode the type of operation. Allowed values are {@link READ} and {@link WRITE}.
* @return {boolean} <code>true</code> when this table contains servers to serve the required operation,
* <code>false</code> otherwise.
*/
}, {
key: 'isStaleFor',
value: function isStaleFor(accessMode) {
return this.expirationTime.lessThan(Date.now()) || this.routers.length < MIN_ROUTERS || accessMode === _driver.READ && this.readers.length === 0 || accessMode === _driver.WRITE && this.writers.length === 0;
}
}, {
key: '_allServers',
value: function _allServers() {
return [].concat((0, _toConsumableArray3.default)(this.routers), (0, _toConsumableArray3.default)(this.readers), (0, _toConsumableArray3.default)(this.writers));
}
}, {
key: 'toString',
value: function toString() {
return 'RoutingTable[' + ('expirationTime=' + this.expirationTime + ', ') + ('routers=[' + this.routers + '], ') + ('readers=[' + this.readers + '], ') + ('writers=[' + this.writers + ']]');
}
}]);
return RoutingTable;
}();
/**
* Remove all occurrences of the element in the array.
* @param {Array} array the array to filter.
* @param {object} element the element to remove.
* @return {Array} new filtered array.
*/
exports.default = RoutingTable;
function removeFromArray(array, element) {
return array.filter(function (item) {
return item !== element;
});
}

View File

@@ -0,0 +1,175 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _error = require('../error');
var _integer = require('../integer');
var _integer2 = _interopRequireDefault(_integer);
var _serverVersion = require('./server-version');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CALL_GET_SERVERS = 'CALL dbms.cluster.routing.getServers'; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var GET_ROUTING_TABLE_PARAM = 'context';
var CALL_GET_ROUTING_TABLE = 'CALL dbms.cluster.routing.getRoutingTable({' + GET_ROUTING_TABLE_PARAM + '})';
var PROCEDURE_NOT_FOUND_CODE = 'Neo.ClientError.Procedure.ProcedureNotFound';
var UNAUTHORIZED_CODE = 'Neo.ClientError.Security.Unauthorized';
var RoutingUtil = function () {
function RoutingUtil(routingContext) {
(0, _classCallCheck3.default)(this, RoutingUtil);
this._routingContext = routingContext;
}
/**
* Invoke routing procedure using the given session.
* @param {Session} session the session to use.
* @param {string} routerAddress the URL of the router.
* @return {Promise<Record[]>} promise resolved with records returned by the procedure call or null if
* connection error happened.
*/
(0, _createClass3.default)(RoutingUtil, [{
key: 'callRoutingProcedure',
value: function callRoutingProcedure(session, routerAddress) {
return this._callAvailableRoutingProcedure(session).then(function (result) {
session.close();
return result.records;
}).catch(function (error) {
if (error.code === PROCEDURE_NOT_FOUND_CODE) {
// throw when getServers procedure not found because this is clearly a configuration issue
throw (0, _error.newError)('Server at ' + routerAddress + ' can\'t perform routing. Make sure you are connecting to a causal cluster', _error.SERVICE_UNAVAILABLE);
} else if (error.code === UNAUTHORIZED_CODE) {
// auth error is a sign of a configuration issue, rediscovery should not proceed
throw error;
} else {
// return nothing when failed to connect because code higher in the callstack is still able to retry with a
// different session towards a different router
return null;
}
});
}
}, {
key: 'parseTtl',
value: function parseTtl(record, routerAddress) {
try {
var now = (0, _integer.int)(Date.now());
var expires = record.get('ttl').multiply(1000).add(now);
// if the server uses a really big expire time like Long.MAX_VALUE this may have overflowed
if (expires.lessThan(now)) {
return _integer2.default.MAX_VALUE;
}
return expires;
} catch (error) {
throw (0, _error.newError)('Unable to parse TTL entry from router ' + routerAddress + ' from record:\n' + (0, _stringify2.default)(record), _error.PROTOCOL_ERROR);
}
}
}, {
key: 'parseServers',
value: function parseServers(record, routerAddress) {
try {
var servers = record.get('servers');
var routers = [];
var readers = [];
var writers = [];
servers.forEach(function (server) {
var role = server['role'];
var addresses = server['addresses'];
if (role === 'ROUTE') {
routers = parseArray(addresses);
} else if (role === 'WRITE') {
writers = parseArray(addresses);
} else if (role === 'READ') {
readers = parseArray(addresses);
} else {
throw (0, _error.newError)('Unknown server role "' + role + '"', _error.PROTOCOL_ERROR);
}
});
return {
routers: routers,
readers: readers,
writers: writers
};
} catch (ignore) {
throw (0, _error.newError)('Unable to parse servers entry from router ' + routerAddress + ' from record:\n' + (0, _stringify2.default)(record), _error.PROTOCOL_ERROR);
}
}
}, {
key: '_callAvailableRoutingProcedure',
value: function _callAvailableRoutingProcedure(session) {
var _this = this;
return session._run(null, null, function (connection, streamObserver) {
var serverVersionString = connection.server.version;
var serverVersion = _serverVersion.ServerVersion.fromString(serverVersionString);
if (serverVersion.compareTo(_serverVersion.VERSION_3_2_0) >= 0) {
var params = (0, _defineProperty3.default)({}, GET_ROUTING_TABLE_PARAM, _this._routingContext);
connection.run(CALL_GET_ROUTING_TABLE, params, streamObserver);
} else {
connection.run(CALL_GET_SERVERS, {}, streamObserver);
}
});
}
}]);
return RoutingUtil;
}();
exports.default = RoutingUtil;
function parseArray(addresses) {
if (!Array.isArray(addresses)) {
throw new TypeError('Array expected but got: ' + addresses);
}
return (0, _from2.default)(addresses);
}

View File

@@ -0,0 +1,156 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.VERSION_IN_DEV = exports.VERSION_3_4_0 = exports.VERSION_3_2_0 = exports.VERSION_3_1_0 = exports.ServerVersion = undefined;
var _maxSafeInteger = require('babel-runtime/core-js/number/max-safe-integer');
var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _util = require('./util');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var SERVER_VERSION_REGEX = new RegExp('^(Neo4j/)?(\\d+)\\.(\\d+)(?:\\.)?(\\d*)(\\.|-|\\+)?([0-9A-Za-z-.]*)?$'); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var NEO4J_IN_DEV_VERSION_STRING = 'Neo4j/dev';
var ServerVersion = function () {
/**
* @constructor
* @param {number} major the major version number.
* @param {number} minor the minor version number.
* @param {number} patch the patch version number.
*/
function ServerVersion(major, minor, patch) {
(0, _classCallCheck3.default)(this, ServerVersion);
this.major = major;
this.minor = minor;
this.patch = patch;
}
/**
* Fetch server version using the given driver.
* @param {Driver} driver the driver to use.
* @return {Promise<ServerVersion>} promise resolved with a {@link ServerVersion} object or rejected with error.
*/
(0, _createClass3.default)(ServerVersion, [{
key: 'compareTo',
/**
* Compare this version to the given one.
* @param {ServerVersion} other the version to compare with.
* @return {number} value 0 if this version is the same as the given one, value less then 0 when this version
* was released earlier than the given one and value greater then 0 when this version was released after
* than the given one.
*/
value: function compareTo(other) {
var result = compareInts(this.major, other.major);
if (result === 0) {
result = compareInts(this.minor, other.minor);
if (result === 0) {
result = compareInts(this.patch, other.patch);
}
}
return result;
}
}], [{
key: 'fromDriver',
value: function fromDriver(driver) {
var session = driver.session();
return session.run('RETURN 1').then(function (result) {
session.close();
return ServerVersion.fromString(result.summary.server.version);
});
}
/**
* Parse given string to a {@link ServerVersion} object.
* @param {string} versionStr the string to parse.
* @return {ServerVersion} version for the given string.
* @throws Error if given string can't be parsed.
*/
}, {
key: 'fromString',
value: function fromString(versionStr) {
if (!versionStr) {
return new ServerVersion(3, 0, 0);
}
(0, _util.assertString)(versionStr, 'Neo4j version string');
if (versionStr.toLowerCase() === NEO4J_IN_DEV_VERSION_STRING.toLowerCase()) {
return VERSION_IN_DEV;
}
var version = versionStr.match(SERVER_VERSION_REGEX);
if (!version) {
throw new Error('Unparsable Neo4j version: ' + versionStr);
}
var major = parseIntStrict(version[2]);
var minor = parseIntStrict(version[3]);
var patch = parseIntStrict(version[4] || 0);
return new ServerVersion(major, minor, patch);
}
}]);
return ServerVersion;
}();
function parseIntStrict(str, name) {
var value = parseInt(str, 10);
if (!value && value !== 0) {
throw new Error('Unparsable number ' + name + ': \'' + str + '\'');
}
return value;
}
function compareInts(x, y) {
return x < y ? -1 : x === y ? 0 : 1;
}
var VERSION_3_1_0 = new ServerVersion(3, 1, 0);
var VERSION_3_2_0 = new ServerVersion(3, 2, 0);
var VERSION_3_4_0 = new ServerVersion(3, 4, 0);
var maxVer = _maxSafeInteger2.default;
var VERSION_IN_DEV = new ServerVersion(maxVer, maxVer, maxVer);
exports.ServerVersion = ServerVersion;
exports.VERSION_3_1_0 = VERSION_3_1_0;
exports.VERSION_3_2_0 = VERSION_3_2_0;
exports.VERSION_3_4_0 = VERSION_3_4_0;
exports.VERSION_IN_DEV = VERSION_IN_DEV;

View File

@@ -0,0 +1,201 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _record = require('../record');
var _record2 = _interopRequireDefault(_record);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Handles a RUN/PULL_ALL, or RUN/DISCARD_ALL requests, maps the responses
* in a way that a user-provided observer can see these as a clean Stream
* of records.
* This class will queue up incoming messages until a user-provided observer
* for the incoming stream is registered. Thus, we keep fields around
* for tracking head/records/tail. These are only used if there is no
* observer registered.
* @access private
*/
var StreamObserver = function () {
/**
* @constructor
* @param errorTransformer optional callback to be used for adding additional logic on error
*/
function StreamObserver() {
var errorTransformer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (err) {
return err;
};
(0, _classCallCheck3.default)(this, StreamObserver);
this._fieldKeys = null;
this._fieldLookup = null;
this._queuedRecords = [];
this._tail = null;
this._error = null;
this._hasFailed = false;
this._errorTransformer = errorTransformer;
this._observer = null;
this._conn = null;
this._meta = {};
}
/**
* Will be called on every record that comes in and transform a raw record
* to a Object. If user-provided observer is present, pass transformed record
* to it's onNext method, otherwise, push to record que.
* @param {Array} rawRecord - An array with the raw record
*/
(0, _createClass3.default)(StreamObserver, [{
key: 'onNext',
value: function onNext(rawRecord) {
var record = new _record2.default(this._fieldKeys, rawRecord, this._fieldLookup);
if (this._observer) {
this._observer.onNext(record);
} else {
this._queuedRecords.push(record);
}
}
}, {
key: 'onCompleted',
value: function onCompleted(meta) {
if (this._fieldKeys === null) {
// Stream header, build a name->index field lookup table
// to be used by records. This is an optimization to make it
// faster to look up fields in a record by name, rather than by index.
// Since the records we get back via Bolt are just arrays of values.
this._fieldKeys = [];
this._fieldLookup = {};
if (meta.fields && meta.fields.length > 0) {
this._fieldKeys = meta.fields;
for (var i = 0; i < meta.fields.length; i++) {
this._fieldLookup[meta.fields[i]] = i;
}
}
} else {
// End of stream
if (this._observer) {
this._observer.onCompleted(meta);
} else {
this._tail = meta;
}
}
this._copyMetadataOnCompletion(meta);
}
}, {
key: '_copyMetadataOnCompletion',
value: function _copyMetadataOnCompletion(meta) {
for (var key in meta) {
if (meta.hasOwnProperty(key)) {
this._meta[key] = meta[key];
}
}
}
}, {
key: 'serverMetadata',
value: function serverMetadata() {
var serverMeta = { server: this._conn.server };
return (0, _assign2.default)({}, this._meta, serverMeta);
}
}, {
key: 'resolveConnection',
value: function resolveConnection(conn) {
this._conn = conn;
}
/**
* Will be called on errors.
* If user-provided observer is present, pass the error
* to it's onError method, otherwise set instance variable _error.
* @param {Object} error - An error object
*/
}, {
key: 'onError',
value: function onError(error) {
var transformedError = this._errorTransformer(error, this._conn);
if (this._hasFailed) {
return;
}
this._hasFailed = true;
if (this._observer) {
if (this._observer.onError) {
this._observer.onError(transformedError);
} else {
console.log(transformedError);
}
} else {
this._error = transformedError;
}
}
/**
* Subscribe to events with provided observer.
* @param {Object} observer - Observer object
* @param {function(record: Object)} observer.onNext - Handle records, one by one.
* @param {function(metadata: Object)} observer.onComplete - Handle stream tail, the metadata.
* @param {function(error: Object)} observer.onError - Handle errors.
*/
}, {
key: 'subscribe',
value: function subscribe(observer) {
if (this._error) {
observer.onError(this._error);
return;
}
if (this._queuedRecords.length > 0) {
for (var i = 0; i < this._queuedRecords.length; i++) {
observer.onNext(this._queuedRecords[i]);
}
}
if (this._tail) {
observer.onCompleted(this._tail);
}
this._observer = observer;
}
}, {
key: 'hasFailed',
value: function hasFailed() {
return this._hasFailed;
}
}]);
return StreamObserver;
}(); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.default = StreamObserver;

View File

@@ -0,0 +1,576 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.normalizeSecondsForDuration = normalizeSecondsForDuration;
exports.normalizeNanosecondsForDuration = normalizeNanosecondsForDuration;
exports.localTimeToNanoOfDay = localTimeToNanoOfDay;
exports.nanoOfDayToLocalTime = nanoOfDayToLocalTime;
exports.localDateTimeToEpochSecond = localDateTimeToEpochSecond;
exports.epochSecondAndNanoToLocalDateTime = epochSecondAndNanoToLocalDateTime;
exports.dateToEpochDay = dateToEpochDay;
exports.epochDayToDate = epochDayToDate;
exports.durationToIsoString = durationToIsoString;
exports.timeToIsoString = timeToIsoString;
exports.timeZoneOffsetToIsoString = timeZoneOffsetToIsoString;
exports.dateToIsoString = dateToIsoString;
exports.totalNanoseconds = totalNanoseconds;
exports.timeZoneOffsetInSeconds = timeZoneOffsetInSeconds;
exports.assertValidYear = assertValidYear;
exports.assertValidMonth = assertValidMonth;
exports.assertValidDay = assertValidDay;
exports.assertValidHour = assertValidHour;
exports.assertValidMinute = assertValidMinute;
exports.assertValidSecond = assertValidSecond;
exports.assertValidNanosecond = assertValidNanosecond;
var _integer = require('../integer');
var _temporalTypes = require('../temporal-types');
var _util = require('./util');
var _error = require('../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
Code in this util should be compatible with code in the database that uses JSR-310 java.time APIs.
It is based on a library called ThreeTen (https://github.com/ThreeTen/threetenbp) which was derived
from JSR-310 reference implementation previously hosted on GitHub. Code uses `Integer` type everywhere
to correctly handle large integer values that are greater than <code>Number.MAX_SAFE_INTEGER</code>.
Please consult either ThreeTen or js-joda (https://github.com/js-joda/js-joda) when working with the
conversion functions.
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ValueRange = function () {
function ValueRange(min, max) {
(0, _classCallCheck3.default)(this, ValueRange);
this._minNumber = min;
this._maxNumber = max;
this._minInteger = (0, _integer.int)(min);
this._maxInteger = (0, _integer.int)(max);
}
(0, _createClass3.default)(ValueRange, [{
key: 'contains',
value: function contains(value) {
if ((0, _integer.isInt)(value)) {
return value.greaterThanOrEqual(this._minInteger) && value.lessThanOrEqual(this._maxInteger);
} else {
return value >= this._minNumber && value <= this._maxNumber;
}
}
}, {
key: 'toString',
value: function toString() {
return '[' + this._minNumber + ', ' + this._maxNumber + ']';
}
}]);
return ValueRange;
}();
var YEAR_RANGE = new ValueRange(-999999999, 999999999);
var MONTH_OF_YEAR_RANGE = new ValueRange(1, 12);
var DAY_OF_MONTH_RANGE = new ValueRange(1, 31);
var HOUR_OF_DAY_RANGE = new ValueRange(0, 23);
var MINUTE_OF_HOUR_RANGE = new ValueRange(0, 59);
var SECOND_OF_MINUTE_RANGE = new ValueRange(0, 59);
var NANOSECOND_OF_SECOND_RANGE = new ValueRange(0, 999999999);
var MINUTES_PER_HOUR = 60;
var SECONDS_PER_MINUTE = 60;
var SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
var NANOS_PER_SECOND = 1000000000;
var NANOS_PER_MILLISECOND = 1000000;
var NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE;
var NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR;
var DAYS_0000_TO_1970 = 719528;
var DAYS_PER_400_YEAR_CYCLE = 146097;
var SECONDS_PER_DAY = 86400;
function normalizeSecondsForDuration(seconds, nanoseconds) {
return (0, _integer.int)(seconds).add(floorDiv(nanoseconds, NANOS_PER_SECOND));
}
function normalizeNanosecondsForDuration(nanoseconds) {
return floorMod(nanoseconds, NANOS_PER_SECOND);
}
/**
* Converts given local time into a single integer representing this same time in nanoseconds of the day.
* @param {Integer|number|string} hour the hour of the local time to convert.
* @param {Integer|number|string} minute the minute of the local time to convert.
* @param {Integer|number|string} second the second of the local time to convert.
* @param {Integer|number|string} nanosecond the nanosecond of the local time to convert.
* @return {Integer} nanoseconds representing the given local time.
*/
function localTimeToNanoOfDay(hour, minute, second, nanosecond) {
hour = (0, _integer.int)(hour);
minute = (0, _integer.int)(minute);
second = (0, _integer.int)(second);
nanosecond = (0, _integer.int)(nanosecond);
var totalNanos = hour.multiply(NANOS_PER_HOUR);
totalNanos = totalNanos.add(minute.multiply(NANOS_PER_MINUTE));
totalNanos = totalNanos.add(second.multiply(NANOS_PER_SECOND));
return totalNanos.add(nanosecond);
}
/**
* Converts nanoseconds of the day into local time.
* @param {Integer|number|string} nanoOfDay the nanoseconds of the day to convert.
* @return {LocalTime} the local time representing given nanoseconds of the day.
*/
function nanoOfDayToLocalTime(nanoOfDay) {
nanoOfDay = (0, _integer.int)(nanoOfDay);
var hour = nanoOfDay.div(NANOS_PER_HOUR);
nanoOfDay = nanoOfDay.subtract(hour.multiply(NANOS_PER_HOUR));
var minute = nanoOfDay.div(NANOS_PER_MINUTE);
nanoOfDay = nanoOfDay.subtract(minute.multiply(NANOS_PER_MINUTE));
var second = nanoOfDay.div(NANOS_PER_SECOND);
var nanosecond = nanoOfDay.subtract(second.multiply(NANOS_PER_SECOND));
return new _temporalTypes.LocalTime(hour, minute, second, nanosecond);
}
/**
* Converts given local date time into a single integer representing this same time in epoch seconds UTC.
* @param {Integer|number|string} year the year of the local date-time to convert.
* @param {Integer|number|string} month the month of the local date-time to convert.
* @param {Integer|number|string} day the day of the local date-time to convert.
* @param {Integer|number|string} hour the hour of the local date-time to convert.
* @param {Integer|number|string} minute the minute of the local date-time to convert.
* @param {Integer|number|string} second the second of the local date-time to convert.
* @param {Integer|number|string} nanosecond the nanosecond of the local date-time to convert.
* @return {Integer} epoch second in UTC representing the given local date time.
*/
function localDateTimeToEpochSecond(year, month, day, hour, minute, second, nanosecond) {
var epochDay = dateToEpochDay(year, month, day);
var localTimeSeconds = localTimeToSecondOfDay(hour, minute, second);
return epochDay.multiply(SECONDS_PER_DAY).add(localTimeSeconds);
}
/**
* Converts given epoch second and nanosecond adjustment into a local date time object.
* @param {Integer|number|string} epochSecond the epoch second to use.
* @param {Integer|number|string} nano the nanosecond to use.
* @return {LocalDateTime} the local date time representing given epoch second and nano.
*/
function epochSecondAndNanoToLocalDateTime(epochSecond, nano) {
var epochDay = floorDiv(epochSecond, SECONDS_PER_DAY);
var secondsOfDay = floorMod(epochSecond, SECONDS_PER_DAY);
var nanoOfDay = secondsOfDay.multiply(NANOS_PER_SECOND).add(nano);
var localDate = epochDayToDate(epochDay);
var localTime = nanoOfDayToLocalTime(nanoOfDay);
return new _temporalTypes.LocalDateTime(localDate.year, localDate.month, localDate.day, localTime.hour, localTime.minute, localTime.second, localTime.nanosecond);
}
/**
* Converts given local date into a single integer representing it's epoch day.
* @param {Integer|number|string} year the year of the local date to convert.
* @param {Integer|number|string} month the month of the local date to convert.
* @param {Integer|number|string} day the day of the local date to convert.
* @return {Integer} epoch day representing the given date.
*/
function dateToEpochDay(year, month, day) {
year = (0, _integer.int)(year);
month = (0, _integer.int)(month);
day = (0, _integer.int)(day);
var epochDay = year.multiply(365);
if (year.greaterThanOrEqual(0)) {
epochDay = epochDay.add(year.add(3).div(4).subtract(year.add(99).div(100)).add(year.add(399).div(400)));
} else {
epochDay = epochDay.subtract(year.div(-4).subtract(year.div(-100)).add(year.div(-400)));
}
epochDay = epochDay.add(month.multiply(367).subtract(362).div(12));
epochDay = epochDay.add(day.subtract(1));
if (month.greaterThan(2)) {
epochDay = epochDay.subtract(1);
if (!isLeapYear(year)) {
epochDay = epochDay.subtract(1);
}
}
return epochDay.subtract(DAYS_0000_TO_1970);
}
/**
* Converts given epoch day to a local date.
* @param {Integer|number|string} epochDay the epoch day to convert.
* @return {Date} the date representing the epoch day in years, months and days.
*/
function epochDayToDate(epochDay) {
epochDay = (0, _integer.int)(epochDay);
var zeroDay = epochDay.add(DAYS_0000_TO_1970).subtract(60);
var adjust = (0, _integer.int)(0);
if (zeroDay.lessThan(0)) {
var adjustCycles = zeroDay.add(1).div(DAYS_PER_400_YEAR_CYCLE).subtract(1);
adjust = adjustCycles.multiply(400);
zeroDay = zeroDay.add(adjustCycles.multiply(-DAYS_PER_400_YEAR_CYCLE));
}
var year = zeroDay.multiply(400).add(591).div(DAYS_PER_400_YEAR_CYCLE);
var dayOfYearEst = zeroDay.subtract(year.multiply(365).add(year.div(4)).subtract(year.div(100)).add(year.div(400)));
if (dayOfYearEst.lessThan(0)) {
year = year.subtract(1);
dayOfYearEst = zeroDay.subtract(year.multiply(365).add(year.div(4)).subtract(year.div(100)).add(year.div(400)));
}
year = year.add(adjust);
var marchDayOfYear = dayOfYearEst;
var marchMonth = marchDayOfYear.multiply(5).add(2).div(153);
var month = marchMonth.add(2).modulo(12).add(1);
var day = marchDayOfYear.subtract(marchMonth.multiply(306).add(5).div(10)).add(1);
year = year.add(marchMonth.div(10));
return new _temporalTypes.Date(year, month, day);
}
/**
* Format given duration to an ISO 8601 string.
* @param {Integer|number|string} months the number of months.
* @param {Integer|number|string} days the number of days.
* @param {Integer|number|string} seconds the number of seconds.
* @param {Integer|number|string} nanoseconds the number of nanoseconds.
* @return {string} ISO string that represents given duration.
*/
function durationToIsoString(months, days, seconds, nanoseconds) {
var monthsString = formatNumber(months);
var daysString = formatNumber(days);
var secondsAndNanosecondsString = formatSecondsAndNanosecondsForDuration(seconds, nanoseconds);
return 'P' + monthsString + 'M' + daysString + 'DT' + secondsAndNanosecondsString + 'S';
}
/**
* Formats given time to an ISO 8601 string.
* @param {Integer|number|string} hour the hour value.
* @param {Integer|number|string} minute the minute value.
* @param {Integer|number|string} second the second value.
* @param {Integer|number|string} nanosecond the nanosecond value.
* @return {string} ISO string that represents given time.
*/
function timeToIsoString(hour, minute, second, nanosecond) {
var hourString = formatNumber(hour, 2);
var minuteString = formatNumber(minute, 2);
var secondString = formatNumber(second, 2);
var nanosecondString = formatNanosecond(nanosecond);
return hourString + ':' + minuteString + ':' + secondString + nanosecondString;
}
/**
* Formats given time zone offset in seconds to string representation like '±HH:MM', '±HH:MM:SS' or 'Z' for UTC.
* @param {Integer|number|string} offsetSeconds the offset in seconds.
* @return {string} ISO string that represents given offset.
*/
function timeZoneOffsetToIsoString(offsetSeconds) {
offsetSeconds = (0, _integer.int)(offsetSeconds);
if (offsetSeconds.equals(0)) {
return 'Z';
}
var isNegative = offsetSeconds.isNegative();
if (isNegative) {
offsetSeconds = offsetSeconds.multiply(-1);
}
var signPrefix = isNegative ? '-' : '+';
var hours = formatNumber(offsetSeconds.div(SECONDS_PER_HOUR), 2);
var minutes = formatNumber(offsetSeconds.div(SECONDS_PER_MINUTE).modulo(MINUTES_PER_HOUR), 2);
var secondsValue = offsetSeconds.modulo(SECONDS_PER_MINUTE);
var seconds = secondsValue.equals(0) ? null : formatNumber(secondsValue, 2);
return seconds ? '' + signPrefix + hours + ':' + minutes + ':' + seconds : '' + signPrefix + hours + ':' + minutes;
}
/**
* Formats given date to an ISO 8601 string.
* @param {Integer|number|string} year the date year.
* @param {Integer|number|string} month the date month.
* @param {Integer|number|string} day the date day.
* @return {string} ISO string that represents given date.
*/
function dateToIsoString(year, month, day) {
year = (0, _integer.int)(year);
var isNegative = year.isNegative();
if (isNegative) {
year = year.multiply(-1);
}
var yearString = formatNumber(year, 4);
if (isNegative) {
yearString = '-' + yearString;
}
var monthString = formatNumber(month, 2);
var dayString = formatNumber(day, 2);
return yearString + '-' + monthString + '-' + dayString;
}
/**
* Get the total number of nanoseconds from the milliseconds of the given standard JavaScript date and optional nanosecond part.
* @param {global.Date} standardDate the standard JavaScript date.
* @param {Integer|number|undefined} nanoseconds the optional number of nanoseconds.
* @return {Integer|number} the total amount of nanoseconds.
*/
function totalNanoseconds(standardDate, nanoseconds) {
nanoseconds = nanoseconds || 0;
var nanosFromMillis = standardDate.getMilliseconds() * NANOS_PER_MILLISECOND;
return (0, _integer.isInt)(nanoseconds) ? nanoseconds.add(nanosFromMillis) : nanoseconds + nanosFromMillis;
}
/**
* Get the time zone offset in seconds from the given standard JavaScript date.
* @param {global.Date} standardDate the standard JavaScript date.
* @return {number} the time zone offset in seconds.
*/
function timeZoneOffsetInSeconds(standardDate) {
return standardDate.getTimezoneOffset() * SECONDS_PER_MINUTE;
}
/**
* Assert that the year value is valid.
* @param {Integer|number} year the value to check.
* @return {Integer|number} the value of the year if it is valid. Exception is thrown otherwise.
*/
function assertValidYear(year) {
return assertValidTemporalValue(year, YEAR_RANGE, 'Year');
}
/**
* Assert that the month value is valid.
* @param {Integer|number} month the value to check.
* @return {Integer|number} the value of the month if it is valid. Exception is thrown otherwise.
*/
function assertValidMonth(month) {
return assertValidTemporalValue(month, MONTH_OF_YEAR_RANGE, 'Month');
}
/**
* Assert that the day value is valid.
* @param {Integer|number} day the value to check.
* @return {Integer|number} the value of the day if it is valid. Exception is thrown otherwise.
*/
function assertValidDay(day) {
return assertValidTemporalValue(day, DAY_OF_MONTH_RANGE, 'Day');
}
/**
* Assert that the hour value is valid.
* @param {Integer|number} hour the value to check.
* @return {Integer|number} the value of the hour if it is valid. Exception is thrown otherwise.
*/
function assertValidHour(hour) {
return assertValidTemporalValue(hour, HOUR_OF_DAY_RANGE, 'Hour');
}
/**
* Assert that the minute value is valid.
* @param {Integer|number} minute the value to check.
* @return {Integer|number} the value of the minute if it is valid. Exception is thrown otherwise.
*/
function assertValidMinute(minute) {
return assertValidTemporalValue(minute, MINUTE_OF_HOUR_RANGE, 'Minute');
}
/**
* Assert that the second value is valid.
* @param {Integer|number} second the value to check.
* @return {Integer|number} the value of the second if it is valid. Exception is thrown otherwise.
*/
function assertValidSecond(second) {
return assertValidTemporalValue(second, SECOND_OF_MINUTE_RANGE, 'Second');
}
/**
* Assert that the nanosecond value is valid.
* @param {Integer|number} nanosecond the value to check.
* @return {Integer|number} the value of the nanosecond if it is valid. Exception is thrown otherwise.
*/
function assertValidNanosecond(nanosecond) {
return assertValidTemporalValue(nanosecond, NANOSECOND_OF_SECOND_RANGE, 'Nanosecond');
}
/**
* Check if the given value is of expected type and is in the expected range.
* @param {Integer|number} value the value to check.
* @param {ValueRange} range the range.
* @param {string} name the name of the value.
* @return {Integer|number} the value if valid. Exception is thrown otherwise.
*/
function assertValidTemporalValue(value, range, name) {
(0, _util.assertNumberOrInteger)(value, name);
if (!range.contains(value)) {
throw (0, _error.newError)(name + ' is expected to be in range ' + range + ' but was: ' + value);
}
return value;
}
/**
* Converts given local time into a single integer representing this same time in seconds of the day. Nanoseconds are skipped.
* @param {Integer|number|string} hour the hour of the local time.
* @param {Integer|number|string} minute the minute of the local time.
* @param {Integer|number|string} second the second of the local time.
* @return {Integer} seconds representing the given local time.
*/
function localTimeToSecondOfDay(hour, minute, second) {
hour = (0, _integer.int)(hour);
minute = (0, _integer.int)(minute);
second = (0, _integer.int)(second);
var totalSeconds = hour.multiply(SECONDS_PER_HOUR);
totalSeconds = totalSeconds.add(minute.multiply(SECONDS_PER_MINUTE));
return totalSeconds.add(second);
}
/**
* Check if given year is a leap year. Uses algorithm described here {@link https://en.wikipedia.org/wiki/Leap_year#Algorithm}.
* @param {Integer|number|string} year the year to check. Will be converted to {@link Integer} for all calculations.
* @return {boolean} <code>true</code> if given year is a leap year, <code>false</code> otherwise.
*/
function isLeapYear(year) {
year = (0, _integer.int)(year);
if (!year.modulo(4).equals(0)) {
return false;
} else if (!year.modulo(100).equals(0)) {
return true;
} else if (!year.modulo(400).equals(0)) {
return false;
} else {
return true;
}
}
/**
* @param {Integer|number|string} x the divident.
* @param {Integer|number|string} y the divisor.
* @return {Integer} the result.
*/
function floorDiv(x, y) {
x = (0, _integer.int)(x);
y = (0, _integer.int)(y);
var result = x.div(y);
if (x.isPositive() !== y.isPositive() && result.multiply(y).notEquals(x)) {
result = result.subtract(1);
}
return result;
}
/**
* @param {Integer|number|string} x the divident.
* @param {Integer|number|string} y the divisor.
* @return {Integer} the result.
*/
function floorMod(x, y) {
x = (0, _integer.int)(x);
y = (0, _integer.int)(y);
return x.subtract(floorDiv(x, y).multiply(y));
}
/**
* @param {Integer|number|string} seconds the number of seconds to format.
* @param {Integer|number|string} nanoseconds the number of nanoseconds to format.
* @return {string} formatted value.
*/
function formatSecondsAndNanosecondsForDuration(seconds, nanoseconds) {
seconds = (0, _integer.int)(seconds);
nanoseconds = (0, _integer.int)(nanoseconds);
var secondsString = void 0;
var nanosecondsString = void 0;
var secondsNegative = seconds.isNegative();
var nanosecondsGreaterThanZero = nanoseconds.greaterThan(0);
if (secondsNegative && nanosecondsGreaterThanZero) {
if (seconds.equals(-1)) {
secondsString = '-0';
} else {
secondsString = seconds.add(1).toString();
}
} else {
secondsString = seconds.toString();
}
if (nanosecondsGreaterThanZero) {
if (secondsNegative) {
nanosecondsString = formatNanosecond(nanoseconds.negate().add(2 * NANOS_PER_SECOND).modulo(NANOS_PER_SECOND));
} else {
nanosecondsString = formatNanosecond(nanoseconds.add(NANOS_PER_SECOND).modulo(NANOS_PER_SECOND));
}
}
return nanosecondsString ? secondsString + nanosecondsString : secondsString;
}
/**
* @param {Integer|number|string} value the number of nanoseconds to format.
* @return {string} formatted and possibly left-padded nanoseconds part as string.
*/
function formatNanosecond(value) {
value = (0, _integer.int)(value);
return value.equals(0) ? '' : '.' + formatNumber(value, 9);
}
/**
* @param {Integer|number|string} num the number to format.
* @param {number} [stringLength=undefined] the string length to left-pad to.
* @return {string} formatted and possibly left-padded number as string.
*/
function formatNumber(num) {
var stringLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
num = (0, _integer.int)(num);
var isNegative = num.isNegative();
if (isNegative) {
num = num.negate();
}
var numString = num.toString();
if (stringLength) {
// left pad the string with zeroes
while (numString.length < stringLength) {
numString = '0' + numString;
}
}
return isNegative ? '-' + numString : numString;
}

View File

@@ -0,0 +1,237 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _error = require('../error');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000; // 30 seconds
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_INITIAL_RETRY_DELAY_MS = 1000; // 1 seconds
var DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0;
var DEFAULT_RETRY_DELAY_JITTER_FACTOR = 0.2;
var TransactionExecutor = function () {
function TransactionExecutor(maxRetryTimeMs, initialRetryDelayMs, multiplier, jitterFactor) {
(0, _classCallCheck3.default)(this, TransactionExecutor);
this._maxRetryTimeMs = _valueOrDefault(maxRetryTimeMs, DEFAULT_MAX_RETRY_TIME_MS);
this._initialRetryDelayMs = _valueOrDefault(initialRetryDelayMs, DEFAULT_INITIAL_RETRY_DELAY_MS);
this._multiplier = _valueOrDefault(multiplier, DEFAULT_RETRY_DELAY_MULTIPLIER);
this._jitterFactor = _valueOrDefault(jitterFactor, DEFAULT_RETRY_DELAY_JITTER_FACTOR);
this._inFlightTimeoutIds = [];
this._verifyAfterConstruction();
}
(0, _createClass3.default)(TransactionExecutor, [{
key: 'execute',
value: function execute(transactionCreator, transactionWork) {
var _this = this;
return new _promise2.default(function (resolve, reject) {
_this._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject);
}).catch(function (error) {
var retryStartTimeMs = Date.now();
var retryDelayMs = _this._initialRetryDelayMs;
return _this._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTimeMs, retryDelayMs);
});
}
}, {
key: 'close',
value: function close() {
// cancel all existing timeouts to prevent further retries
this._inFlightTimeoutIds.forEach(function (timeoutId) {
return clearTimeout(timeoutId);
});
this._inFlightTimeoutIds = [];
}
}, {
key: '_retryTransactionPromise',
value: function _retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, retryDelayMs) {
var _this2 = this;
var elapsedTimeMs = Date.now() - retryStartTime;
if (elapsedTimeMs > this._maxRetryTimeMs || !TransactionExecutor._canRetryOn(error)) {
return _promise2.default.reject(error);
}
return new _promise2.default(function (resolve, reject) {
var nextRetryTime = _this2._computeDelayWithJitter(retryDelayMs);
var timeoutId = setTimeout(function () {
// filter out this timeoutId when time has come and function is being executed
_this2._inFlightTimeoutIds = _this2._inFlightTimeoutIds.filter(function (id) {
return id !== timeoutId;
});
_this2._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject);
}, nextRetryTime);
// add newly created timeoutId to the list of all in-flight timeouts
_this2._inFlightTimeoutIds.push(timeoutId);
}).catch(function (error) {
var nextRetryDelayMs = retryDelayMs * _this2._multiplier;
return _this2._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, nextRetryDelayMs);
});
}
}, {
key: '_executeTransactionInsidePromise',
value: function _executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject) {
var _this3 = this;
var tx = void 0;
try {
tx = transactionCreator();
} catch (error) {
// failed to create a transaction
reject(error);
return;
}
var resultPromise = this._safeExecuteTransactionWork(tx, transactionWork);
resultPromise.then(function (result) {
return _this3._handleTransactionWorkSuccess(result, tx, resolve, reject);
}).catch(function (error) {
return _this3._handleTransactionWorkFailure(error, tx, reject);
});
}
}, {
key: '_safeExecuteTransactionWork',
value: function _safeExecuteTransactionWork(tx, transactionWork) {
try {
var result = transactionWork(tx);
// user defined callback is supposed to return a promise, but it might not; so to protect against an
// incorrect API usage we wrap the returned value with a resolved promise; this is effectively a
// validation step without type checks
return _promise2.default.resolve(result);
} catch (error) {
return _promise2.default.reject(error);
}
}
}, {
key: '_handleTransactionWorkSuccess',
value: function _handleTransactionWorkSuccess(result, tx, resolve, reject) {
if (tx.isOpen()) {
// transaction work returned resolved promise and transaction has not been committed/rolled back
// try to commit the transaction
tx.commit().then(function () {
// transaction was committed, return result to the user
resolve(result);
}).catch(function (error) {
// transaction failed to commit, propagate the failure
reject(error);
});
} else {
// transaction work returned resolved promise and transaction is already committed/rolled back
// return the result returned by given transaction work
resolve(result);
}
}
}, {
key: '_handleTransactionWorkFailure',
value: function _handleTransactionWorkFailure(error, tx, reject) {
if (tx.isOpen()) {
// transaction work failed and the transaction is still open, roll it back and propagate the failure
tx.rollback().catch(function (ignore) {
// ignore the rollback error
}).then(function () {
return reject(error);
}); // propagate the original error we got from the transaction work
} else {
// transaction is already rolled back, propagate the error
reject(error);
}
}
}, {
key: '_computeDelayWithJitter',
value: function _computeDelayWithJitter(delayMs) {
var jitter = delayMs * this._jitterFactor;
var min = delayMs - jitter;
var max = delayMs + jitter;
return Math.random() * (max - min) + min;
}
}, {
key: '_verifyAfterConstruction',
value: function _verifyAfterConstruction() {
if (this._maxRetryTimeMs < 0) {
throw (0, _error.newError)('Max retry time should be >= 0: ' + this._maxRetryTimeMs);
}
if (this._initialRetryDelayMs < 0) {
throw (0, _error.newError)('Initial retry delay should >= 0: ' + this._initialRetryDelayMs);
}
if (this._multiplier < 1.0) {
throw (0, _error.newError)('Multiplier should be >= 1.0: ' + this._multiplier);
}
if (this._jitterFactor < 0 || this._jitterFactor > 1) {
throw (0, _error.newError)('Jitter factor should be in [0.0, 1.0]: ' + this._jitterFactor);
}
}
}], [{
key: '_canRetryOn',
value: function _canRetryOn(error) {
return error && error.code && (error.code === _error.SERVICE_UNAVAILABLE || error.code === _error.SESSION_EXPIRED || this._isTransientError(error));
}
}, {
key: '_isTransientError',
value: function _isTransientError(error) {
// Retries should not happen when transaction was explicitly terminated by the user.
// Termination of transaction might result in two different error codes depending on where it was
// terminated. These are really client errors but classification on the server is not entirely correct and
// they are classified as transient.
var code = error.code;
if (code.indexOf('TransientError') >= 0) {
if (code === 'Neo.TransientError.Transaction.Terminated' || code === 'Neo.TransientError.Transaction.LockClientStopped') {
return false;
}
return true;
}
return false;
}
}]);
return TransactionExecutor;
}();
exports.default = TransactionExecutor;
;
function _valueOrDefault(value, defaultValue) {
if (value || value === 0) {
return value;
}
return defaultValue;
}

216
node_modules/neo4j-driver/lib/v1/internal/url-util.js generated vendored Normal file
View File

@@ -0,0 +1,216 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _uriJs = require('uri-js');
var _util = require('./util');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_BOLT_PORT = 7687;
var DEFAULT_HTTP_PORT = 7474;
var DEFAULT_HTTPS_PORT = 7473;
var Url = function Url(scheme, host, port, hostAndPort, query) {
(0, _classCallCheck3.default)(this, Url);
/**
* Nullable scheme (protocol) of the URL.
* Example: 'bolt', 'bolt+routing', 'http', 'https', etc.
* @type {string}
*/
this.scheme = scheme;
/**
* Nonnull host name or IP address. IPv6 not wrapped in square brackets.
* Example: 'neo4j.com', 'localhost', '127.0.0.1', '192.168.10.15', '::1', '2001:4860:4860::8844', etc.
* @type {string}
*/
this.host = host;
/**
* Nonnull number representing port. Default port for the given scheme is used if given URL string
* does not contain port. Example: 7687 for bolt, 7474 for HTTP and 7473 for HTTPS.
* @type {number}
*/
this.port = port;
/**
* Nonnull host name or IP address plus port, separated by ':'. IPv6 wrapped in square brackets.
* Example: 'neo4j.com', 'neo4j.com:7687', '127.0.0.1', '127.0.0.1:8080', '[2001:4860:4860::8844]',
* '[2001:4860:4860::8844]:9090', etc.
* @type {string}
*/
this.hostAndPort = hostAndPort;
/**
* Nonnull object representing parsed query string key-value pairs. Duplicated keys not supported.
* Example: '{}', '{'key1': 'value1', 'key2': 'value2'}', etc.
* @type {object}
*/
this.query = query;
};
function parseDatabaseUrl(url) {
(0, _util.assertString)(url, 'URL');
var sanitized = sanitizeUrl(url);
var parsedUrl = (0, _uriJs.parse)(sanitized.url);
var scheme = sanitized.schemeMissing ? null : extractScheme(parsedUrl.scheme);
var host = extractHost(parsedUrl.host); // no square brackets for IPv6
var formattedHost = formatHost(host); // has square brackets for IPv6
var port = extractPort(parsedUrl.port, scheme);
var hostAndPort = formattedHost + ':' + port;
var query = extractQuery(parsedUrl.query, url);
return new Url(scheme, host, port, hostAndPort, query);
}
function sanitizeUrl(url) {
url = url.trim();
if (url.indexOf('://') === -1) {
// url does not contain scheme, add dummy 'none://' to make parser work correctly
return { schemeMissing: true, url: 'none://' + url };
}
return { schemeMissing: false, url: url };
}
function extractScheme(scheme) {
if (scheme) {
scheme = scheme.trim();
if (scheme.charAt(scheme.length - 1) === ':') {
scheme = scheme.substring(0, scheme.length - 1);
}
return scheme;
}
return null;
}
function extractHost(host, url) {
if (!host) {
throw new Error('Unable to extract host from ' + url);
}
return host.trim();
}
function extractPort(portString, scheme) {
var port = parseInt(portString, 10);
return port === 0 || port ? port : defaultPortForScheme(scheme);
}
function extractQuery(queryString, url) {
var query = trimAndSanitizeQuery(queryString);
var context = {};
if (query) {
query.split('&').forEach(function (pair) {
var keyValue = pair.split('=');
if (keyValue.length !== 2) {
throw new Error('Invalid parameters: \'' + keyValue + '\' in URL \'' + url + '\'.');
}
var key = trimAndVerifyQueryElement(keyValue[0], 'key', url);
var value = trimAndVerifyQueryElement(keyValue[1], 'value', url);
if (context[key]) {
throw new Error('Duplicated query parameters with key \'' + key + '\' in URL \'' + url + '\'');
}
context[key] = value;
});
}
return context;
}
function trimAndSanitizeQuery(query) {
query = (query || '').trim();
if (query && query.charAt(0) === '?') {
query = query.substring(1, query.length);
}
return query;
}
function trimAndVerifyQueryElement(element, name, url) {
element = (element || '').trim();
if (!element) {
throw new Error('Illegal empty ' + name + ' in URL query \'' + url + '\'');
}
return element;
}
function escapeIPv6Address(address) {
var startsWithSquareBracket = address.charAt(0) === '[';
var endsWithSquareBracket = address.charAt(address.length - 1) === ']';
if (!startsWithSquareBracket && !endsWithSquareBracket) {
return '[' + address + ']';
} else if (startsWithSquareBracket && endsWithSquareBracket) {
return address;
} else {
throw new Error('Illegal IPv6 address ' + address);
}
}
function formatHost(host) {
if (!host) {
throw new Error('Illegal host ' + host);
}
var isIPv6Address = host.indexOf(':') >= 0;
return isIPv6Address ? escapeIPv6Address(host) : host;
}
function formatIPv4Address(address, port) {
return address + ':' + port;
}
function formatIPv6Address(address, port) {
var escapedAddress = escapeIPv6Address(address);
return escapedAddress + ':' + port;
}
function defaultPortForScheme(scheme) {
if (scheme === 'http') {
return DEFAULT_HTTP_PORT;
} else if (scheme === 'https') {
return DEFAULT_HTTPS_PORT;
} else {
return DEFAULT_BOLT_PORT;
}
}
exports.default = {
parseDatabaseUrl: parseDatabaseUrl,
defaultPortForScheme: defaultPortForScheme,
formatIPv4Address: formatIPv4Address,
formatIPv6Address: formatIPv6Address
};

123
node_modules/neo4j-driver/lib/v1/internal/utf8.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buf = require('./buf');
var _string_decoder = require('string_decoder');
var _error = require('./../error');
var platformObj = {}; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This module defines a cross-platform UTF-8 encoder and decoder that works
// with the Buffer API defined in buf.js
try {
// This will throw an exception is 'buffer' is not available
require.resolve("buffer");
var decoder = new _string_decoder.StringDecoder('utf8');
var node = require('buffer');
// use static factory function present in newer NodeJS versions to create a buffer containing the given string
// or fallback to the old, potentially deprecated constructor
var newNodeJSBuffer = typeof node.Buffer.from === 'function' ? function (str) {
return node.Buffer.from(str, 'utf8');
} : function (str) {
return new node.Buffer(str, 'utf8');
};
platformObj = {
"encode": function encode(str) {
return new _buf.NodeBuffer(newNodeJSBuffer(str));
},
"decode": function decode(buffer, length) {
if (buffer instanceof _buf.NodeBuffer) {
var start = buffer.position,
end = start + length;
buffer.position = Math.min(end, buffer.length);
return buffer._buffer.toString('utf8', start, end);
} else if (buffer instanceof _buf.CombinedBuffer) {
var out = streamDecodeCombinedBuffer(buffer, length, function (partBuffer) {
return decoder.write(partBuffer._buffer);
}, function () {
return decoder.end();
});
return out;
} else {
throw (0, _error.newError)("Don't know how to decode strings from `" + buffer + "`.");
}
}
};
} catch (e) {
// Not on NodeJS, add shim for WebAPI TextEncoder/TextDecoder
var textEncoding = require('../../external/text-encoding/index');
var encoder = new textEncoding.TextEncoder("utf-8");
var _decoder = new textEncoding.TextDecoder("utf-8");
platformObj = {
"encode": function encode(str) {
return new _buf.HeapBuffer(encoder.encode(str).buffer);
},
"decode": function decode(buffer, length) {
if (buffer instanceof _buf.HeapBuffer) {
return _decoder.decode(buffer.readView(Math.min(length, buffer.length - buffer.position)));
} else {
// Decoding combined buffer is complicated. For simplicity, for now,
// we simply copy the combined buffer into a regular buffer and decode that.
var tmpBuf = (0, _buf.alloc)(length);
for (var i = 0; i < length; i++) {
tmpBuf.writeUInt8(buffer.readUInt8());
}
tmpBuf.reset();
return _decoder.decode(tmpBuf.readView(length));
}
}
};
}
var streamDecodeCombinedBuffer = function streamDecodeCombinedBuffer(combinedBuffers, length, decodeFn, endFn) {
var remainingBytesToRead = length;
var position = combinedBuffers.position;
combinedBuffers._updatePos(Math.min(length, combinedBuffers.length - position));
// Reduce CombinedBuffers to a decoded string
var out = combinedBuffers._buffers.reduce(function (last, partBuffer) {
if (remainingBytesToRead <= 0) {
return last;
} else if (position >= partBuffer.length) {
position -= partBuffer.length;
return '';
} else {
partBuffer._updatePos(position - partBuffer.position);
var bytesToRead = Math.min(partBuffer.length - position, remainingBytesToRead);
var lastSlice = partBuffer.readSlice(bytesToRead);
partBuffer._updatePos(bytesToRead);
remainingBytesToRead = Math.max(remainingBytesToRead - lastSlice.length, 0);
position = 0;
return last + decodeFn(lastSlice);
}
}, '');
return out + endFn();
};
exports.default = platformObj;

147
node_modules/neo4j-driver/lib/v1/internal/util.js generated vendored Normal file
View File

@@ -0,0 +1,147 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ENCRYPTION_OFF = exports.ENCRYPTION_ON = exports.validateStatementAndParameters = exports.assertValidDate = exports.assertNumberOrInteger = exports.assertNumber = exports.assertString = exports.isString = exports.isEmptyObjectOrNull = undefined;
var _isNan = require("babel-runtime/core-js/number/is-nan");
var _isNan2 = _interopRequireDefault(_isNan);
var _stringify = require("babel-runtime/core-js/json/stringify");
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _integer = require("../integer");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ENCRYPTION_ON = "ENCRYPTION_ON"; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ENCRYPTION_OFF = "ENCRYPTION_OFF";
function isEmptyObjectOrNull(obj) {
if (obj === null) {
return true;
}
if (!isObject(obj)) {
return false;
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
function isObject(obj) {
return (typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === 'object' && !Array.isArray(obj) && obj !== null;
}
/**
* Check and normalize given statement and parameters.
* @param {string|{text: string, parameters: object}} statement the statement to check.
* @param {object} parameters
* @return {{query: string, params: object}} the normalized query with parameters.
* @throws TypeError when either given query or parameters are invalid.
*/
function validateStatementAndParameters(statement, parameters) {
var query = statement;
var params = parameters || {};
if ((typeof statement === "undefined" ? "undefined" : (0, _typeof3.default)(statement)) === 'object' && statement.text) {
query = statement.text;
params = statement.parameters || {};
}
assertCypherStatement(query);
assertQueryParameters(params);
return { query: query, params: params };
}
function assertString(obj, objName) {
if (!isString(obj)) {
throw new TypeError(objName + ' expected to be string but was: ' + (0, _stringify2.default)(obj));
}
return obj;
}
function assertNumber(obj, objName) {
if (typeof obj !== 'number') {
throw new TypeError(objName + ' expected to be a number but was: ' + (0, _stringify2.default)(obj));
}
return obj;
}
function assertNumberOrInteger(obj, objName) {
if (typeof obj !== 'number' && !(0, _integer.isInt)(obj)) {
throw new TypeError(objName + ' expected to be either a number or an Integer object but was: ' + (0, _stringify2.default)(obj));
}
return obj;
}
function assertValidDate(obj, objName) {
if (Object.prototype.toString.call(obj) !== '[object Date]') {
throw new TypeError(objName + ' expected to be a standard JavaScript Date but was: ' + (0, _stringify2.default)(obj));
}
if ((0, _isNan2.default)(obj.getTime())) {
throw new TypeError(objName + ' expected to be valid JavaScript Date but its time was NaN: ' + (0, _stringify2.default)(obj));
}
return obj;
}
function assertCypherStatement(obj) {
assertString(obj, 'Cypher statement');
if (obj.trim().length === 0) {
throw new TypeError('Cypher statement is expected to be a non-empty string.');
}
}
function assertQueryParameters(obj) {
if (!isObject(obj)) {
// objects created with `Object.create(null)` do not have a constructor property
var _constructor = obj.constructor ? ' ' + obj.constructor.name : '';
throw new TypeError("Query parameters are expected to either be undefined/null or an object, given:" + _constructor + " " + obj);
}
}
function isString(str) {
return Object.prototype.toString.call(str) === '[object String]';
}
exports.isEmptyObjectOrNull = isEmptyObjectOrNull;
exports.isString = isString;
exports.assertString = assertString;
exports.assertNumber = assertNumber;
exports.assertNumberOrInteger = assertNumberOrInteger;
exports.assertValidDate = assertValidDate;
exports.validateStatementAndParameters = validateStatementAndParameters;
exports.ENCRYPTION_ON = ENCRYPTION_ON;
exports.ENCRYPTION_OFF = ENCRYPTION_OFF;

169
node_modules/neo4j-driver/lib/v1/record.js generated vendored Normal file
View File

@@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
var _error = require("./error");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateFieldLookup(keys) {
var lookup = {};
keys.forEach(function (name, idx) {
lookup[name] = idx;
});
return lookup;
}
/**
* Records make up the contents of the {@link Result}, and is how you access
* the output of a statement. A simple statement might yield a result stream
* with a single record, for instance:
*
* MATCH (u:User) RETURN u.name, u.age
*
* This returns a stream of records with two fields, named `u.name` and `u.age`,
* each record represents one user found by the statement above. You can access
* the values of each field either by name:
*
* record.get("u.name")
*
* Or by it's position:
*
* record.get(0)
*
* @access public
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Record = function () {
/**
* Create a new record object.
* @constructor
* @access private
* @param {string[]} keys An array of field keys, in the order the fields appear in the record
* @param {Array} fields An array of field values
* @param {Object} fieldLookup An object of fieldName -> value index, used to map
* field names to values. If this is null, one will be
* generated.
*/
function Record(keys, fields) {
var fieldLookup = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
(0, _classCallCheck3.default)(this, Record);
this.keys = keys;
this.length = keys.length;
this._fields = fields;
this._fieldLookup = fieldLookup || generateFieldLookup(keys);
}
/**
* Run the given function for each field in this record. The function
* will get three arguments - the value, the key and this record, in that
* order.
*
* @param {function(value: Object, key: string, record: Record)} visitor the function to apply to each field.
*/
(0, _createClass3.default)(Record, [{
key: "forEach",
value: function forEach(visitor) {
for (var i = 0; i < this.keys.length; i++) {
visitor(this._fields[i], this.keys[i], this);
}
}
/**
* Generates an object out of the current Record
*
* @returns {Object}
*/
}, {
key: "toObject",
value: function toObject() {
var object = {};
this.forEach(function (value, key) {
object[key] = value;
});
return object;
}
/**
* Get a value from this record, either by index or by field key.
*
* @param {string|Number} key Field key, or the index of the field.
* @returns {*}
*/
}, {
key: "get",
value: function get(key) {
var index = void 0;
if (!(typeof key === "number")) {
index = this._fieldLookup[key];
if (index === undefined) {
throw (0, _error.newError)("This record has no field with key '" + key + "', available key are: [" + this.keys + "].");
}
} else {
index = key;
}
if (index > this._fields.length - 1 || index < 0) {
throw (0, _error.newError)("This record has no field with index '" + index + "'. Remember that indexes start at `0`, " + "and make sure your statement returns records in the shape you meant it to.");
}
return this._fields[index];
}
/**
* Check if a value from this record, either by index or by field key, exists.
*
* @param {string|Number} key Field key, or the index of the field.
* @returns {boolean}
*/
}, {
key: "has",
value: function has(key) {
// if key is a number, we check if it is in the _fields array
if (typeof key === "number") {
return key >= 0 && key < this._fields.length;
}
// if it's not a number, we check _fieldLookup dictionary directly
return this._fieldLookup[key] !== undefined;
}
}]);
return Record;
}();
exports.default = Record;

446
node_modules/neo4j-driver/lib/v1/result-summary.js generated vendored Normal file
View File

@@ -0,0 +1,446 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.statementType = undefined;
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _integer = require('./integer');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A ResultSummary instance contains structured metadata for a {Result}.
* @access public
*/
var ResultSummary = function () {
/**
* @constructor
* @param {string} statement - The statement this summary is for
* @param {Object} parameters - Parameters for the statement
* @param {Object} metadata - Statement metadata
*/
function ResultSummary(statement, parameters, metadata) {
(0, _classCallCheck3.default)(this, ResultSummary);
/**
* The statement and parameters this summary is for.
* @type {{text: string, parameters: Object}}
* @public
*/
this.statement = { text: statement, parameters: parameters };
/**
* The type of statement executed. Can be "r" for read-only statement, "rw" for read-write statement,
* "w" for write-only statement and "s" for schema-write statement.
* String constants are available in {@link statementType} object.
* @type {string}
* @public
*/
this.statementType = metadata.type;
/**
* Counters for operations the statement triggered.
* @type {StatementStatistics}
* @public
*/
this.counters = new StatementStatistics(metadata.stats || {});
//for backwards compatibility, remove in future version
this.updateStatistics = this.counters;
/**
* This describes how the database will execute the statement.
* Statement plan for the executed statement if available, otherwise undefined.
* Will only be populated for queries that start with "EXPLAIN".
* @type {Plan}
*/
this.plan = metadata.plan || metadata.profile ? new Plan(metadata.plan || metadata.profile) : false;
/**
* This describes how the database did execute your statement. This will contain detailed information about what
* each step of the plan did. Profiled statement plan for the executed statement if available, otherwise undefined.
* Will only be populated for queries that start with "PROFILE".
* @type {ProfiledPlan}
* @public
*/
this.profile = metadata.profile ? new ProfiledPlan(metadata.profile) : false;
/**
* An array of notifications that might arise when executing the statement. Notifications can be warnings about
* problematic statements or other valuable information that can be presented in a client. Unlike failures
* or errors, notifications do not affect the execution of a statement.
* @type {Array<Notification>}
* @public
*/
this.notifications = this._buildNotifications(metadata.notifications);
/**
* The basic information of the server where the result is obtained from.
* @type {ServerInfo}
* @public
*/
this.server = new ServerInfo(metadata.server);
/**
* The time it took the server to consume the result.
* @type {number}
* @public
*/
this.resultConsumedAfter = metadata.result_consumed_after;
/**
* The time it took the server to make the result available for consumption in milliseconds.
* @type {number}
* @public
*/
this.resultAvailableAfter = metadata.result_available_after;
}
(0, _createClass3.default)(ResultSummary, [{
key: '_buildNotifications',
value: function _buildNotifications(notifications) {
if (!notifications) {
return [];
}
return notifications.map(function (n) {
return new Notification(n);
});
}
/**
* Check if the result summary has a plan
* @return {boolean}
*/
}, {
key: 'hasPlan',
value: function hasPlan() {
return this.plan instanceof Plan;
}
/**
* Check if the result summary has a profile
* @return {boolean}
*/
}, {
key: 'hasProfile',
value: function hasProfile() {
return this.profile instanceof ProfiledPlan;
}
}]);
return ResultSummary;
}();
/**
* Class for execution plan received by prepending Cypher with EXPLAIN.
* @access public
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Plan =
/**
* Create a Plan instance
* @constructor
* @param {Object} plan - Object with plan data
*/
function Plan(plan) {
(0, _classCallCheck3.default)(this, Plan);
this.operatorType = plan.operatorType;
this.identifiers = plan.identifiers;
this.arguments = plan.args;
this.children = plan.children ? plan.children.map(function (child) {
return new Plan(child);
}) : [];
};
/**
* Class for execution plan received by prepending Cypher with PROFILE.
* @access public
*/
var ProfiledPlan =
/**
* Create a ProfiledPlan instance
* @constructor
* @param {Object} profile - Object with profile data
*/
function ProfiledPlan(profile) {
(0, _classCallCheck3.default)(this, ProfiledPlan);
this.operatorType = profile.operatorType;
this.identifiers = profile.identifiers;
this.arguments = profile.args;
this.dbHits = profile.args.DbHits.toInt();
this.rows = profile.args.Rows.toInt();
this.children = profile.children ? profile.children.map(function (child) {
return new ProfiledPlan(child);
}) : [];
};
/**
* Get statistical information for a {@link Result}.
* @access public
*/
var StatementStatistics = function () {
/**
* Structurize the statistics
* @constructor
* @param {Object} statistics - Result statistics
*/
function StatementStatistics(statistics) {
var _this = this;
(0, _classCallCheck3.default)(this, StatementStatistics);
this._stats = {
nodesCreated: 0,
nodesDeleted: 0,
relationshipsCreated: 0,
relationshipsDeleted: 0,
propertiesSet: 0,
labelsAdded: 0,
labelsRemoved: 0,
indexesAdded: 0,
indexesRemoved: 0,
constraintsAdded: 0,
constraintsRemoved: 0
};
(0, _keys2.default)(statistics).forEach(function (index) {
//To camelCase
_this._stats[index.replace(/(\-\w)/g, function (m) {
return m[1].toUpperCase();
})] = (0, _integer.isInt)(statistics[index]) ? statistics[index].toInt() : statistics[index];
});
}
/**
* Did the database get updated?
* @return {boolean}
*/
(0, _createClass3.default)(StatementStatistics, [{
key: 'containsUpdates',
value: function containsUpdates() {
var _this2 = this;
return (0, _keys2.default)(this._stats).reduce(function (last, current) {
return last + _this2._stats[current];
}, 0) > 0;
}
/**
* @return {Number} - Number of nodes created.
*/
}, {
key: 'nodesCreated',
value: function nodesCreated() {
return this._stats.nodesCreated;
}
/**
* @return {Number} - Number of nodes deleted.
*/
}, {
key: 'nodesDeleted',
value: function nodesDeleted() {
return this._stats.nodesDeleted;
}
/**
* @return {Number} - Number of relationships created.
*/
}, {
key: 'relationshipsCreated',
value: function relationshipsCreated() {
return this._stats.relationshipsCreated;
}
/**
* @return {Number} - Number of nodes deleted.
*/
}, {
key: 'relationshipsDeleted',
value: function relationshipsDeleted() {
return this._stats.relationshipsDeleted;
}
/**
* @return {Number} - Number of properties set.
*/
}, {
key: 'propertiesSet',
value: function propertiesSet() {
return this._stats.propertiesSet;
}
/**
* @return {Number} - Number of labels added.
*/
}, {
key: 'labelsAdded',
value: function labelsAdded() {
return this._stats.labelsAdded;
}
/**
* @return {Number} - Number of labels removed.
*/
}, {
key: 'labelsRemoved',
value: function labelsRemoved() {
return this._stats.labelsRemoved;
}
/**
* @return {Number} - Number of indexes added.
*/
}, {
key: 'indexesAdded',
value: function indexesAdded() {
return this._stats.indexesAdded;
}
/**
* @return {Number} - Number of indexes removed.
*/
}, {
key: 'indexesRemoved',
value: function indexesRemoved() {
return this._stats.indexesRemoved;
}
/**
* @return {Number} - Number of constraints added.
*/
}, {
key: 'constraintsAdded',
value: function constraintsAdded() {
return this._stats.constraintsAdded;
}
/**
* @return {Number} - Number of constraints removed.
*/
}, {
key: 'constraintsRemoved',
value: function constraintsRemoved() {
return this._stats.constraintsRemoved;
}
}]);
return StatementStatistics;
}();
/**
* Class for Cypher notifications
* @access public
*/
var Notification = function () {
/**
* Create a Notification instance
* @constructor
* @param {Object} notification - Object with notification data
*/
function Notification(notification) {
(0, _classCallCheck3.default)(this, Notification);
this.code = notification.code;
this.title = notification.title;
this.description = notification.description;
this.severity = notification.severity;
this.position = Notification._constructPosition(notification.position);
}
(0, _createClass3.default)(Notification, null, [{
key: '_constructPosition',
value: function _constructPosition(pos) {
if (!pos) {
return {};
}
return {
offset: pos.offset.toInt(),
line: pos.line.toInt(),
column: pos.column.toInt()
};
}
}]);
return Notification;
}();
/**
* Class for exposing server info from a result.
* @access public
*/
var ServerInfo =
/**
* Create a ServerInfo instance
* @constructor
* @param {Object} serverMeta - Object with serverMeta data
*/
function ServerInfo(serverMeta) {
(0, _classCallCheck3.default)(this, ServerInfo);
if (serverMeta) {
this.address = serverMeta.address;
this.version = serverMeta.version;
}
};
var statementType = {
READ_ONLY: 'r',
READ_WRITE: 'rw',
WRITE_ONLY: 'w',
SCHEMA_WRITE: 's'
};
exports.statementType = statementType;
exports.default = ResultSummary;

215
node_modules/neo4j-driver/lib/v1/result.js generated vendored Normal file
View File

@@ -0,0 +1,215 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _resultSummary = require('./result-summary');
var _resultSummary2 = _interopRequireDefault(_resultSummary);
var _connectionHolder = require('./internal/connection-holder');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DEFAULT_ON_ERROR = function DEFAULT_ON_ERROR(error) {
console.log('Uncaught error when processing result: ' + error);
};
var DEFAULT_ON_COMPLETED = function DEFAULT_ON_COMPLETED(summary) {};
/**
* A stream of {@link Record} representing the result of a statement.
* Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary}
* summary, or rejected with error that contains {@link string} code and {@link string} message.
* Alternatively can be consumed lazily using <code>Result.subscribe()</code> function.
* @access public
*/
var Result = function () {
/**
* Inject the observer to be used.
* @constructor
* @access private
* @param {StreamObserver} streamObserver
* @param {mixed} statement - Cypher statement to execute
* @param {Object} parameters - Map with parameters to use in statement
* @param metaSupplier function, when called provides metadata
* @param {ConnectionHolder} connectionHolder - to be notified when result is either fully consumed or error happened.
*/
function Result(streamObserver, statement, parameters, metaSupplier, connectionHolder) {
(0, _classCallCheck3.default)(this, Result);
this._stack = captureStacktrace();
this._streamObserver = streamObserver;
this._p = null;
this._statement = statement;
this._parameters = parameters || {};
this._metaSupplier = metaSupplier || function () {
return {};
};
this._connectionHolder = connectionHolder || _connectionHolder.EMPTY_CONNECTION_HOLDER;
}
/**
* Create and return new Promise
* @return {Promise} new Promise.
* @access private
*/
(0, _createClass3.default)(Result, [{
key: '_createPromise',
value: function _createPromise() {
if (this._p) {
return;
}
var self = this;
this._p = new _promise2.default(function (resolve, reject) {
var records = [];
var observer = {
onNext: function onNext(record) {
records.push(record);
},
onCompleted: function onCompleted(summary) {
resolve({ records: records, summary: summary });
},
onError: function onError(error) {
reject(error);
}
};
self.subscribe(observer);
});
}
/**
* Waits for all results and calls the passed in function with the results.
* Cannot be combined with the <code>Result.subscribe()</code> function.
*
* @param {function(result: {records:Array<Record>, summary: ResultSummary})} onFulfilled - function to be called
* when finished.
* @param {function(error: {message:string, code:string})} onRejected - function to be called upon errors.
* @return {Promise} promise.
*/
}, {
key: 'then',
value: function then(onFulfilled, onRejected) {
this._createPromise();
return this._p.then(onFulfilled, onRejected);
}
/**
* Catch errors when using promises.
* Cannot be used with the subscribe function.
* @param {function(error: Neo4jError)} onRejected - Function to be called upon errors.
* @return {Promise} promise.
*/
}, {
key: 'catch',
value: function _catch(onRejected) {
this._createPromise();
return this._p.catch(onRejected);
}
/**
* Stream records to observer as they come in, this is a more efficient method
* of handling the results, and allows you to handle arbitrarily large results.
*
* @param {Object} observer - Observer object
* @param {function(record: Record)} observer.onNext - handle records, one by one.
* @param {function(summary: ResultSummary)} observer.onCompleted - handle stream tail, the result summary.
* @param {function(error: {message:string, code:string})} observer.onError - handle errors.
* @return
*/
}, {
key: 'subscribe',
value: function subscribe(observer) {
var _this = this;
var self = this;
var onCompletedOriginal = observer.onCompleted || DEFAULT_ON_COMPLETED;
var onCompletedWrapper = function onCompletedWrapper(metadata) {
var additionalMeta = self._metaSupplier();
for (var key in additionalMeta) {
if (additionalMeta.hasOwnProperty(key)) {
metadata[key] = additionalMeta[key];
}
}
var sum = new _resultSummary2.default(_this._statement, _this._parameters, metadata);
// notify connection holder that the used connection is not needed any more because result has
// been fully consumed; call the original onCompleted callback after that
self._connectionHolder.releaseConnection().then(function () {
onCompletedOriginal.call(observer, sum);
});
};
observer.onCompleted = onCompletedWrapper;
var onErrorOriginal = observer.onError || DEFAULT_ON_ERROR;
var onErrorWrapper = function onErrorWrapper(error) {
// notify connection holder that the used connection is not needed any more because error happened
// and result can't bee consumed any further; call the original onError callback after that
self._connectionHolder.releaseConnection().then(function () {
replaceStacktrace(error, _this._stack);
onErrorOriginal.call(observer, error);
});
};
observer.onError = onErrorWrapper;
this._streamObserver.subscribe(observer);
}
}]);
return Result;
}();
function captureStacktrace() {
var error = new Error('');
if (error.stack) {
return error.stack.replace(/^Error(\n\r)*/, ''); // we don't need the 'Error\n' part, if only it exists
}
return null;
}
function replaceStacktrace(error, newStack) {
if (newStack) {
// Error.prototype.toString() concatenates error.name and error.message nicely
// then we add the rest of the stack trace
error.stack = error.toString() + '\n' + newStack;
}
}
exports.default = Result;

197
node_modules/neo4j-driver/lib/v1/routing-driver.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _session = require('./session');
var _session2 = _interopRequireDefault(_session);
var _driver = require('./driver');
var _error = require('./error');
var _connectionProviders = require('./internal/connection-providers');
var _leastConnectedLoadBalancingStrategy = require('./internal/least-connected-load-balancing-strategy');
var _leastConnectedLoadBalancingStrategy2 = _interopRequireDefault(_leastConnectedLoadBalancingStrategy);
var _roundRobinLoadBalancingStrategy = require('./internal/round-robin-load-balancing-strategy');
var _roundRobinLoadBalancingStrategy2 = _interopRequireDefault(_roundRobinLoadBalancingStrategy);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A driver that supports routing in a causal cluster.
* @private
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var RoutingDriver = function (_Driver) {
(0, _inherits3.default)(RoutingDriver, _Driver);
function RoutingDriver(hostPort, routingContext, userAgent) {
var token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var config = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
(0, _classCallCheck3.default)(this, RoutingDriver);
var _this = (0, _possibleConstructorReturn3.default)(this, (RoutingDriver.__proto__ || (0, _getPrototypeOf2.default)(RoutingDriver)).call(this, hostPort, userAgent, token, validateConfig(config)));
_this._routingContext = routingContext;
return _this;
}
(0, _createClass3.default)(RoutingDriver, [{
key: '_createConnectionProvider',
value: function _createConnectionProvider(hostPort, connectionPool, driverOnErrorCallback) {
var loadBalancingStrategy = RoutingDriver._createLoadBalancingStrategy(this._config, connectionPool);
return new _connectionProviders.LoadBalancer(hostPort, this._routingContext, connectionPool, loadBalancingStrategy, driverOnErrorCallback);
}
}, {
key: '_createSession',
value: function _createSession(mode, connectionProvider, bookmark, config) {
var _this2 = this;
return new RoutingSession(mode, connectionProvider, bookmark, config, function (error, conn) {
if (!conn) {
// connection can be undefined if error happened before connection was acquired
return error;
}
var hostPort = conn.hostPort;
if (error.code === _error.SESSION_EXPIRED || isDatabaseUnavailable(error)) {
_this2._connectionProvider.forget(hostPort);
return error;
} else if (isFailureToWrite(error)) {
_this2._connectionProvider.forgetWriter(hostPort);
return (0, _error.newError)('No longer possible to write to server at ' + hostPort, _error.SESSION_EXPIRED);
} else {
return error;
}
});
}
}, {
key: '_connectionErrorCode',
value: function _connectionErrorCode() {
// connection errors mean SERVICE_UNAVAILABLE for direct driver but for routing driver they should only
// result in SESSION_EXPIRED because there might still exist other servers capable of serving the request
return _error.SESSION_EXPIRED;
}
/**
* Create new load balancing strategy based on the config.
* @param {object} config the user provided config.
* @param {Pool} connectionPool the connection pool for this driver.
* @return {LoadBalancingStrategy} new strategy.
* @private
*/
}], [{
key: '_createLoadBalancingStrategy',
value: function _createLoadBalancingStrategy(config, connectionPool) {
var configuredValue = config.loadBalancingStrategy;
if (!configuredValue || configuredValue === _leastConnectedLoadBalancingStrategy.LEAST_CONNECTED_STRATEGY_NAME) {
return new _leastConnectedLoadBalancingStrategy2.default(connectionPool);
} else if (configuredValue === _roundRobinLoadBalancingStrategy.ROUND_ROBIN_STRATEGY_NAME) {
return new _roundRobinLoadBalancingStrategy2.default();
} else {
throw (0, _error.newError)('Unknown load balancing strategy: ' + configuredValue);
}
}
}]);
return RoutingDriver;
}(_driver.Driver);
/**
* @private
*/
function validateConfig(config) {
if (config.trust === 'TRUST_ON_FIRST_USE') {
throw (0, _error.newError)('The chosen trust mode is not compatible with a routing driver');
}
return config;
}
/**
* @private
*/
function isFailureToWrite(error) {
return error.code === 'Neo.ClientError.Cluster.NotALeader' || error.code === 'Neo.ClientError.General.ForbiddenOnReadOnlyDatabase';
}
/**
* @private
*/
function isDatabaseUnavailable(error) {
return error.code === 'Neo.TransientError.General.DatabaseUnavailable';
}
/**
* @private
*/
var RoutingSession = function (_Session) {
(0, _inherits3.default)(RoutingSession, _Session);
function RoutingSession(mode, connectionProvider, bookmark, config, onFailedConnection) {
(0, _classCallCheck3.default)(this, RoutingSession);
var _this3 = (0, _possibleConstructorReturn3.default)(this, (RoutingSession.__proto__ || (0, _getPrototypeOf2.default)(RoutingSession)).call(this, mode, connectionProvider, bookmark, config));
_this3._onFailedConnection = onFailedConnection;
return _this3;
}
(0, _createClass3.default)(RoutingSession, [{
key: '_onRunFailure',
value: function _onRunFailure() {
return this._onFailedConnection;
}
}]);
return RoutingSession;
}(_session2.default);
exports.default = RoutingDriver;

308
node_modules/neo4j-driver/lib/v1/session.js generated vendored Normal file
View File

@@ -0,0 +1,308 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _streamObserver = require('./internal/stream-observer');
var _streamObserver2 = _interopRequireDefault(_streamObserver);
var _result = require('./result');
var _result2 = _interopRequireDefault(_result);
var _transaction = require('./transaction');
var _transaction2 = _interopRequireDefault(_transaction);
var _error = require('./error');
var _util = require('./internal/util');
var _connectionHolder = require('./internal/connection-holder');
var _connectionHolder2 = _interopRequireDefault(_connectionHolder);
var _driver = require('./driver');
var _driver2 = _interopRequireDefault(_driver);
var _transactionExecutor = require('./internal/transaction-executor');
var _transactionExecutor2 = _interopRequireDefault(_transactionExecutor);
var _bookmark = require('./internal/bookmark');
var _bookmark2 = _interopRequireDefault(_bookmark);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A Session instance is used for handling the connection and
* sending statements through the connection.
* @access public
*/
var Session = function () {
/**
* @constructor
* @param {string} mode the default access mode for this session.
* @param {ConnectionProvider} connectionProvider - the connection provider to acquire connections from.
* @param {Bookmark} bookmark - the initial bookmark for this session.
* @param {Object} [config={}] - this driver configuration.
*/
function Session(mode, connectionProvider, bookmark, config) {
(0, _classCallCheck3.default)(this, Session);
this._mode = mode;
this._readConnectionHolder = new _connectionHolder2.default(_driver.READ, connectionProvider);
this._writeConnectionHolder = new _connectionHolder2.default(_driver.WRITE, connectionProvider);
this._open = true;
this._hasTx = false;
this._lastBookmark = bookmark;
this._transactionExecutor = _createTransactionExecutor(config);
}
/**
* Run Cypher statement
* Could be called with a statement object i.e.: {text: "MATCH ...", parameters: {param: 1}}
* or with the statement and parameters as separate arguments.
* @param {mixed} statement - Cypher statement to execute
* @param {Object} parameters - Map with parameters to use in statement
* @return {Result} - New Result
*/
(0, _createClass3.default)(Session, [{
key: 'run',
value: function run(statement) {
var parameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _validateStatementAnd = (0, _util.validateStatementAndParameters)(statement, parameters),
query = _validateStatementAnd.query,
params = _validateStatementAnd.params;
return this._run(query, params, function (connection, streamObserver) {
return connection.run(query, params, streamObserver);
});
}
}, {
key: '_run',
value: function _run(statement, parameters, statementRunner) {
var streamObserver = new _streamObserver2.default(this._onRunFailure());
var connectionHolder = this._connectionHolderWithMode(this._mode);
if (!this._hasTx) {
connectionHolder.initializeConnection();
connectionHolder.getConnection(streamObserver).then(function (connection) {
statementRunner(connection, streamObserver);
connection.pullAll(streamObserver);
connection.sync();
}).catch(function (error) {
return streamObserver.onError(error);
});
} else {
streamObserver.onError((0, _error.newError)('Statements cannot be run directly on a ' + 'session with an open transaction; either run from within the ' + 'transaction or use a different session.'));
}
return new _result2.default(streamObserver, statement, parameters, function () {
return streamObserver.serverMetadata();
}, connectionHolder);
}
/**
* Begin a new transaction in this session. A session can have at most one transaction running at a time, if you
* want to run multiple concurrent transactions, you should use multiple concurrent sessions.
*
* While a transaction is open the session cannot be used to run statements outside the transaction.
*
* @param {string|string[]} [bookmarkOrBookmarks=null] - reference or references to some previous transactions.
* DEPRECATED: This parameter is deprecated in favour of {@link Driver#session} that accepts an initial bookmark.
* Session will ensure that all nested transactions are chained with bookmarks to guarantee causal consistency.
* @returns {Transaction} - New Transaction
*/
}, {
key: 'beginTransaction',
value: function beginTransaction(bookmarkOrBookmarks) {
this._updateBookmark(new _bookmark2.default(bookmarkOrBookmarks));
return this._beginTransaction(this._mode);
}
}, {
key: '_beginTransaction',
value: function _beginTransaction(accessMode) {
var _this = this;
if (this._hasTx) {
throw (0, _error.newError)('You cannot begin a transaction on a session with an open transaction; ' + 'either run from within the transaction or use a different session.');
}
var mode = _driver2.default._validateSessionMode(accessMode);
var connectionHolder = this._connectionHolderWithMode(mode);
connectionHolder.initializeConnection();
this._hasTx = true;
return new _transaction2.default(connectionHolder, function () {
_this._hasTx = false;
}, this._onRunFailure(), this._lastBookmark, this._updateBookmark.bind(this));
}
/**
* Return the bookmark received following the last completed {@link Transaction}.
*
* @return {string|null} a reference to a previous transaction
*/
}, {
key: 'lastBookmark',
value: function lastBookmark() {
return this._lastBookmark.maxBookmarkAsString();
}
/**
* Execute given unit of work in a {@link READ} transaction.
*
* Transaction will automatically be committed unless the given function throws or returns a rejected promise.
* Some failures of the given function or the commit itself will be retried with exponential backoff with initial
* delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's
* <code>maxTransactionRetryTime</code> property in milliseconds.
*
* @param {function(tx: Transaction): Promise} transactionWork - callback that executes operations against
* a given {@link Transaction}.
* @return {Promise} resolved promise as returned by the given function or rejected promise when given
* function or commit fails.
*/
}, {
key: 'readTransaction',
value: function readTransaction(transactionWork) {
return this._runTransaction(_driver.READ, transactionWork);
}
/**
* Execute given unit of work in a {@link WRITE} transaction.
*
* Transaction will automatically be committed unless the given function throws or returns a rejected promise.
* Some failures of the given function or the commit itself will be retried with exponential backoff with initial
* delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's
* <code>maxTransactionRetryTime</code> property in milliseconds.
*
* @param {function(tx: Transaction): Promise} transactionWork - callback that executes operations against
* a given {@link Transaction}.
* @return {Promise} resolved promise as returned by the given function or rejected promise when given
* function or commit fails.
*/
}, {
key: 'writeTransaction',
value: function writeTransaction(transactionWork) {
return this._runTransaction(_driver.WRITE, transactionWork);
}
}, {
key: '_runTransaction',
value: function _runTransaction(accessMode, transactionWork) {
var _this2 = this;
return this._transactionExecutor.execute(function () {
return _this2._beginTransaction(accessMode);
}, transactionWork);
}
/**
* Update value of the last bookmark.
* @param {Bookmark} newBookmark the new bookmark.
* @private
*/
}, {
key: '_updateBookmark',
value: function _updateBookmark(newBookmark) {
if (newBookmark && !newBookmark.isEmpty()) {
this._lastBookmark = newBookmark;
}
}
/**
* Close this session.
* @param {function()} callback - Function to be called after the session has been closed
* @return
*/
}, {
key: 'close',
value: function close() {
var _this3 = this;
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {
return null;
};
if (this._open) {
this._open = false;
this._transactionExecutor.close();
this._readConnectionHolder.close().then(function () {
_this3._writeConnectionHolder.close().then(function () {
callback();
});
});
} else {
callback();
}
}
//Can be overridden to add error callback on RUN
}, {
key: '_onRunFailure',
value: function _onRunFailure() {
return function (err) {
return err;
};
}
}, {
key: '_connectionHolderWithMode',
value: function _connectionHolderWithMode(mode) {
if (mode === _driver.READ) {
return this._readConnectionHolder;
} else if (mode === _driver.WRITE) {
return this._writeConnectionHolder;
} else {
throw (0, _error.newError)('Unknown access mode: ' + mode);
}
}
}]);
return Session;
}(); /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function _createTransactionExecutor(config) {
var maxRetryTimeMs = config && config.maxTransactionRetryTime ? config.maxTransactionRetryTime : null;
return new _transactionExecutor2.default(maxRetryTimeMs);
}
exports.default = Session;

104
node_modules/neo4j-driver/lib/v1/spatial-types.js generated vendored Normal file
View File

@@ -0,0 +1,104 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Point = undefined;
var _defineProperty = require('babel-runtime/core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
var _isInteger = require('babel-runtime/core-js/number/is-integer');
var _isInteger2 = _interopRequireDefault(_isInteger);
var _freeze = require('babel-runtime/core-js/object/freeze');
var _freeze2 = _interopRequireDefault(_freeze);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.isPoint = isPoint;
var _util = require('./internal/util');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var POINT_IDENTIFIER_PROPERTY = '__isPoint__';
/**
* Represents a single two or three-dimensional point in a particular coordinate reference system.
* Created <code>Point</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Point = exports.Point = function () {
/**
* @constructor
* @param {Integer|number} srid the coordinate reference system identifier.
* @param {number} x the <code>x</code> coordinate of the point.
* @param {number} y the <code>y</code> coordinate of the point.
* @param {number} [z=undefined] the <code>y</code> coordinate of the point or <code>undefined</code> if point has 2 dimensions.
*/
function Point(srid, x, y, z) {
(0, _classCallCheck3.default)(this, Point);
this.srid = (0, _util.assertNumberOrInteger)(srid, 'SRID');
this.x = (0, _util.assertNumber)(x, 'X coordinate');
this.y = (0, _util.assertNumber)(y, 'Y coordinate');
this.z = z === null || z === undefined ? z : (0, _util.assertNumber)(z, 'Z coordinate');
(0, _freeze2.default)(this);
}
(0, _createClass3.default)(Point, [{
key: 'toString',
value: function toString() {
return this.z || this.z === 0 ? 'Point{srid=' + formatAsFloat(this.srid) + ', x=' + formatAsFloat(this.x) + ', y=' + formatAsFloat(this.y) + ', z=' + formatAsFloat(this.z) + '}' : 'Point{srid=' + formatAsFloat(this.srid) + ', x=' + formatAsFloat(this.x) + ', y=' + formatAsFloat(this.y) + '}';
}
}]);
return Point;
}();
function formatAsFloat(number) {
return (0, _isInteger2.default)(number) ? number + '.0' : number.toString();
}
(0, _defineProperty2.default)(Point.prototype, POINT_IDENTIFIER_PROPERTY, {
value: true,
enumerable: false,
configurable: false
});
/**
* Test if given object is an instance of {@link Point} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link Point}, <code>false</code> otherwise.
*/
function isPoint(obj) {
return (obj && obj[POINT_IDENTIFIER_PROPERTY]) === true;
}

476
node_modules/neo4j-driver/lib/v1/temporal-types.js generated vendored Normal file
View File

@@ -0,0 +1,476 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DateTime = exports.LocalDateTime = exports.Date = exports.Time = exports.LocalTime = exports.Duration = undefined;
var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _defineProperty = require('babel-runtime/core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
var _freeze = require('babel-runtime/core-js/object/freeze');
var _freeze2 = _interopRequireDefault(_freeze);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.isDuration = isDuration;
exports.isLocalTime = isLocalTime;
exports.isTime = isTime;
exports.isDate = isDate;
exports.isLocalDateTime = isLocalDateTime;
exports.isDateTime = isDateTime;
var _temporalUtil = require('./internal/temporal-util');
var util = _interopRequireWildcard(_temporalUtil);
var _util = require('./internal/util');
var _error = require('./error');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var IDENTIFIER_PROPERTY_ATTRIBUTES = {
value: true,
enumerable: false,
configurable: false
}; /**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DURATION_IDENTIFIER_PROPERTY = '__isDuration__';
var LOCAL_TIME_IDENTIFIER_PROPERTY = '__isLocalTime__';
var TIME_IDENTIFIER_PROPERTY = '__isTime__';
var DATE_IDENTIFIER_PROPERTY = '__isDate__';
var LOCAL_DATE_TIME_IDENTIFIER_PROPERTY = '__isLocalDateTime__';
var DATE_TIME_IDENTIFIER_PROPERTY = '__isDateTime__';
/**
* Represents an ISO 8601 duration. Contains both date-based values (years, months, days) and time-based values (seconds, nanoseconds).
* Created <code>Duration</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
var Duration = exports.Duration = function () {
/**
* @constructor
* @param {Integer|number} months the number of months for the new duration.
* @param {Integer|number} days the number of days for the new duration.
* @param {Integer|number} seconds the number of seconds for the new duration.
* @param {Integer|number} nanoseconds the number of nanoseconds for the new duration.
*/
function Duration(months, days, seconds, nanoseconds) {
(0, _classCallCheck3.default)(this, Duration);
this.months = (0, _util.assertNumberOrInteger)(months, 'Months');
this.days = (0, _util.assertNumberOrInteger)(days, 'Days');
(0, _util.assertNumberOrInteger)(seconds, 'Seconds');
(0, _util.assertNumberOrInteger)(nanoseconds, 'Nanoseconds');
this.seconds = util.normalizeSecondsForDuration(seconds, nanoseconds);
this.nanoseconds = util.normalizeNanosecondsForDuration(nanoseconds);
(0, _freeze2.default)(this);
}
(0, _createClass3.default)(Duration, [{
key: 'toString',
value: function toString() {
return util.durationToIsoString(this.months, this.days, this.seconds, this.nanoseconds);
}
}]);
return Duration;
}();
(0, _defineProperty2.default)(Duration.prototype, DURATION_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
* Test if given object is an instance of {@link Duration} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link Duration}, <code>false</code> otherwise.
*/
function isDuration(obj) {
return hasIdentifierProperty(obj, DURATION_IDENTIFIER_PROPERTY);
}
/**
* Represents an instant capturing the time of day, but not the date, nor the timezone.
* Created <code>LocalTime</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
var LocalTime = exports.LocalTime = function () {
/**
* @constructor
* @param {Integer|number} hour the hour for the new local time.
* @param {Integer|number} minute the minute for the new local time.
* @param {Integer|number} second the second for the new local time.
* @param {Integer|number} nanosecond the nanosecond for the new local time.
*/
function LocalTime(hour, minute, second, nanosecond) {
(0, _classCallCheck3.default)(this, LocalTime);
this.hour = util.assertValidHour(hour);
this.minute = util.assertValidMinute(minute);
this.second = util.assertValidSecond(second);
this.nanosecond = util.assertValidNanosecond(nanosecond);
(0, _freeze2.default)(this);
}
/**
* Create a local time object from the given standard JavaScript <code>Date</code> and optional nanoseconds.
* Year, month, day and time zone offset components of the given date are ignored.
* @param {global.Date} standardDate the standard JavaScript date to convert.
* @param {Integer|number|undefined} nanosecond the optional amount of nanoseconds.
* @return {LocalTime} new local time.
*/
(0, _createClass3.default)(LocalTime, [{
key: 'toString',
value: function toString() {
return util.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond);
}
}], [{
key: 'fromStandardDate',
value: function fromStandardDate(standardDate, nanosecond) {
verifyStandardDateAndNanos(standardDate, nanosecond);
return new LocalTime(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util.totalNanoseconds(standardDate, nanosecond));
}
}]);
return LocalTime;
}();
(0, _defineProperty2.default)(LocalTime.prototype, LOCAL_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
* Test if given object is an instance of {@link LocalTime} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link LocalTime}, <code>false</code> otherwise.
*/
function isLocalTime(obj) {
return hasIdentifierProperty(obj, LOCAL_TIME_IDENTIFIER_PROPERTY);
}
/**
* Represents an instant capturing the time of day, and the timezone offset in seconds, but not the date.
* Created <code>Time</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
var Time = exports.Time = function () {
/**
* @constructor
* @param {Integer|number} hour the hour for the new local time.
* @param {Integer|number} minute the minute for the new local time.
* @param {Integer|number} second the second for the new local time.
* @param {Integer|number} nanosecond the nanosecond for the new local time.
* @param {Integer|number} timeZoneOffsetSeconds the time zone offset in seconds.
*/
function Time(hour, minute, second, nanosecond, timeZoneOffsetSeconds) {
(0, _classCallCheck3.default)(this, Time);
this.hour = util.assertValidHour(hour);
this.minute = util.assertValidMinute(minute);
this.second = util.assertValidSecond(second);
this.nanosecond = util.assertValidNanosecond(nanosecond);
this.timeZoneOffsetSeconds = (0, _util.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds');
(0, _freeze2.default)(this);
}
/**
* Create a time object from the given standard JavaScript <code>Date</code> and optional nanoseconds.
* Year, month and day components of the given date are ignored.
* @param {global.Date} standardDate the standard JavaScript date to convert.
* @param {Integer|number|undefined} nanosecond the optional amount of nanoseconds.
* @return {Time} new time.
*/
(0, _createClass3.default)(Time, [{
key: 'toString',
value: function toString() {
return util.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond) + util.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds);
}
}], [{
key: 'fromStandardDate',
value: function fromStandardDate(standardDate, nanosecond) {
verifyStandardDateAndNanos(standardDate, nanosecond);
return new Time(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util.totalNanoseconds(standardDate, nanosecond), util.timeZoneOffsetInSeconds(standardDate));
}
}]);
return Time;
}();
(0, _defineProperty2.default)(Time.prototype, TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
* Test if given object is an instance of {@link Time} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link Time}, <code>false</code> otherwise.
*/
function isTime(obj) {
return hasIdentifierProperty(obj, TIME_IDENTIFIER_PROPERTY);
}
/**
* Represents an instant capturing the date, but not the time, nor the timezone.
* Created <code>Date</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
var Date = exports.Date = function () {
/**
* @constructor
* @param {Integer|number} year the year for the new local date.
* @param {Integer|number} month the month for the new local date.
* @param {Integer|number} day the day for the new local date.
*/
function Date(year, month, day) {
(0, _classCallCheck3.default)(this, Date);
this.year = util.assertValidYear(year);
this.month = util.assertValidMonth(month);
this.day = util.assertValidDay(day);
(0, _freeze2.default)(this);
}
/**
* Create a date object from the given standard JavaScript <code>Date</code>.
* Hour, minute, second, millisecond and time zone offset components of the given date are ignored.
* @param {global.Date} standardDate the standard JavaScript date to convert.
* @return {Date} new date.
*/
(0, _createClass3.default)(Date, [{
key: 'toString',
value: function toString() {
return util.dateToIsoString(this.year, this.month, this.day);
}
}], [{
key: 'fromStandardDate',
value: function fromStandardDate(standardDate) {
verifyStandardDateAndNanos(standardDate, null);
return new Date(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate());
}
}]);
return Date;
}();
(0, _defineProperty2.default)(Date.prototype, DATE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
* Test if given object is an instance of {@link Date} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link Date}, <code>false</code> otherwise.
*/
function isDate(obj) {
return hasIdentifierProperty(obj, DATE_IDENTIFIER_PROPERTY);
}
/**
* Represents an instant capturing the date and the time, but not the timezone.
* Created <code>LocalDateTime</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
var LocalDateTime = exports.LocalDateTime = function () {
/**
* @constructor
* @param {Integer|number} year the year for the new local date.
* @param {Integer|number} month the month for the new local date.
* @param {Integer|number} day the day for the new local date.
* @param {Integer|number} hour the hour for the new local time.
* @param {Integer|number} minute the minute for the new local time.
* @param {Integer|number} second the second for the new local time.
* @param {Integer|number} nanosecond the nanosecond for the new local time.
*/
function LocalDateTime(year, month, day, hour, minute, second, nanosecond) {
(0, _classCallCheck3.default)(this, LocalDateTime);
this.year = util.assertValidYear(year);
this.month = util.assertValidMonth(month);
this.day = util.assertValidDay(day);
this.hour = util.assertValidHour(hour);
this.minute = util.assertValidMinute(minute);
this.second = util.assertValidSecond(second);
this.nanosecond = util.assertValidNanosecond(nanosecond);
(0, _freeze2.default)(this);
}
/**
* Create a local date-time object from the given standard JavaScript <code>Date</code> and optional nanoseconds.
* Time zone offset component of the given date is ignored.
* @param {global.Date} standardDate the standard JavaScript date to convert.
* @param {Integer|number|undefined} nanosecond the optional amount of nanoseconds.
* @return {LocalDateTime} new local date-time.
*/
(0, _createClass3.default)(LocalDateTime, [{
key: 'toString',
value: function toString() {
return localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond);
}
}], [{
key: 'fromStandardDate',
value: function fromStandardDate(standardDate, nanosecond) {
verifyStandardDateAndNanos(standardDate, nanosecond);
return new LocalDateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util.totalNanoseconds(standardDate, nanosecond));
}
}]);
return LocalDateTime;
}();
(0, _defineProperty2.default)(LocalDateTime.prototype, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
* Test if given object is an instance of {@link LocalDateTime} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link LocalDateTime}, <code>false</code> otherwise.
*/
function isLocalDateTime(obj) {
return hasIdentifierProperty(obj, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY);
}
/**
* Represents an instant capturing the date, the time and the timezone identifier.
* Created <code>DateTime</code> objects are frozen with {@link Object#freeze()} in constructor and thus immutable.
*/
var DateTime = exports.DateTime = function () {
/**
* @constructor
* @param {Integer|number} year the year for the new date-time.
* @param {Integer|number} month the month for the new date-time.
* @param {Integer|number} day the day for the new date-time.
* @param {Integer|number} hour the hour for the new date-time.
* @param {Integer|number} minute the minute for the new date-time.
* @param {Integer|number} second the second for the new date-time.
* @param {Integer|number} nanosecond the nanosecond for the new date-time.
* @param {Integer|number|null} timeZoneOffsetSeconds the total time zone offset in seconds for the new date-time. Either this argument or <code>timeZoneId</code> should be defined.
* @param {string|null} timeZoneId the time zone id for the new date-time. Either this argument or <code>timeZoneOffsetSeconds</code> should be defined.
*/
function DateTime(year, month, day, hour, minute, second, nanosecond, timeZoneOffsetSeconds, timeZoneId) {
(0, _classCallCheck3.default)(this, DateTime);
this.year = util.assertValidYear(year);
this.month = util.assertValidMonth(month);
this.day = util.assertValidDay(day);
this.hour = util.assertValidHour(hour);
this.minute = util.assertValidMinute(minute);
this.second = util.assertValidSecond(second);
this.nanosecond = util.assertValidNanosecond(nanosecond);
var _verifyTimeZoneArgume = verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId),
_verifyTimeZoneArgume2 = (0, _slicedToArray3.default)(_verifyTimeZoneArgume, 2),
offset = _verifyTimeZoneArgume2[0],
id = _verifyTimeZoneArgume2[1];
this.timeZoneOffsetSeconds = offset;
this.timeZoneId = id;
(0, _freeze2.default)(this);
}
/**
* Create a date-time object from the given standard JavaScript <code>Date</code> and optional nanoseconds.
* @param {global.Date} standardDate the standard JavaScript date to convert.
* @param {Integer|number|undefined} nanosecond the optional amount of nanoseconds.
* @return {DateTime} new date-time.
*/
(0, _createClass3.default)(DateTime, [{
key: 'toString',
value: function toString() {
var localDateTimeStr = localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond);
var timeZoneStr = this.timeZoneId ? '[' + this.timeZoneId + ']' : util.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds);
return localDateTimeStr + timeZoneStr;
}
}], [{
key: 'fromStandardDate',
value: function fromStandardDate(standardDate, nanosecond) {
verifyStandardDateAndNanos(standardDate, nanosecond);
return new DateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util.totalNanoseconds(standardDate, nanosecond), util.timeZoneOffsetInSeconds(standardDate), null /* no time zone id */);
}
}]);
return DateTime;
}();
(0, _defineProperty2.default)(DateTime.prototype, DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
* Test if given object is an instance of {@link DateTime} class.
* @param {object} obj the object to test.
* @return {boolean} <code>true</code> if given object is a {@link DateTime}, <code>false</code> otherwise.
*/
function isDateTime(obj) {
return hasIdentifierProperty(obj, DATE_TIME_IDENTIFIER_PROPERTY);
}
function hasIdentifierProperty(obj, property) {
return (obj && obj[property]) === true;
}
function localDateTimeToString(year, month, day, hour, minute, second, nanosecond) {
return util.dateToIsoString(year, month, day) + 'T' + util.timeToIsoString(hour, minute, second, nanosecond);
}
function verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId) {
var offsetDefined = timeZoneOffsetSeconds || timeZoneOffsetSeconds === 0;
var idDefined = timeZoneId && timeZoneId !== '';
if (offsetDefined && !idDefined) {
(0, _util.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds');
return [timeZoneOffsetSeconds, null];
} else if (!offsetDefined && idDefined) {
(0, _util.assertString)(timeZoneId, 'Time zone ID');
return [null, timeZoneId];
} else if (offsetDefined && idDefined) {
throw (0, _error.newError)('Unable to create DateTime with both time zone offset and id. Please specify either of them. Given offset: ' + timeZoneOffsetSeconds + ' and id: ' + timeZoneId);
} else {
throw (0, _error.newError)('Unable to create DateTime without either time zone offset or id. Please specify either of them. Given offset: ' + timeZoneOffsetSeconds + ' and id: ' + timeZoneId);
}
}
function verifyStandardDateAndNanos(standardDate, nanosecond) {
(0, _util.assertValidDate)(standardDate, 'Standard date');
if (nanosecond !== null && nanosecond !== undefined) {
(0, _util.assertNumberOrInteger)(nanosecond, 'Nanosecond');
}
}

369
node_modules/neo4j-driver/lib/v1/transaction.js generated vendored Normal file
View File

@@ -0,0 +1,369 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _get2 = require('babel-runtime/helpers/get');
var _get3 = _interopRequireDefault(_get2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _streamObserver = require('./internal/stream-observer');
var _streamObserver2 = _interopRequireDefault(_streamObserver);
var _result = require('./result');
var _result2 = _interopRequireDefault(_result);
var _util = require('./internal/util');
var _connectionHolder = require('./internal/connection-holder');
var _bookmark = require('./internal/bookmark');
var _bookmark2 = _interopRequireDefault(_bookmark);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Represents a transaction in the Neo4j database.
*
* @access public
*/
var Transaction = function () {
/**
* @constructor
* @param {ConnectionHolder} connectionHolder - the connection holder to get connection from.
* @param {function()} onClose - Function to be called when transaction is committed or rolled back.
* @param {function(error: Error): Error} errorTransformer callback use to transform error.
* @param {Bookmark} bookmark bookmark for transaction begin.
* @param {function(bookmark: Bookmark)} onBookmark callback invoked when new bookmark is produced.
*/
function Transaction(connectionHolder, onClose, errorTransformer, bookmark, onBookmark) {
(0, _classCallCheck3.default)(this, Transaction);
this._connectionHolder = connectionHolder;
var streamObserver = new _TransactionStreamObserver(this);
this._connectionHolder.getConnection(streamObserver).then(function (conn) {
conn.run('BEGIN', bookmark.asBeginTransactionParameters(), streamObserver);
conn.pullAll(streamObserver);
}).catch(function (error) {
return streamObserver.onError(error);
});
this._state = _states.ACTIVE;
this._onClose = onClose;
this._errorTransformer = errorTransformer;
this._onBookmark = onBookmark;
}
/**
* Run Cypher statement
* Could be called with a statement object i.e.: <code>{text: "MATCH ...", parameters: {param: 1}}</code>
* or with the statement and parameters as separate arguments.
* @param {mixed} statement - Cypher statement to execute
* @param {Object} parameters - Map with parameters to use in statement
* @return {Result} New Result
*/
(0, _createClass3.default)(Transaction, [{
key: 'run',
value: function run(statement, parameters) {
var _validateStatementAnd = (0, _util.validateStatementAndParameters)(statement, parameters),
query = _validateStatementAnd.query,
params = _validateStatementAnd.params;
return this._state.run(this._connectionHolder, new _TransactionStreamObserver(this), query, params);
}
/**
* Commits the transaction and returns the result.
*
* After committing the transaction can no longer be used.
*
* @returns {Result} New Result
*/
}, {
key: 'commit',
value: function commit() {
var committed = this._state.commit(this._connectionHolder, new _TransactionStreamObserver(this));
this._state = committed.state;
//clean up
this._onClose();
return committed.result;
}
/**
* Rollbacks the transaction.
*
* After rolling back, the transaction can no longer be used.
*
* @returns {Result} New Result
*/
}, {
key: 'rollback',
value: function rollback() {
var committed = this._state.rollback(this._connectionHolder, new _TransactionStreamObserver(this));
this._state = committed.state;
//clean up
this._onClose();
return committed.result;
}
/**
* Check if this transaction is active, which means commit and rollback did not happen.
* @return {boolean} <code>true</code> when not committed and not rolled back, <code>false</code> otherwise.
*/
}, {
key: 'isOpen',
value: function isOpen() {
return this._state == _states.ACTIVE;
}
}, {
key: '_onError',
value: function _onError() {
var _this = this;
if (this.isOpen()) {
// attempt to rollback, useful when Transaction#run() failed
return this.rollback().catch(function (ignoredError) {
// ignore all errors because it is best effort and transaction might already be rolled back
}).then(function () {
// after rollback attempt change this transaction's state to FAILED
_this._state = _states.FAILED;
});
} else {
// error happened in in-active transaction, just to the cleanup and change state to FAILED
this._state = _states.FAILED;
this._onClose();
// no async actions needed - return resolved promise
return _promise2.default.resolve();
}
}
}]);
return Transaction;
}();
/** Internal stream observer used for transactional results*/
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var _TransactionStreamObserver = function (_StreamObserver) {
(0, _inherits3.default)(_TransactionStreamObserver, _StreamObserver);
function _TransactionStreamObserver(tx) {
(0, _classCallCheck3.default)(this, _TransactionStreamObserver);
var _this2 = (0, _possibleConstructorReturn3.default)(this, (_TransactionStreamObserver.__proto__ || (0, _getPrototypeOf2.default)(_TransactionStreamObserver)).call(this, tx._errorTransformer || function (err) {
return err;
}));
_this2._tx = tx;
//this is to to avoid multiple calls to onError caused by IGNORED
_this2._hasFailed = false;
return _this2;
}
(0, _createClass3.default)(_TransactionStreamObserver, [{
key: 'onError',
value: function onError(error) {
var _this3 = this;
if (!this._hasFailed) {
this._tx._onError().then(function () {
(0, _get3.default)(_TransactionStreamObserver.prototype.__proto__ || (0, _getPrototypeOf2.default)(_TransactionStreamObserver.prototype), 'onError', _this3).call(_this3, error);
_this3._hasFailed = true;
});
}
}
}, {
key: 'onCompleted',
value: function onCompleted(meta) {
(0, _get3.default)(_TransactionStreamObserver.prototype.__proto__ || (0, _getPrototypeOf2.default)(_TransactionStreamObserver.prototype), 'onCompleted', this).call(this, meta);
var bookmark = new _bookmark2.default(meta.bookmark);
this._tx._onBookmark(bookmark);
}
}]);
return _TransactionStreamObserver;
}(_streamObserver2.default);
/** internal state machine of the transaction*/
var _states = {
//The transaction is running with no explicit success or failure marked
ACTIVE: {
commit: function commit(connectionHolder, observer) {
return { result: _runPullAll("COMMIT", connectionHolder, observer),
state: _states.SUCCEEDED };
},
rollback: function rollback(connectionHolder, observer) {
return { result: _runPullAll("ROLLBACK", connectionHolder, observer), state: _states.ROLLED_BACK };
},
run: function run(connectionHolder, observer, statement, parameters) {
connectionHolder.getConnection(observer).then(function (conn) {
conn.run(statement, parameters || {}, observer);
conn.pullAll(observer);
conn.sync();
}).catch(function (error) {
return observer.onError(error);
});
return _newRunResult(observer, statement, parameters, function () {
return observer.serverMetadata();
});
}
},
//An error has occurred, transaction can no longer be used and no more messages will
// be sent for this transaction.
FAILED: {
commit: function commit(connectionHolder, observer) {
observer.onError({
error: "Cannot commit statements in this transaction, because previous statements in the " + "transaction has failed and the transaction has been rolled back. Please start a new" + " transaction to run another statement."
});
return { result: _newDummyResult(observer, "COMMIT", {}), state: _states.FAILED };
},
rollback: function rollback(connectionHolder, observer) {
observer.onError({ error: "Cannot rollback transaction, because previous statements in the " + "transaction has failed and the transaction has already been rolled back." });
return { result: _newDummyResult(observer, "ROLLBACK", {}), state: _states.FAILED };
},
run: function run(connectionHolder, observer, statement, parameters) {
observer.onError({ error: "Cannot run statement, because previous statements in the " + "transaction has failed and the transaction has already been rolled back." });
return _newDummyResult(observer, statement, parameters);
}
},
//This transaction has successfully committed
SUCCEEDED: {
commit: function commit(connectionHolder, observer) {
observer.onError({
error: "Cannot commit statements in this transaction, because commit has already been successfully called on the transaction and transaction has been closed. Please start a new" + " transaction to run another statement."
});
return { result: _newDummyResult(observer, "COMMIT", {}), state: _states.SUCCEEDED };
},
rollback: function rollback(connectionHolder, observer) {
observer.onError({ error: "Cannot rollback transaction, because transaction has already been successfully closed." });
return { result: _newDummyResult(observer, "ROLLBACK", {}), state: _states.SUCCEEDED };
},
run: function run(connectionHolder, observer, statement, parameters) {
observer.onError({ error: "Cannot run statement, because transaction has already been successfully closed." });
return _newDummyResult(observer, statement, parameters);
}
},
//This transaction has been rolled back
ROLLED_BACK: {
commit: function commit(connectionHolder, observer) {
observer.onError({
error: "Cannot commit this transaction, because it has already been rolled back."
});
return { result: _newDummyResult(observer, "COMMIT", {}), state: _states.ROLLED_BACK };
},
rollback: function rollback(connectionHolder, observer) {
observer.onError({ error: "Cannot rollback transaction, because transaction has already been rolled back." });
return { result: _newDummyResult(observer, "ROLLBACK", {}), state: _states.ROLLED_BACK };
},
run: function run(connectionHolder, observer, statement, parameters) {
observer.onError({ error: "Cannot run statement, because transaction has already been rolled back." });
return _newDummyResult(observer, statement, parameters);
}
}
};
function _runPullAll(msg, connectionHolder, observer) {
connectionHolder.getConnection(observer).then(function (conn) {
conn.run(msg, {}, observer);
conn.pullAll(observer);
conn.sync();
}).catch(function (error) {
return observer.onError(error);
});
// for commit & rollback we need result that uses real connection holder and notifies it when
// connection is not needed and can be safely released to the pool
return new _result2.default(observer, msg, {}, emptyMetadataSupplier, connectionHolder);
}
/**
* Creates a {@link Result} with empty connection holder.
* Should be used as a result for running cypher statements. They can result in metadata but should not
* influence real connection holder to release connections because single transaction can have
* {@link Transaction#run} called multiple times.
* @param {StreamObserver} observer - an observer for the created result.
* @param {string} statement - the cypher statement that produced the result.
* @param {object} parameters - the parameters for cypher statement that produced the result.
* @param {function} metadataSupplier - the function that returns a metadata object.
* @return {Result} new result.
* @private
*/
function _newRunResult(observer, statement, parameters, metadataSupplier) {
return new _result2.default(observer, statement, parameters, metadataSupplier, _connectionHolder.EMPTY_CONNECTION_HOLDER);
}
/**
* Creates a {@link Result} without metadata supplier and with empty connection holder.
* For cases when result represents an intermediate or failed action, does not require any metadata and does not
* need to influence real connection holder to release connections.
* @param {StreamObserver} observer - an observer for the created result.
* @param {string} statement - the cypher statement that produced the result.
* @param {object} parameters - the parameters for cypher statement that produced the result.
* @return {Result} new result.
* @private
*/
function _newDummyResult(observer, statement, parameters) {
return new _result2.default(observer, statement, parameters, emptyMetadataSupplier, _connectionHolder.EMPTY_CONNECTION_HOLDER);
}
function emptyMetadataSupplier() {
return {};
}
exports.default = Transaction;

32
node_modules/neo4j-driver/lib/version.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// DO NOT CHANGE THE VERSION BELOW HERE
// This is set by the build system at release time, using
// gulp set --version <releaseversion>
//
// This is set up this way to keep the version in the code in
// sync with the npm package version, and to allow the build
// system to control version names at packaging time.
exports.default = "1.6.3";