neo4j-driver
Version:
The official Neo4j driver for Javascript
1,299 lines (1,284 loc) • 1.61 MB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.neo4j = factory());
})(this, (function () { 'use strict';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var lib$2 = {};
var driver$1 = {};
var lib$1 = {};
var error = {};
var json$3 = {};
var objectUtil$2 = {};
Object.defineProperty(objectUtil$2, "__esModule", { value: true });
objectUtil$2.getBrokenObjectReason = objectUtil$2.isBrokenObject = objectUtil$2.createBrokenObject = void 0;
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* 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.
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
var __isBrokenObject__ = '__isBrokenObject__';
// eslint-disable-next-line @typescript-eslint/naming-convention
var __reason__ = '__reason__';
/**
* Creates a object which all method call will throw the given error
*
* @param {Error} error The error
* @param {any} object The object. Default: {}
* @returns {any} A broken object
*/
function createBrokenObject(error, object) {
if (object === void 0) { object = {}; }
var fail = function () {
throw error;
};
return new Proxy(object, {
get: function (_, p) {
if (p === __isBrokenObject__) {
return true;
}
else if (p === __reason__) {
return error;
}
else if (p === 'toJSON') {
return undefined;
}
fail();
},
set: fail,
apply: fail,
construct: fail,
defineProperty: fail,
deleteProperty: fail,
getOwnPropertyDescriptor: fail,
getPrototypeOf: fail,
has: fail,
isExtensible: fail,
ownKeys: fail,
preventExtensions: fail,
setPrototypeOf: fail
});
}
objectUtil$2.createBrokenObject = createBrokenObject;
/**
* Verifies if it is a Broken Object
* @param {any} object The object
* @returns {boolean} If it was created with createBrokenObject
*/
function isBrokenObject(object) {
return object !== null && typeof object === 'object' && object[__isBrokenObject__] === true;
}
objectUtil$2.isBrokenObject = isBrokenObject;
/**
* Returns if the reason the object is broken.
*
* This method should only be called with instances create with {@link createBrokenObject}
*
* @param {any} object The object
* @returns {Error} The reason the object is broken
*/
function getBrokenObjectReason(object) {
return object[__reason__];
}
objectUtil$2.getBrokenObjectReason = getBrokenObjectReason;
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* 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.
*/
Object.defineProperty(json$3, "__esModule", { value: true });
json$3.stringify = void 0;
var object_util_1 = objectUtil$2;
/**
* Custom version on JSON.stringify that can handle values that normally don't support serialization, such as BigInt.
* @private
* @param val A JavaScript value, usually an object or array, to be converted.
* @returns A JSON string representing the given value.
*/
function stringify(val, opts) {
return JSON.stringify(val, function (_, value) {
if ((0, object_util_1.isBrokenObject)(value)) {
return {
__isBrokenObject__: true,
__reason__: (0, object_util_1.getBrokenObjectReason)(value)
};
}
if (typeof value === 'bigint') {
return "".concat(value, "n");
}
if ((opts === null || opts === void 0 ? void 0 : opts.useCustomToString) === true &&
typeof value === 'object' &&
!Array.isArray(value) &&
typeof value.toString === 'function' &&
value.toString !== Object.prototype.toString) {
return value === null || value === void 0 ? void 0 : value.toString();
}
return value;
});
}
json$3.stringify = stringify;
var gqlConstants = {};
(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.rawPolyfilledDiagnosticRecord = void 0;
exports.rawPolyfilledDiagnosticRecord = {
OPERATION: '',
OPERATION_CODE: '0',
CURRENT_SCHEMA: '/'
};
Object.freeze(exports.rawPolyfilledDiagnosticRecord);
}(gqlConstants));
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* 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 __extends$R = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __createBinding$d = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault$d = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar$d = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$d(result, mod, k);
__setModuleDefault$d(result, mod);
return result;
};
Object.defineProperty(error, "__esModule", { value: true });
error.PROTOCOL_ERROR = error.SESSION_EXPIRED = error.SERVICE_UNAVAILABLE = error.GQLError = error.Neo4jError = error.isRetriableError = error.newGQLError = error.newError = void 0;
// A common place for constructing error objects, to keep them
// uniform across the driver surface.
var json$2 = __importStar$d(json$3);
var gql_constants_1$1 = gqlConstants;
/**
* @typedef { 'DATABASE_ERROR' | 'CLIENT_ERROR' | 'TRANSIENT_ERROR' | 'UNKNOWN' } ErrorClassification
* @experimental this is part of the preview of GQL-compliant errors
*/
var errorClassification = {
DATABASE_ERROR: 'DATABASE_ERROR',
CLIENT_ERROR: 'CLIENT_ERROR',
TRANSIENT_ERROR: 'TRANSIENT_ERROR',
UNKNOWN: 'UNKNOWN'
};
Object.freeze(errorClassification);
var classifications = Object.values(errorClassification);
/**
* Error code representing complete loss of service. Used by {@link Neo4jError#code}.
* @type {string}
*/
var SERVICE_UNAVAILABLE$6 = 'ServiceUnavailable';
error.SERVICE_UNAVAILABLE = SERVICE_UNAVAILABLE$6;
/**
* Error code representing transient loss of service. Used by {@link Neo4jError#code}.
* @type {string}
*/
var SESSION_EXPIRED$2 = 'SessionExpired';
error.SESSION_EXPIRED = SESSION_EXPIRED$2;
/**
* Error code representing serialization/deserialization issue in the Bolt protocol. Used by {@link Neo4jError#code}.
* @type {string}
*/
var PROTOCOL_ERROR$6 = 'ProtocolError';
error.PROTOCOL_ERROR = PROTOCOL_ERROR$6;
/**
* Error code representing an no classified error. Used by {@link Neo4jError#code}.
* @type {string}
*/
var NOT_AVAILABLE$1 = 'N/A';
/// TODO: Remove definitions of this.constructor and this.__proto__
/**
* Class for nested errors, to be used as causes in {@link Neo4jError}
* @experimental this class is part of the preview of GQL-compliant errors
*/
var GQLError = /** @class */ (function (_super) {
__extends$R(GQLError, _super);
/**
* @constructor
* @param {string} message - the error message
* @param {string} gqlStatus - the GQL status code of the error
* @param {string} gqlStatusDescription - the GQL status description of the error
* @param {ErrorDiagnosticRecord} diagnosticRecord - the error diagnostic record
* @param {Error} cause - Optional nested error, the cause of the error
*/
function GQLError(message, gqlStatus, gqlStatusDescription, diagnosticRecord, cause) {
var _this = this;
var _a;
// eslint-disable-next-line
// @ts-ignore: not available in ES6 yet
_this = _super.call(this, message, cause != null ? { cause: cause } : undefined) || this;
_this.constructor = GQLError;
// eslint-disable-next-line no-proto
_this.__proto__ = GQLError.prototype;
/**
* Optional, nested error which caused the error
*
* @type {Error?}
* @public
*/
_this.cause = cause != null ? cause : undefined;
/**
* The GQL Status code
*
* @type {string}
* @experimental this property is part of the preview of GQL-compliant errors
* @public
*/
_this.gqlStatus = gqlStatus;
/**
* The GQL Status Description
*
* @type {string}
* @experimental this property is part of the preview of GQL-compliant errors
* @public
*/
_this.gqlStatusDescription = gqlStatusDescription;
/**
* The GQL diagnostic record
*
* @type {DiagnosticRecord}
* @experimental this property is part of the preview of GQL-compliant errors
* @public
*/
_this.diagnosticRecord = diagnosticRecord;
/**
* The GQL error classification, extracted from the diagnostic record
*
* @type {ErrorClassification}
* @experimental this property is part of the preview of GQL-compliant errors
* @public
*/
_this.classification = _extractClassification(_this.diagnosticRecord);
/**
* The GQL error classification, extracted from the diagnostic record as a raw string
*
* @type {string}
* @experimental this property is part of the preview of GQL-compliant errors
* @public
*/
_this.rawClassification = (_a = diagnosticRecord === null || diagnosticRecord === void 0 ? void 0 : diagnosticRecord._classification) !== null && _a !== void 0 ? _a : undefined;
_this.name = 'GQLError';
return _this;
}
Object.defineProperty(GQLError.prototype, "diagnosticRecordAsJsonString", {
/**
* The json string representation of the diagnostic record.
* The goal of this method is provide a serialized object for human inspection.
*
* @type {string}
* @experimental this is part of the preview of GQL-compliant errors
* @public
*/
get: function () {
return json$2.stringify(this.diagnosticRecord, { useCustomToString: true });
},
enumerable: false,
configurable: true
});
return GQLError;
}(Error));
error.GQLError = GQLError;
/**
* Class for all errors thrown/returned by the driver.
*/
var Neo4jError = /** @class */ (function (_super) {
__extends$R(Neo4jError, _super);
/**
* @constructor
* @param {string} message - the error message
* @param {string} code - Optional error code. Will be populated when error originates in the database.
* @param {string} gqlStatus - the GQL status code of the error
* @param {string} gqlStatusDescription - the GQL status description of the error
* @param {DiagnosticRecord} diagnosticRecord - the error diagnostic record
* @param {Error} cause - Optional nested error, the cause of the error
*/
function Neo4jError(message, code, gqlStatus, gqlStatusDescription, diagnosticRecord, cause) {
var _this = _super.call(this, message, gqlStatus, gqlStatusDescription, diagnosticRecord, cause) || this;
_this.constructor = Neo4jError;
// eslint-disable-next-line no-proto
_this.__proto__ = Neo4jError.prototype;
/**
* The Neo4j Error code
*
* @type {string}
* @public
*/
_this.code = code;
_this.name = 'Neo4jError';
_this.retriable = _isRetriableCode(code);
return _this;
}
/**
* Verifies if the given error is retriable.
*
* @param {object|undefined|null} error the error object
* @returns {boolean} true if the error is retriable
*/
Neo4jError.isRetriable = function (error) {
return error !== null &&
error !== undefined &&
error instanceof Neo4jError &&
error.retriable;
};
return Neo4jError;
}(GQLError));
error.Neo4jError = Neo4jError;
/**
* Create a new error from a message and optional data
* @param message the error message
* @param {Neo4jErrorCode} [code] the error code
* @param {Neo4jError} [cause]
* @param {String} [gqlStatus]
* @param {String} [gqlStatusDescription]
* @param {DiagnosticRecord} diagnosticRecord - the error message
* @return {Neo4jError} an {@link Neo4jError}
* @private
*/
function newError(message, code, cause, gqlStatus, gqlStatusDescription, diagnosticRecord) {
return new Neo4jError(message, code !== null && code !== void 0 ? code : NOT_AVAILABLE$1, gqlStatus !== null && gqlStatus !== void 0 ? gqlStatus : '50N42', gqlStatusDescription !== null && gqlStatusDescription !== void 0 ? gqlStatusDescription : 'error: general processing exception - unexpected error. ' + message, diagnosticRecord !== null && diagnosticRecord !== void 0 ? diagnosticRecord : gql_constants_1$1.rawPolyfilledDiagnosticRecord, cause);
}
error.newError = newError;
/**
* Create a new GQL error from a message and optional data
* @param message the error message
* @param {Neo4jError} [cause]
* @param {String} [gqlStatus]
* @param {String} [gqlStatusDescription]
* @param {DiagnosticRecord} diagnosticRecord - the error message
* @return {Neo4jError} an {@link Neo4jError}
* @experimental this is part of the preview of GQL-compliant errors
* @private
*/
function newGQLError(message, cause, gqlStatus, gqlStatusDescription, diagnosticRecord) {
return new GQLError(message, gqlStatus !== null && gqlStatus !== void 0 ? gqlStatus : '50N42', gqlStatusDescription !== null && gqlStatusDescription !== void 0 ? gqlStatusDescription : 'error: general processing exception - unexpected error. ' + message, diagnosticRecord !== null && diagnosticRecord !== void 0 ? diagnosticRecord : gql_constants_1$1.rawPolyfilledDiagnosticRecord, cause);
}
error.newGQLError = newGQLError;
/**
* Verifies if the given error is retriable.
*
* @public
* @param {object|undefined|null} error the error object
* @returns {boolean} true if the error is retriable
*/
var isRetriableError = Neo4jError.isRetriable;
error.isRetriableError = isRetriableError;
/**
* @private
* @param {string} code the error code
* @returns {boolean} true if the error is a retriable error
*/
function _isRetriableCode(code) {
return code === SERVICE_UNAVAILABLE$6 ||
code === SESSION_EXPIRED$2 ||
_isAuthorizationExpired(code) ||
_isTransientError(code);
}
/**
* @private
* @param {string} code the error to check
* @return {boolean} true if the error is a transient error
*/
function _isTransientError(code) {
return (code === null || code === void 0 ? void 0 : code.includes('TransientError')) === true;
}
/**
* @private
* @param {string} code the error to check
* @returns {boolean} true if the error is a service unavailable error
*/
function _isAuthorizationExpired(code) {
return code === 'Neo.ClientError.Security.AuthorizationExpired';
}
/**
* extracts a typed classification from the diagnostic record.
*/
function _extractClassification(diagnosticRecord) {
if (diagnosticRecord === undefined || diagnosticRecord._classification === undefined) {
return 'UNKNOWN';
}
return classifications.includes(diagnosticRecord._classification) ? diagnosticRecord === null || diagnosticRecord === void 0 ? void 0 : diagnosticRecord._classification : 'UNKNOWN';
}
var integer = {};
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* 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.
*/
Object.defineProperty(integer, "__esModule", { value: true });
integer.toString = integer.toNumber = integer.inSafeRange = integer.isInt = integer.int = void 0;
// 64-bit Integer library, originally from Long.js by dcodeIO
// https://github.com/dcodeIO/Long.js
// License Apache 2
var error_1$c = error;
/**
* A cache of the Integer representations of small integer values.
* @type {!Object}
* @inner
* @private
*/
// eslint-disable-next-line no-use-before-define
var INT_CACHE = new Map();
/**
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
* See exported functions for more convenient ways of operating integers.
* Use `int()` function to create new integers, `isInt()` to check if given object is integer,
* `inSafeRange()` to check if it is safe to convert given value to native number,
* `toNumber()` and `toString()` to convert given integer to number or string respectively.
* @access public
* @exports Integer
* @class A Integer class for representing a 64 bit two's-complement integer value.
* @param {number} low The low (signed) 32 bits of the long
* @param {number} high The high (signed) 32 bits of the long
*
* @constructor
*/
var Integer = /** @class */ (function () {
function Integer(low, high) {
/**
* The low 32 bits as a signed value.
* @type {number}
* @expose
*/
this.low = low !== null && low !== void 0 ? low : 0;
/**
* The high 32 bits as a signed value.
* @type {number}
* @expose
*/
this.high = high !== null && high !== void 0 ? high : 0;
}
// The internal representation of an Integer is the two given signed, 32-bit values.
// We use 32-bit pieces because these are the size of integers on which
// JavaScript performs bit-operations. For operations like addition and
// multiplication, we split each number into 16 bit pieces, which can easily be
// multiplied within JavaScript's floating-point representation without overflow
// or change in sign.
//
// In the algorithms below, we frequently reduce the negative case to the
// positive case by negating the input(s) and then post-processing the result.
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
// a positive number, it overflows back into a negative). Not handling this
// case would often result in infinite recursion.
//
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
// methods on which they depend.
Integer.prototype.inSafeRange = function () {
return (this.greaterThanOrEqual(Integer.MIN_SAFE_VALUE) &&
this.lessThanOrEqual(Integer.MAX_SAFE_VALUE));
};
/**
* Converts the Integer to an exact javascript Number, assuming it is a 32 bit integer.
* @returns {number}
* @expose
*/
Integer.prototype.toInt = function () {
return this.low;
};
/**
* Converts the Integer to a the nearest floating-point representation of this value (double, 53 bit mantissa).
* @returns {number}
* @expose
*/
Integer.prototype.toNumber = function () {
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};
/**
* Converts the Integer to a BigInt representation of this value
* @returns {bigint}
* @expose
*/
Integer.prototype.toBigInt = function () {
if (this.isZero()) {
return BigInt(0);
}
else if (this.isPositive()) {
return (BigInt(this.high >>> 0) * BigInt(TWO_PWR_32_DBL) +
BigInt(this.low >>> 0));
}
else {
var negate = this.negate();
return (BigInt(-1) *
(BigInt(negate.high >>> 0) * BigInt(TWO_PWR_32_DBL) +
BigInt(negate.low >>> 0)));
}
};
/**
* Converts the Integer to native number or -Infinity/+Infinity when it does not fit.
* @return {number}
* @package
*/
Integer.prototype.toNumberOrInfinity = function () {
if (this.lessThan(Integer.MIN_SAFE_VALUE)) {
return Number.NEGATIVE_INFINITY;
}
else if (this.greaterThan(Integer.MAX_SAFE_VALUE)) {
return Number.POSITIVE_INFINITY;
}
else {
return this.toNumber();
}
};
/**
* Converts the Integer to a string written in the specified radix.
* @param {number=} radix Radix (2-36), defaults to 10
* @returns {string}
* @override
* @throws {RangeError} If `radix` is out of range
* @expose
*/
Integer.prototype.toString = function (radix) {
radix = radix !== null && radix !== void 0 ? radix : 10;
if (radix < 2 || radix > 36) {
throw RangeError('radix out of range: ' + radix.toString());
}
if (this.isZero()) {
return '0';
}
var rem;
if (this.isNegative()) {
if (this.equals(Integer.MIN_VALUE)) {
// We need to change the Integer value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixInteger = Integer.fromNumber(radix);
var div = this.div(radixInteger);
rem = div.multiply(radixInteger).subtract(this);
return div.toString(radix) + rem.toInt().toString(radix);
}
else {
return '-' + this.negate().toString(radix);
}
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Integer.fromNumber(Math.pow(radix, 6));
// eslint-disable-next-line @typescript-eslint/no-this-alias
rem = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower);
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;
var digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
}
else {
while (digits.length < 6) {
digits = '0' + digits;
}
result = '' + digits + result;
}
}
};
/**
* Converts the Integer to it primitive value.
*
* @since 5.4.0
* @returns {bigint}
*
* @see {@link Integer#toBigInt}
* @see {@link Integer#toInt}
* @see {@link Integer#toNumber}
* @see {@link Integer#toString}
*/
Integer.prototype.valueOf = function () {
return this.toBigInt();
};
/**
* Gets the high 32 bits as a signed integer.
* @returns {number} Signed high bits
* @expose
*/
Integer.prototype.getHighBits = function () {
return this.high;
};
/**
* Gets the low 32 bits as a signed integer.
* @returns {number} Signed low bits
* @expose
*/
Integer.prototype.getLowBits = function () {
return this.low;
};
/**
* Gets the number of bits needed to represent the absolute value of this Integer.
* @returns {number}
* @expose
*/
Integer.prototype.getNumBitsAbs = function () {
if (this.isNegative()) {
return this.equals(Integer.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs();
}
var val = this.high !== 0 ? this.high : this.low;
var bit = 0;
for (bit = 31; bit > 0; bit--) {
if ((val & (1 << bit)) !== 0) {
break;
}
}
return this.high !== 0 ? bit + 33 : bit + 1;
};
/**
* Tests if this Integer's value equals zero.
* @returns {boolean}
* @expose
*/
Integer.prototype.isZero = function () {
return this.high === 0 && this.low === 0;
};
/**
* Tests if this Integer's value is negative.
* @returns {boolean}
* @expose
*/
Integer.prototype.isNegative = function () {
return this.high < 0;
};
/**
* Tests if this Integer's value is positive.
* @returns {boolean}
* @expose
*/
Integer.prototype.isPositive = function () {
return this.high >= 0;
};
/**
* Tests if this Integer's value is odd.
* @returns {boolean}
* @expose
*/
Integer.prototype.isOdd = function () {
return (this.low & 1) === 1;
};
/**
* Tests if this Integer's value is even.
* @returns {boolean}
* @expose
*/
Integer.prototype.isEven = function () {
return (this.low & 1) === 0;
};
/**
* Tests if this Integer's value equals the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
Integer.prototype.equals = function (other) {
var theOther = Integer.fromValue(other);
return this.high === theOther.high && this.low === theOther.low;
};
/**
* Tests if this Integer's value differs from the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
Integer.prototype.notEquals = function (other) {
return !this.equals(/* validates */ other);
};
/**
* Tests if this Integer's value is less than the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
Integer.prototype.lessThan = function (other) {
return this.compare(/* validates */ other) < 0;
};
/**
* Tests if this Integer's value is less than or equal the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
Integer.prototype.lessThanOrEqual = function (other) {
return this.compare(/* validates */ other) <= 0;
};
/**
* Tests if this Integer's value is greater than the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
Integer.prototype.greaterThan = function (other) {
return this.compare(/* validates */ other) > 0;
};
/**
* Tests if this Integer's value is greater than or equal the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
Integer.prototype.greaterThanOrEqual = function (other) {
return this.compare(/* validates */ other) >= 0;
};
/**
* Compares this Integer's value with the specified's.
* @param {!Integer|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
* @expose
*/
Integer.prototype.compare = function (other) {
var theOther = Integer.fromValue(other);
if (this.equals(theOther)) {
return 0;
}
var thisNeg = this.isNegative();
var otherNeg = theOther.isNegative();
if (thisNeg && !otherNeg) {
return -1;
}
if (!thisNeg && otherNeg) {
return 1;
}
// At this point the sign bits are the same
return this.subtract(theOther).isNegative() ? -1 : 1;
};
/**
* Negates this Integer's value.
* @returns {!Integer} Negated Integer
* @expose
*/
Integer.prototype.negate = function () {
if (this.equals(Integer.MIN_VALUE)) {
return Integer.MIN_VALUE;
}
return this.not().add(Integer.ONE);
};
/**
* Returns the sum of this and the specified Integer.
* @param {!Integer|number|string} addend Addend
* @returns {!Integer} Sum
* @expose
*/
Integer.prototype.add = function (addend) {
var theAddend = Integer.fromValue(addend);
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high >>> 16;
var a32 = this.high & 0xffff;
var a16 = this.low >>> 16;
var a00 = this.low & 0xffff;
var b48 = theAddend.high >>> 16;
var b32 = theAddend.high & 0xffff;
var b16 = theAddend.low >>> 16;
var b00 = theAddend.low & 0xffff;
var c48 = 0;
var c32 = 0;
var c16 = 0;
var c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xffff;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xffff;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xffff;
c48 += a48 + b48;
c48 &= 0xffff;
return Integer.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns the difference of this and the specified Integer.
* @param {!Integer|number|string} subtrahend Subtrahend
* @returns {!Integer} Difference
* @expose
*/
Integer.prototype.subtract = function (subtrahend) {
var theSubtrahend = Integer.fromValue(subtrahend);
return this.add(theSubtrahend.negate());
};
/**
* Returns the product of this and the specified Integer.
* @param {!Integer|number|string} multiplier Multiplier
* @returns {!Integer} Product
* @expose
*/
Integer.prototype.multiply = function (multiplier) {
if (this.isZero()) {
return Integer.ZERO;
}
var theMultiplier = Integer.fromValue(multiplier);
if (theMultiplier.isZero()) {
return Integer.ZERO;
}
if (this.equals(Integer.MIN_VALUE)) {
return theMultiplier.isOdd() ? Integer.MIN_VALUE : Integer.ZERO;
}
if (theMultiplier.equals(Integer.MIN_VALUE)) {
return this.isOdd() ? Integer.MIN_VALUE : Integer.ZERO;
}
if (this.isNegative()) {
if (theMultiplier.isNegative()) {
return this.negate().multiply(theMultiplier.negate());
}
else {
return this.negate()
.multiply(theMultiplier)
.negate();
}
}
else if (theMultiplier.isNegative()) {
return this.multiply(theMultiplier.negate()).negate();
}
// If both longs are small, use float multiplication
if (this.lessThan(TWO_PWR_24) && theMultiplier.lessThan(TWO_PWR_24)) {
return Integer.fromNumber(this.toNumber() * theMultiplier.toNumber());
}
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high >>> 16;
var a32 = this.high & 0xffff;
var a16 = this.low >>> 16;
var a00 = this.low & 0xffff;
var b48 = theMultiplier.high >>> 16;
var b32 = theMultiplier.high & 0xffff;
var b16 = theMultiplier.low >>> 16;
var b00 = theMultiplier.low & 0xffff;
var c48 = 0;
var c32 = 0;
var c16 = 0;
var c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xffff;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xffff;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xffff;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xffff;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xffff;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xffff;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xffff;
return Integer.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
};
/**
* Returns this Integer divided by the specified.
* @param {!Integer|number|string} divisor Divisor
* @returns {!Integer} Quotient
* @expose
*/
Integer.prototype.div = function (divisor) {
var theDivisor = Integer.fromValue(divisor);
if (theDivisor.isZero()) {
throw (0, error_1$c.newError)('division by zero');
}
if (this.isZero()) {
return Integer.ZERO;
}
var approx, rem, res;
if (this.equals(Integer.MIN_VALUE)) {
if (theDivisor.equals(Integer.ONE) ||
theDivisor.equals(Integer.NEG_ONE)) {
return Integer.MIN_VALUE;
}
if (theDivisor.equals(Integer.MIN_VALUE)) {
return Integer.ONE;
}
else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shiftRight(1);
approx = halfThis.div(theDivisor).shiftLeft(1);
if (approx.equals(Integer.ZERO)) {
return theDivisor.isNegative() ? Integer.ONE : Integer.NEG_ONE;
}
else {
rem = this.subtract(theDivisor.multiply(approx));
res = approx.add(rem.div(theDivisor));
return res;
}
}
}
else if (theDivisor.equals(Integer.MIN_VALUE)) {
return Integer.ZERO;
}
if (this.isNegative()) {
if (theDivisor.isNegative()) {
return this.negate().div(theDivisor.negate());
}
return this.negate()
.div(theDivisor)
.negate();
}
else if (theDivisor.isNegative()) {
return this.div(theDivisor.negate()).negate();
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
res = Integer.ZERO;
// eslint-disable-next-line @typescript-eslint/no-this-alias
rem = this;
while (rem.greaterThanOrEqual(theDivisor)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
approx = Math.max(1, Math.floor(rem.toNumber() / theDivisor.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
var approxRes = Integer.fromNumber(approx);
var approxRem = approxRes.multiply(theDivisor);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = Integer.fromNumber(approx);
approxRem = approxRes.multiply(theDivisor);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero()) {
approxRes = Integer.ONE;
}
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
};
/**
* Returns this Integer modulo the specified.
* @param {!Integer|number|string} divisor Divisor
* @returns {!Integer} Remainder
* @expose
*/
Integer.prototype.modulo = function (divisor) {
var theDivisor = Integer.fromValue(divisor);
return this.subtract(this.div(theDivisor).multiply(theDivisor));
};
/**
* Returns the bitwise NOT of this Integer.
* @returns {!Integer}
* @expose
*/
Integer.prototype.not = function () {
return Integer.fromBits(~this.low, ~this.high);
};
/**
* Returns the bitwise AND of this Integer and the specified.
* @param {!Integer|number|string} other Other Integer
* @returns {!Integer}
* @expose
*/
Integer.prototype.and = function (other) {
var theOther = Integer.fromValue(other);
return Integer.fromBits(this.low & theOther.low, this.high & theOther.high);
};
/**
* Returns the bitwise OR of this Integer and the specified.
* @param {!Integer|number|string} other Other Integer
* @returns {!Integer}
* @expose
*/
Integer.prototype.or = function (other) {
var theOther = Integer.fromValue(other);
return Integer.fromBits(this.low | theOther.low, this.high | theOther.high);
};
/**
* Returns the bitwise XOR of this Integer and the given one.
* @param {!Integer|number|string} other Other Integer
* @returns {!Integer}
* @expose
*/
Integer.prototype.xor = function (other) {
var theOther = Integer.fromValue(other);
return Integer.fromBits(this.low ^ theOther.low, this.high ^ theOther.high);
};
/**
* Returns this Integer with bits shifted to the left by the given amount.
* @param {number|!Integer} numBits Number of bits
* @returns {!Integer} Shifted Integer
* @expose
*/
Integer.prototype.shiftLeft = function (numBits) {
var bitsCount = Integer.toNumber(numBits);
if ((bitsCount &= 63) === 0) {
return Integer.ZERO;
}
else if (bitsCount < 32) {
return Integer.fromBits(this.low << bitsCount, (this.high << bitsCount) | (this.low >>> (32 - bitsCount)));
}
else {
return Integer.fromBits(0, this.low << (bitsCount - 32));
}
};
/**
* Returns this Integer with bits arithmetically shifted to the right by the given amount.
* @param {number|!Integer} numBits Number of bits
* @returns {!Integer} Shifted Integer
* @expose
*/
Integer.prototype.shiftRight = function (numBits) {
var bitsCount = Integer.toNumber(numBits);
var numBitNum = Integer.toNumber(numBits);
if ((bitsCount &= 63) === 0) {
return Integer.ZERO;
}
else if (numBitNum < 32) {
return Integer.fromBits((this.low >>> bitsCount) | (this.high << (32 - bitsCount)), this.high >> bitsCount);
}
else {
return Integer.fromBits(this.high >> (bitsCount - 32), this.high >= 0 ? 0 : -1);
}
};
/**
* Tests if the specified object is a Integer.
* @access private
* @param {*} obj Object
* @returns {boolean}
* @expose
*/
Integer.isInteger = function (obj) {
return (obj === null || obj === void 0 ? void 0 : obj.__isInteger__) === true;
};
/**
* Returns a Integer representing the given 32 bit integer value.
* @access private
* @param {number} value The 32 bit integer in question
* @returns {!Integer} The corresponding Integer value
* @expose
*/
Integer.fromInt = function (value) {
var cachedObj;
value = value | 0;
if (value >= -128 && value < 128) {
cachedObj = INT_CACHE.get(value);
if (cachedObj != null) {
return cachedObj;
}
}
var obj = new Integer(value, value < 0 ? -1 : 0);
if (value >= -128 && value < 128) {
INT_CACHE.set(value, obj);
}
return obj;
};
/**
* Returns a Integer representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
* assumed to use 32 bits.
* @access private
* @param {number} lowBits The low 32 bits
* @param {number} highBits The high 32 bits
* @returns {!Integer} The corresponding Integer value
* @expose
*/
Integer.fromBits = function (lowBits, highBits) {
return new Integer(lowBits, highBits);
};
/**
* Returns a Integer representing the given value, provided that it is a finite number. Otherwise, zero is returned.
* @access private
* @param {number} value The number in question
* @returns {!Integer} The corresponding Integer value
* @expose
*/
Integer.fromNumber = function (value) {
if (isNaN(value) || !isFinite(value)) {
return Integer.ZERO;
}
if (value <= -TWO_PWR_63_DBL) {
return Integer.MIN_VALUE;
}
if (value + 1 >= TWO_PWR_63_DBL) {
return Integer.MAX_VALUE;
}
if (value < 0) {
return Integer.fromNumber(-value).negate();
}
return new Integer(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0);
};
/**
* Returns a Integer representation of the given string, written using the specified radix.
* @access private
* @param {string} str The textual representation of the Integer
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
* @param {Object} [opts={}] Configuration options
* @param {boolean} [opts.strictStringValidation=false] Enable strict validation generated Integer.
* @returns {!Integer} The corresponding Integer value
* @expose
*/
Integer.fromString = function (str, radix, _a) {
var _b = _a === void 0 ? {} : _a, strictStringValidation = _b.strictStringValidation;
if (str.length === 0) {
throw (0, error_1$c.newError)('number format error: empty string');
}
if (str === 'NaN' ||
str === 'Infinity' ||
str === '+Infinity' ||
str === '-Infinity') {
return Integer.ZERO;
}
radix = radix !== null && radix !== void 0 ? radix : 10;
if (radix < 2 || radix > 36) {
throw (0, error_1$c.newError)('radix out of range: ' + radix.toString());
}
var p;
if ((p = str.indexOf('-')) > 0) {
throw (0, error_1$c.newError)('number format error: interior "-" character: ' + str);
}
else if (p === 0) {
return Integer.fromString(str.substring(1), radix).negate();
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Integer.fromNumber(Math.pow(radix, 8));
var result = Integer.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var valueString = str.substring(i, i + size);
var value = parseInt(valueString, radix);
if (strictStringValidation === true && !_isValidNumberFromString(valueString, value, radix)) {
throw (0, error_1$c.newError)("number format error: \"".concat(valueString, "\" is NaN in radix ").concat(radix, ": ").concat(str));
}
if (size < 8) {
var power = Integer.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(Integer.fromNumber(value));
}
else {
result = result.multiply(radixToPower);
result = result.add(Integer.fromNumber(value));
}
}
return result;
};
/**
* Converts the specified value to a Integer.
* @access private
* @param {!Integer|number|string|bigint|!{low: number, high: number}} val Value
* @param {Object} [opts={}] Configuration options
* @param {boolean} [opts.strictStringValidation=false] Enable strict validation generated Integer.
* @param {boolean} [opts.ceilFloat=false] Enable round up float to the nearest Integer.
* @returns {!Integer}
* @expose
*/
Integer.fromValue = function (val, opts) {
if (opts === void 0) { opts = {}; }
if (val /* is compatible */ instanceof Integer) {
return val;
}
if (typeof val === 'number') {
if (opts.ceilFloat === true) {
val = Math.ceil(val);
}
return Integer.fromNumber(val);
}
if (typeof val === 'string') {
return Integer.fromString(val, undefined, opts);
}
if (typeof val === 'bigint') {
return Integer.fromString(val.toString());
}
// Throws for non-objects, converts non-instanceof Integer:
return new Integer(val.low, val.high);
};
/**
* Converts the specified value to a number.
* @access private
* @param {!Integer|number|string|!{low: number, high: number}} val Value
* @returns {number}
* @expose
*/
Integer.toNumber = function (val) {
switch (typeof val) {
case 'number':
return val;
case 'bigint':
return Number(val);
default:
return Integer.fromValue(val).toNumber();
}
};
/**
* Converts the specified value to a string.
* @access private
* @param {!Integer|number|string|!{low: number, high: number}} val Value
* @param {number} radix optional rad