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.createBrokenObject = createBrokenObject;
objectUtil$2.isBrokenObject = isBrokenObject;
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.
 */
// 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
    });
}
/**
 * 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;
}
/**
 * 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__];
}

/**
 * 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 = stringify;
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.sortedElements) === true &&
            typeof value === 'object' &&
            !Array.isArray(value)) {
            return Object.keys(value).sort().reduce(function (obj, key) {
                // @ts-expect-error: no way to avoid implicit 'any'
                obj[key] = value[key];
                return obj;
            }, {});
        }
        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;
    });
}

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$S = (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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$d(result, mod, k[i]);
        __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 = void 0;
error.newError = newError;
error.newGQLError = newGQLError;
// 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$S(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 _a;
        // eslint-disable-next-line
        // @ts-ignore: not available in ES6 yet
        var _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;
        /**
         * Represents the name for the type of error, inherited from base JavaScript {@link Error}.
         * Will be 'GQLError' for {@link GQLError}s and 'Neo4jError' for {@link Neo4jError}s.
         *
         * @type {string}
         * @public
         */
        _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$S(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;
        /**
         * The name of the type of error.
         *
         * @type {string}
         * @public
         */
        _this.name = 'Neo4jError';
        /**
         * If the error is considered retriable.
         * This does not apply when running auto-commit transactions using {@link Session#run}
         *
         * @type {boolean}
         * @public
         */
        _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);
}
/**
 * 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);
}
/**
 * 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$d = 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$d.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$d.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$d.newError)('radix out of range: ' + radix.toString());
        }
        var p;
        if ((p = str.indexOf('-')) > 0) {
            throw (0, error_1$d.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$d.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 radix for string conversion, defaults to 10
     * @returns {string}
     * @expose
     */
    Integer.toString = function (val, radix) {
        return Integer.fromValue(val).toString(radix);
    };
    /**
     * Checks if the given value is in the safe range in order to be converted to a native number
     * @access private
     * @param {!Integer|number|string|!{low: number, high: number}} val Value
     * @param {number} radix optional radix for string conversion, defaults to 10
     * @returns {boolean}
     * @expose
     */
    Integer.inSafeRange = function (val) {
        return Integer.fromValue(val).inSafeRange();
    };
    /**
     * Signed zero.
     * @type {!Integer}
     * @expose
     */
    Integer.ZERO = Integer.fromInt(0);
    /**
     * Signed one.
     * @type {!Integer}
     * @expose
     */
    Integer.ONE = Integer.fromInt(1);
    /**
     * Signed negative one.
     * @type {!Integer}
     * @expose
     */
    Integer.NEG_ONE = Integer.fromInt(-1);
    /**
     * Maximum signed value.
     * @type {!Integer}
     * @expose
     */
    Integer.MAX_VALUE = Integer.fromBits(0xffffffff | 0, 0x7fffffff | 0);
    /**
     * Minimum signed value.
     * @type {!Integer}
     * @expose
     */
    Integer.MIN_VALUE = Integer.fromBits(0, 0x80000000 | 0);
    /**
     * Minimum safe value.
     * @type {!Integer}
     * @expose
     */
    Integer.MIN_SAFE_VALUE = Integer.fromBits(0x1 | 0, 0xffffffffffe00000 | 0);
    /**
     * Maximum safe value.
     * @type {!Integer}
     * @expose
     */
    Integer.MAX_SAFE_VALUE = Integer.fromBits(0xffffffff | 0, 0x1fffff | 0);
    /**
     * An indicator used to reliably determine if an object is a Integer or not.
     * @type {boolean}
     * @const
     * @expose
     * @private
     */
    Integer.__isInteger__ = true;
    return Integer;
}());
/**
 * @private
 * @param num
 * @param radix
 * @param minSize
 * @returns {string}
 */
function _convertNumberToString(num, radix, minSize) {
    var theNumberString = num.toString(radix);
    var paddingLength = Math.max(minSize - theNumberString.length, 0);
    var padding = '0'.repeat(paddingLength);
    return "".concat(padding).concat(theNumberString);
}
/**
 *
 * @private
 * @param theString
 * @param theNumber
 * @param radix
 * @return {boolean} True if valid
 */
function _isValidNumberFromString(theString, theNumber, radix) {
    return !Number.isNaN(theString) &&
        !Number.isNaN(theNumber) &&
        _convertNumberToString(theNumber, radix, theString.length) === theString.toLowerCase();
}
Object.defineProperty(Integer.prototype, '__isInteger__', {
    value: true,
    enumerable: false,
    configurable: false
});
/**
 * @type {number}
 * @const
 * @inner
 * @private
 */
var TWO_PWR_16_DBL = 1 << 16;
/**
 * @type {number}
 * @const
 * @inner
 * @private
 */
var TWO_PWR_24_DBL = 1 << 24;
/**
 * @type {number}
 * @const
 * @inner
 * @private
 */
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
/**
 * @type {number}
 * @const
 * @inner
 * @private
 */
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
/**
 * @type {number}
 * @const
 * @inner
 * @private
 */
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
/**
 * @type {!Integer}
 * @const
 * @inner
 * @private
 */
var TWO_PWR_24 = Integer.fromInt(TWO_PWR_24_DBL);
/**
 * Cast value to Integer type.
 * @access public
 * @param {Mixed} value - The value to use.
 * @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.
 * @return {Integer} - An object of type Integer.
 */
var int = Integer.fromValue;
integer.int = int;
/**
 * Check if a variable is of Integer type.
 * @access public
 * @param {Mixed} value - The variable to check.
 * @return {Boolean} - Is it of the Integer type?
 */
var isInt = Integer.isInteger;
integer.isInt = isInt;
/**
 * Check if a variable can be safely converted to a number
 * @access public
 * @param {Mixed} value - The variable to check
 * @return {Boolean} - true if it is safe to call toNumber on variable otherwise false
 */
var inSafeRange = Integer.inSafeRange;
integer.inSafeRange = inSafeRange;
/**
 * Converts a variable to a number
 * @access public
 * @param {Mixed} value - The variable to convert
 * @return {number} - the variable as a number
 */
var toNumber$1 = Integer.toNumber;
integer.toNumber = toNumber$1;
/**
 * Converts the integer to a string representation
 * @access public
 * @param {Mixed} value - The variable to convert
 * @param {number} radix - radix to use in string conversion, defaults to 10
 * @return {string} - returns a string representation of the integer
 */
var toString = Integer.toString;
integer.toString = toString;
integer.default = Integer;

var temporalTypes = {};

var temporalUtil$1 = {};

var util$4 = {};

var __createBinding$c = (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$c = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$c = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$c(result, mod, k[i]);
        __setModuleDefault$c(result, mod);
        return result;
    };
})();
var __values$d = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(util$4, "__esModule", { value: true });
util$4.ENCRYPTION_OFF = util$4.ENCRYPTION_ON = void 0;
util$4.isEmptyObjectOrNull = isEmptyObjectOrNull;
util$4.isObject = isObject;
util$4.isString = isString$1;
util$4.assertObject = assertObject;
util$4.assertString = assertString$1;
util$4.assertNumber = assertNumber;
util$4.assertNumberOrInteger = assertNumberOrInteger;
util$4.assertValidDate = assertValidDate;
util$4.toNumber = toNumber;
util$4.validateQueryAndParameters = validateQueryAndParameters;
util$4.equals = equals$1;
/**
 * 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/no-unused-vars
var integer_1$2 = __importStar$c(integer);
var json_1$3 = json$3;
var ENCRYPTION_ON$2 = 'ENCRYPTION_ON';
util$4.ENCRYPTION_ON = ENCRYPTION_ON$2;
var ENCRYPTION_OFF$2 = 'ENCRYPTION_OFF';
util$4.ENCRYPTION_OFF = ENCRYPTION_OFF$2;
/**
 * Verifies if the object is null or empty
 * @param obj The subject object
 * @returns {boolean} True if it's empty object or null
 */
function isEmptyObjectOrNull(obj) {
    if (obj === null) {
        return true;
    }
    if (!isObject(obj)) {
        return false;
    }
    for (var prop in obj) {
        if (obj[prop] !== undefined) {
            return false;
        }
    }
    return true;
}
/**
 * Verify if it's an object
 * @param obj The subject
 * @returns {boolean} True if it's an object
 */
function isObject(obj) {
    return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
}
/**
 * Check and normalize given query and parameters.
 * @param {string|{text: string, parameters: Object}} query the query to check.
 * @param {Object} parameters
 * @return {{validatedQuery: string|{text: string, parameters: Object}, params: Object}} the normalized query with parameters.
 * @throws TypeError when either given query or parameters are invalid.
 */
function validateQueryAndParameters(query, parameters, opt) {
    var _a, _b;
    var validatedQuery = '';
    var params = parameters !== null && parameters !== void 0 ? parameters : {};
    var skipAsserts = (_a = opt === null || opt === void 0 ? void 0 : opt.skipAsserts) !== null && _a !== void 0 ? _a : false;
    if (typeof query === 'string') {
        validatedQuery = query;
    }
    else if (query instanceof String) {
        validatedQuery = query.toString();
    }
    else if (typeof query === 'object' && query.text != null) {
        validatedQuery = query.text;
        params = (_b = query.parameters) !== null && _b !== void 0 ? _b : {};
    }
    if (!skipAsserts) {
        assertCypherQuery(validatedQuery);
        assertQueryParameters(params);
    }
    return { validatedQuery: validatedQuery, params: params };
}
/**
 * Assert it's a object
 * @param {any} obj The subject
 * @param {string} objName The object name
 * @returns {object} The subject object
 * @throws {TypeError} when the supplied param is not an object
 */
function assertObject(obj, objName) {
    if (!isObject(obj)) {
        throw new TypeError(objName + ' expected to be an object but was: ' + (0, json_1$3.stringify)(obj));
    }
    return obj;
}
/**
 * Assert it's a string
 * @param {any} obj The subject
 * @param {string} objName The object name
 * @returns {string} The subject string
 * @throws {TypeError} when the supplied param is not a string
 */
function assertString$1(obj, objName) {
    if (!isString$1(obj)) {
        throw new TypeError((0, json_1$3.stringify)(objName) + ' expected to be string but was: ' + (0, json_1$3.stringify)(obj));
    }
    return obj;
}
/**
 * Assert it's a number
 * @param {any} obj The subject
 * @param {string} objName The object name
 * @returns {number} The number
 * @throws {TypeError} when the supplied param is not a number
 */
function assertNumber(obj, objName) {
    if (typeof obj !== 'number') {
        throw new TypeError(objName + ' expected to be a number but was: ' + (0, json_1$3.stringify)(obj));
    }
    return obj;
}
/**
 * Assert it's a number or integer
 * @param {any} obj The subject
 * @param {string} objName The object name
 * @returns {number|Integer} The subject object
 * @throws {TypeError} when the supplied param is not a number or integer
 */
function assertNumberOrInteger(obj, objName) {
    if (typeof obj !== 'number' && typeof obj !== 'bigint' && !(0, integer_1$2.isInt)(obj)) {
        throw new TypeError(objName +
            ' expected to be either a number or an Integer object but was: ' +
            (0, json_1$3.stringify)(obj));
    }
    return obj;
}
/**
 * Assert it's a valid datae
 * @param {any} obj The subject
 * @param {string} objName The object name
 * @returns {Date} The valida date
 * @throws {TypeError} when the supplied param is not a valid date
 */
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, json_1$3.stringify)(obj));
    }
    if (Number.isNaN(obj.getTime())) {
        throw new TypeError(objName +
            ' expected to be valid JavaScript Date but its time was NaN: ' +
            (0, json_1$3.stringify)(obj));
    }
    return obj;
}
/**
 * Validates a cypher query string
 * @param {any} obj The query
 * @returns {void}
 * @throws {TypeError} if the query is not valid
 */
function assertCypherQuery(obj) {
    assertString$1(obj, 'Cypher query');
    if (obj.trim().length === 0) {
        throw new TypeError('Cypher query is expected to be a non-empty string.');
    }
}
/**
 * Validates if the query parameters is an object
 * @param {any} obj The parameters
 * @returns {void}
 * @throws {TypeError} if the parameters is not valid
 */
function assertQueryParameters(obj) {
    if (!isObject(obj)) {
        // objects created with `Object.create(null)` do not have a constructor property
        // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
        var constructor = obj.constructor != null ? ' ' + obj.constructor.name : '';
        throw new TypeError("Query parameters are expected to either be undefined/null or an object, given:".concat(constructor, " ").concat(JSON.stringify(obj)));
    }
}
/**
 * Verify if the supplied object is a string
 *
 * @param str The string
 * @returns {boolean} True if the supplied object is an string
 */
function isString$1(str) {
    return Object.prototype.toString.call(str) === '[object String]';
}
/**
 * Verifies if object are the equals
 * @param {unknown} a
 * @param {unknown} b
 * @returns {boolean}
 */
function equals$1(a, b) {
    var e_1, _a;
    if (a === b) {
        return true;
    }
    if (a === null || b === null) {
        return false;
    }
    if (typeof a === 'object' && typeof b === 'object') {
        var keysA = Object.keys(a);
        var keysB = Object.keys(b);
        if (keysA.length !== keysB.length) {
            return false;
        }
        try {
            for (var keysA_1 = __values$d(keysA), keysA_1_1 = keysA_1.next(); !keysA_1_1.done; keysA_1_1 = keysA_1.next()) {
                var key = keysA_1_1.value;
                if (!equals$1(a[key], b[key])) {
                    return false;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (keysA_1_1 && !keysA_1_1.done && (_a = keysA_1.return)) _a.call(keysA_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return true;
    }
    return false;
}
/**
 * Converts (Integer | bigint) to number.
 *
 * @private
 * @param {NumberOrInteger} value The number or integer
 * @returns {number} The number
 */
function toNumber(value) {
    if (value instanceof integer_1$2.default) {
        return value.toNumber();
    }
    else if (typeof value === 'bigint') {
        return (0, integer_1$2.int)(value).toNumber();
    }
    else {
        return value;
    }
}

(function (exports) {
/**
 * 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 __createBinding = (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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SECONDS_PER_DAY = exports.DAYS_PER_400_YEAR_CYCLE = exports.DAYS_0000_TO_1970 = exports.NANOS_PER_HOUR = exports.NANOS_PER_MINUTE = exports.NANOS_PER_MILLISECOND = exports.NANOS_PER_SECOND = exports.SECONDS_PER_HOUR = exports.SECONDS_PER_MINUTE = exports.MINUTES_PER_HOUR = exports.NANOSECOND_OF_SECOND_RANGE = exports.SECOND_OF_MINUTE_RANGE = exports.MINUTE_OF_HOUR_RANGE = exports.HOUR_OF_DAY_RANGE = exports.DAY_OF_MONTH_RANGE = exports.MONTH_OF_YEAR_RANGE = exports.YEAR_RANGE = void 0;
exports.normalizeSecondsForDuration = normalizeSecondsForDuration;
exports.normalizeNanosecondsForDuration = normalizeNanosecondsForDuration;
exports.localTimeToNanoOfDay = localTimeToNanoOfDay;
exports.localDateTimeToEpochSecond = localDateTimeToEpochSecond;
exports.dateToEpochDay = dateToEpochDay;
exports.durationToIsoString = durationToIsoString;
exports.timeToIsoString = timeToIsoString;
exports.timeZoneOffsetToIsoString = timeZoneOffsetToIsoString;
exports.dateToIsoString = dateToIsoString;
exports.isoStringToStandardDate = isoStringToStandardDate;
exports.toStandardDate = toStandardDate;
exports.newDate = newDate;
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;
exports.assertValidZoneId = assertValidZoneId;
exports.floorDiv = floorDiv;
exports.floorMod = floorMod;
var integer_1 = __importStar(integer);
var error_1 = error;
var util_1 = util$4;
/*
  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 `Number.MAX_SAFE_INTEGER`.

  Please consult either ThreeTen or js-joda (https://github.com/js-joda/js-joda) when working with the
  conversion functions.
 */
var ValueRange = /** @class */ (function () {
    function ValueRange(min, max) {
        this._minNumber = min;
        this._maxNumber = max;
        this._minInteger = (0, integer_1.int)(min);
        this._maxInteger = (0, integer_1.int)(max);
    }
    ValueRange.prototype.contains = function (value) {
        if ((0, integer_1.isInt)(value) && value instanceof integer_1.default) {
            return (value.greaterThanOrEqual(this._minInteger) &&
                value.lessThanOrEqual(this._maxInteger));
        }
        else if (typeof value === 'bigint') {
            var intValue = (0, integer_1.int)(value);
            return (intValue.greaterThanOrEqual(this._minInteger) &&
                intValue.lessThanOrEqual(this._maxInteger));
        }
        else {
            return value >= this._minNumber && value <= this._maxNumber;
        }
    };
    ValueRange.prototype.toString = function () {
        return "[".concat(this._minNumber, ", ").concat(this._maxNumber, "]");
    };
    return ValueRange;
}());
exports.YEAR_RANGE = new ValueRange(-999999999, 999999999);
exports.MONTH_OF_YEAR_RANGE = new ValueRange(1, 12);
exports.DAY_OF_MONTH_RANGE = new ValueRange(1, 31);
exports.HOUR_OF_DAY_RANGE = new ValueRange(0, 23);
exports.MINUTE_OF_HOUR_RANGE = new ValueRange(0, 59);
exports.SECOND_OF_MINUTE_RANGE = new ValueRange(0, 59);
exports.NANOSECOND_OF_SECOND_RANGE = new ValueRange(0, 999999999);
exports.MINUTES_PER_HOUR = 60;
exports.SECONDS_PER_MINUTE = 60;
exports.SECONDS_PER_HOUR = exports.SECONDS_PER_MINUTE * exports.MINUTES_PER_HOUR;
exports.NANOS_PER_SECOND = 1000000000;
exports.NANOS_PER_MILLISECOND = 1000000;
exports.NANOS_PER_MINUTE = exports.NANOS_PER_SECOND * exports.SECONDS_PER_MINUTE;
exports.NANOS_PER_HOUR = exports.NANOS_PER_MINUTE * exports.MINUTES_PER_HOUR;
exports.DAYS_0000_TO_1970 = 719528;
exports.DAYS_PER_400_YEAR_CYCLE = 146097;
exports.SECONDS_PER_DAY = 86400;
function normalizeSecondsForDuration(seconds, nanoseconds) {
    return (0, integer_1.int)(seconds).add(floorDiv(nanoseconds, exports.NANOS_PER_SECOND));
}
function normalizeNanosecondsForDuration(nanoseconds) {
    return floorMod(nanoseconds, exports.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_1.int)(hour);
    minute = (0, integer_1.int)(minute);
    second = (0, integer_1.int)(second);
    nanosecond = (0, integer_1.int)(nanosecond);
    var totalNanos = hour.multiply(exports.NANOS_PER_HOUR);
    totalNanos = totalNanos.add(minute.multiply(exports.NANOS_PER_MINUTE));
    totalNanos = totalNanos.add(second.multiply(exports.NANOS_PER_SECOND));
    return totalNanos.add(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(exports.SECONDS_PER_DAY).add(localTimeSeconds);
}
/**
 * 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_1.int)(year);
    month = (0, integer_1.int)(month);
    day = (0, integer_1.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(exports.DAYS_0000_TO_1970);
}
/**
 * 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".concat(monthsString, "M").concat(daysString, "DT").concat(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 "".concat(hourString, ":").concat(minuteString, ":").concat(secondString).concat(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_1.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(exports.SECONDS_PER_HOUR), 2);
    var minutes = formatNumber(offsetSeconds.div(exports.SECONDS_PER_MINUTE).modulo(exports.MINUTES_PER_HOUR), 2);
    var secondsValue = offsetSeconds.modulo(exports.SECONDS_PER_MINUTE);
    var seconds = secondsValue.equals(0) ? null : formatNumber(secondsValue, 2);
    return seconds != null
        ? "".concat(signPrefix).concat(hours, ":").concat(minutes, ":").concat(seconds)
        : "".concat(signPrefix).concat(hours, ":").concat(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) {
    var yearString = formatYear(year);
    var monthString = formatNumber(month, 2);
    var dayString = formatNumber(day, 2);
    return "".concat(yearString, "-").concat(monthString, "-").concat(dayString);
}
/**
 * Convert the given iso date string to a JavaScript Date object
 *
 * @param {string} isoString The iso date string
 * @returns {Date} the date
 */
function isoStringToStandardDate(isoString) {
    return new Date(isoString);
}
/**
 * Convert the given utc timestamp to a JavaScript Date object
 *
 * @param {number} utc Timestamp in UTC
 * @returns {Date} the date
 */
function toStandardDate(utc) {
    return new Date(utc);
}
/**
 * Shortcut for creating a new StandardDate
 * @param date
 * @returns {Date} the standard date
 */
function newDate(date) {
    return new Date(date);
}
/**
 * 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|bigint|undefined} nanoseconds the optional number of nanoseconds.
 * @return {Integer|number|bigint} the total amount of nanoseconds.
 */
function totalNanoseconds(standardDate, nanoseconds) {
    nanoseconds = nanoseconds !== null && nanoseconds !== void 0 ? nanoseconds : 0;
    var nanosFromMillis = standardDate.getMilliseconds() * exports.NANOS_PER_MILLISECOND;
    return add(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) {
    var secondsPortion = standardDate.getSeconds() - standardDate.getUTCSeconds();
    var minutesPortion = standardDate.getMinutes() - standardDate.getUTCMinutes();
    var hoursPortion = standardDate.getHours() - standardDate.getUTCHours();
    var daysPortion = _getDayOffset(standardDate);
    return hoursPortion * exports.SECONDS_PER_HOUR + minutesPortion * exports.SECONDS_PER_MINUTE + secondsPortion + daysPortion * exports.SECONDS_PER_DAY;
}
/**
 * Get the difference in days from the given JavaScript date in local time and UTC.
 *
 * @private
 * @param {global.Date} standardDate the date to evaluate
 * @returns  {number} the difference in days between date local time and UTC
 */
function _getDayOffset(standardDate) {
    if (standardDate.getMonth() === standardDate.getUTCMonth()) {
        return standardDate.getDate() - standardDate.getUTCDate();
    }
    else if ((standardDate.getFullYear() > standardDate.getUTCFullYear()) || (standardDate.getMonth() > standardDate.getUTCMonth() && standardDate.getFullYear() === standardDate.getUTCFullYear())) {
        return standardDate.getDate() + _daysUntilNextMonth(standardDate.getUTCMonth(), standardDate.getUTCFullYear()) - standardDate.getUTCDate();
    }
    else {
        return standardDate.getDate() - (standardDate.getUTCDate() + _daysUntilNextMonth(standardDate.getMonth(), standardDate.getFullYear()));
    }
}
/**
 * Get the number of days in a month, including a check for leap years.
 *
 * @private
 * @param {number} month the month of the date to evalutate
 * @param {number} year the month of the date to evalutate
 * @returns {number} the total number of days in the month evaluated
 */
function _daysUntilNextMonth(month, year) {
    if (month === 1) {
        if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
            return 29;
        }
        else {
            return 28;
        }
    }
    else if ([0, 2, 4, 6, 7, 9, 11].includes(month)) {
        return 31;
    }
    else {
        return 30;
    }
}
/**
 * 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, exports.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, exports.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, exports.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, exports.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, exports.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, exports.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, exports.NANOSECOND_OF_SECOND_RANGE, 'Nanosecond');
}
var timeZoneValidityCache = new Map();
var newInvalidZoneIdError = function (zoneId, fieldName) { return (0, error_1.newError)("".concat(fieldName, " is expected to be a valid ZoneId but was: \"").concat(zoneId, "\"")); };
function assertValidZoneId(fieldName, zoneId) {
    var cachedResult = timeZoneValidityCache.get(zoneId);
    if (cachedResult === true) {
        return;
    }
    if (cachedResult === false) {
        throw newInvalidZoneIdError(zoneId, fieldName);
    }
    try {
        Intl.DateTimeFormat(undefined, { timeZone: zoneId });
        timeZoneValidityCache.set(zoneId, true);
    }
    catch (e) {
        timeZoneValidityCache.set(zoneId, false);
        throw newInvalidZoneIdError(zoneId, fieldName);
    }
}
/**
 * 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_1.assertNumberOrInteger)(value, name);
    if (!range.contains(value)) {
        throw (0, error_1.newError)("".concat(name, " is expected to be in range ").concat(range.toString(), " but was: ").concat(value.toString()));
    }
    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_1.int)(hour);
    minute = (0, integer_1.int)(minute);
    second = (0, integer_1.int)(second);
    var totalSeconds = hour.multiply(exports.SECONDS_PER_HOUR);
    totalSeconds = totalSeconds.add(minute.multiply(exports.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} `true` if given year is a leap year, `false` otherwise.
 */
function isLeapYear(year) {
    year = (0, integer_1.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_1.int)(x);
    y = (0, integer_1.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_1.int)(x);
    y = (0, integer_1.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_1.int)(seconds);
    nanoseconds = (0, integer_1.int)(nanoseconds);
    var secondsString;
    var nanosecondsString;
    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 * exports.NANOS_PER_SECOND)
                .modulo(exports.NANOS_PER_SECOND));
        }
        else {
            nanosecondsString = formatNanosecond(nanoseconds.add(exports.NANOS_PER_SECOND).modulo(exports.NANOS_PER_SECOND));
        }
    }
    return nanosecondsString != null ? 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_1.int)(value);
    return value.equals(0) ? '' : '.' + formatNumber(value, 9);
}
/**
 *
 * @param {Integer|number|string} year The year to be formatted
 * @return {string} formatted year
 */
function formatYear(year) {
    var yearInteger = (0, integer_1.int)(year);
    if (yearInteger.isNegative() || yearInteger.greaterThan(9999)) {
        return formatNumber(yearInteger, 6, { usePositiveSign: true });
    }
    return formatNumber(yearInteger, 4);
}
/**
 * @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, stringLength, params) {
    num = (0, integer_1.int)(num);
    var isNegative = num.isNegative();
    if (isNegative) {
        num = num.negate();
    }
    var numString = num.toString();
    if (stringLength != null) {
        // left pad the string with zeroes
        while (numString.length < stringLength) {
            numString = '0' + numString;
        }
    }
    if (isNegative) {
        return '-' + numString;
    }
    else if ((params === null || params === void 0 ? void 0 : params.usePositiveSign) === true) {
        return '+' + numString;
    }
    return numString;
}
function add(x, y) {
    if (x instanceof integer_1.default) {
        return x.add(y);
    }
    else if (typeof x === 'bigint') {
        return x + BigInt(y);
    }
    return x + y;
}
}(temporalUtil$1));

/**
 * 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 __createBinding$b = (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$b = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$b = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$b(result, mod, k[i]);
        __setModuleDefault$b(result, mod);
        return result;
    };
})();
var __read$x = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(temporalTypes, "__esModule", { value: true });
temporalTypes.DateTime = temporalTypes.LocalDateTime = temporalTypes.Date = temporalTypes.Time = temporalTypes.LocalTime = temporalTypes.Duration = void 0;
temporalTypes.isDuration = isDuration;
temporalTypes.isLocalTime = isLocalTime;
temporalTypes.isTime = isTime;
temporalTypes.isDate = isDate$1;
temporalTypes.isLocalDateTime = isLocalDateTime;
temporalTypes.isDateTime = isDateTime;
var util$3 = __importStar$b(temporalUtil$1);
var util_1$7 = util$4;
var error_1$c = error;
var integer_1$1 = __importStar$b(integer);
var IDENTIFIER_PROPERTY_ATTRIBUTES$1 = {
    value: true,
    enumerable: false,
    configurable: false,
    writable: false
};
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 `Duration` objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var Duration = /** @class */ (function () {
    /**
     * @constructor
     * @param {NumberOrInteger} months - The number of months for the new duration.
     * @param {NumberOrInteger} days - The number of days for the new duration.
     * @param {NumberOrInteger} seconds - The number of seconds for the new duration.
     * @param {NumberOrInteger} nanoseconds - The number of nanoseconds for the new duration.
     */
    function Duration(months, days, seconds, nanoseconds) {
        /**
         * The number of months.
         * @type {NumberOrInteger}
         */
        this.months = (0, util_1$7.assertNumberOrInteger)(months, 'Months');
        /**
         * The number of days.
         * @type {NumberOrInteger}
         */
        this.days = (0, util_1$7.assertNumberOrInteger)(days, 'Days');
        (0, util_1$7.assertNumberOrInteger)(seconds, 'Seconds');
        (0, util_1$7.assertNumberOrInteger)(nanoseconds, 'Nanoseconds');
        /**
         * The number of seconds.
         * @type {NumberOrInteger}
         */
        this.seconds = util$3.normalizeSecondsForDuration(seconds, nanoseconds);
        /**
         * The number of nanoseconds.
         * @type {NumberOrInteger}
         */
        this.nanoseconds = util$3.normalizeNanosecondsForDuration(nanoseconds);
        Object.freeze(this);
    }
    /**
     * @ignore
     */
    Duration.prototype.toString = function () {
        return util$3.durationToIsoString(this.months, this.days, this.seconds, this.nanoseconds);
    };
    return Duration;
}());
temporalTypes.Duration = Duration;
Object.defineProperty(Duration.prototype, DURATION_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES$1);
/**
 * Test if given object is an instance of {@link Duration} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link Duration}, `false` otherwise.
 */
function isDuration(obj) {
    return hasIdentifierProperty$1(obj, DURATION_IDENTIFIER_PROPERTY);
}
/**
 * Represents an instant capturing the time of day, but not the date, nor the timezone.
 * Created {@link LocalTime} objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var LocalTime = /** @class */ (function () {
    /**
     * @constructor
     * @param {NumberOrInteger} hour - The hour for the new local time.
     * @param {NumberOrInteger} minute - The minute for the new local time.
     * @param {NumberOrInteger} second - The second for the new local time.
     * @param {NumberOrInteger} nanosecond - The nanosecond for the new local time.
     */
    function LocalTime(hour, minute, second, nanosecond) {
        /**
         * The hour.
         * @type {NumberOrInteger}
         */
        this.hour = util$3.assertValidHour(hour);
        /**
         * The minute.
         * @type {NumberOrInteger}
         */
        this.minute = util$3.assertValidMinute(minute);
        /**
         * The second.
         * @type {NumberOrInteger}
         */
        this.second = util$3.assertValidSecond(second);
        /**
         * The nanosecond.
         * @type {NumberOrInteger}
         */
        this.nanosecond = util$3.assertValidNanosecond(nanosecond);
        Object.freeze(this);
    }
    /**
     * Create a {@link LocalTime} object from the given standard JavaScript `Date` 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 {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds.
     * @return {LocalTime<number>} New LocalTime.
     */
    LocalTime.fromStandardDate = function (standardDate, nanosecond) {
        verifyStandardDateAndNanos(standardDate, nanosecond);
        var totalNanoseconds = util$3.totalNanoseconds(standardDate, nanosecond);
        return new LocalTime(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), totalNanoseconds instanceof integer_1$1.default
            ? totalNanoseconds.toInt()
            : typeof totalNanoseconds === 'bigint'
                ? (0, integer_1$1.int)(totalNanoseconds).toInt()
                : totalNanoseconds);
    };
    /**
     * @ignore
     */
    LocalTime.prototype.toString = function () {
        return util$3.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond);
    };
    return LocalTime;
}());
temporalTypes.LocalTime = LocalTime;
Object.defineProperty(LocalTime.prototype, LOCAL_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES$1);
/**
 * Test if given object is an instance of {@link LocalTime} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link LocalTime}, `false` otherwise.
 */
function isLocalTime(obj) {
    return hasIdentifierProperty$1(obj, LOCAL_TIME_IDENTIFIER_PROPERTY);
}
/**
 * Represents an instant capturing the time of day, and the timezone offset in seconds, but not the date.
 * Created {@link Time} objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var Time = /** @class */ (function () {
    /**
     * @constructor
     * @param {NumberOrInteger} hour - The hour for the new local time.
     * @param {NumberOrInteger} minute - The minute for the new local time.
     * @param {NumberOrInteger} second - The second for the new local time.
     * @param {NumberOrInteger} nanosecond - The nanosecond for the new local time.
     * @param {NumberOrInteger} timeZoneOffsetSeconds - The time zone offset in seconds. Value represents the difference, in seconds, from UTC to local time.
     * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC.
     */
    function Time(hour, minute, second, nanosecond, timeZoneOffsetSeconds) {
        /**
         * The hour.
         * @type {NumberOrInteger}
         */
        this.hour = util$3.assertValidHour(hour);
        /**
         * The minute.
         * @type {NumberOrInteger}
         */
        this.minute = util$3.assertValidMinute(minute);
        /**
         * The second.
         * @type {NumberOrInteger}
         */
        this.second = util$3.assertValidSecond(second);
        /**
         * The nanosecond.
         * @type {NumberOrInteger}
         */
        this.nanosecond = util$3.assertValidNanosecond(nanosecond);
        /**
         * The time zone offset in seconds.
         * @type {NumberOrInteger}
         */
        this.timeZoneOffsetSeconds = (0, util_1$7.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds');
        Object.freeze(this);
    }
    /**
     * Create a {@link Time} object from the given standard JavaScript `Date` 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 {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds.
     * @return {Time<number>} New Time.
     */
    Time.fromStandardDate = function (standardDate, nanosecond) {
        verifyStandardDateAndNanos(standardDate, nanosecond);
        return new Time(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), (0, integer_1$1.toNumber)(util$3.totalNanoseconds(standardDate, nanosecond)), util$3.timeZoneOffsetInSeconds(standardDate));
    };
    /**
     * @ignore
     */
    Time.prototype.toString = function () {
        return (util$3.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond) + util$3.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds));
    };
    return Time;
}());
temporalTypes.Time = Time;
Object.defineProperty(Time.prototype, TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES$1);
/**
 * Test if given object is an instance of {@link Time} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link Time}, `false` otherwise.
 */
function isTime(obj) {
    return hasIdentifierProperty$1(obj, TIME_IDENTIFIER_PROPERTY);
}
/**
 * Represents an instant capturing the date, but not the time, nor the timezone.
 * Created {@link Date} objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var Date$1 = /** @class */ (function () {
    /**
     * @constructor
     * @param {NumberOrInteger} year - The year for the new local date.
     * @param {NumberOrInteger} month - The month for the new local date.
     * @param {NumberOrInteger} day - The day for the new local date.
     */
    function Date(year, month, day) {
        /**
         * The year.
         * @type {NumberOrInteger}
         */
        this.year = util$3.assertValidYear(year);
        /**
         * The month.
         * @type {NumberOrInteger}
         */
        this.month = util$3.assertValidMonth(month);
        /**
         * The day.
         * @type {NumberOrInteger}
         */
        this.day = util$3.assertValidDay(day);
        Object.freeze(this);
    }
    /**
     * Create a {@link Date} object from the given standard JavaScript `Date`.
     * Hour, minute, second, millisecond and time zone offset components of the given date are ignored.
     *
     * NOTE: the function {@link toStandardDate} and {@link fromStandardDate} are not inverses of one another. {@link fromStandardDate} takes the Day, Month and Year in local time from the supplies JavaScript Date object, while {@link toStandardDate} creates a new JavaScript Date object at midnight UTC. This incongruity will be rectified in 6.0
     * If your timezone has a negative offset from UTC, creating a JavaScript Date at midnight UTC and converting it with {@link fromStandardDate} will result in a Date for the day before.
     *
     * @param {global.Date} standardDate - The standard JavaScript date to convert.
     * @return {Date} New Date.
     */
    Date.fromStandardDate = function (standardDate) {
        verifyStandardDateAndNanos(standardDate);
        return new Date(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate());
    };
    /**
     * Convert date to standard JavaScript `Date`.
     *
     * The time component of the returned `Date` is set to midnight
     * and the time zone is set to UTC.
     *
     * NOTE: the function {@link toStandardDate} and {@link fromStandardDate} are not inverses of one another. {@link fromStandardDate} takes the Day, Month and Year in local time from the supplies JavaScript Date object, while {@link toStandardDate} creates a new JavaScript Date object at midnight UTC. This incongruity will be rectified in 6.0
     *
     * @returns {StandardDate} Standard JavaScript `Date` at `00:00:00.000` UTC.
     */
    Date.prototype.toStandardDate = function () {
        return util$3.isoStringToStandardDate(this.toString());
    };
    /**
     * @ignore
     */
    Date.prototype.toString = function () {
        return util$3.dateToIsoString(this.year, this.month, this.day);
    };
    return Date;
}());
temporalTypes.Date = Date$1;
Object.defineProperty(Date$1.prototype, DATE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES$1);
/**
 * Test if given object is an instance of {@link Date} class.
 * @param {Object} obj - The object to test.
 * @return {boolean} `true` if given object is a {@link Date}, `false` otherwise.
 */
function isDate$1(obj) {
    return hasIdentifierProperty$1(obj, DATE_IDENTIFIER_PROPERTY);
}
/**
 * Represents an instant capturing the date and the time, but not the timezone.
 * Created {@link LocalDateTime} objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var LocalDateTime = /** @class */ (function () {
    /**
     * @constructor
     * @param {NumberOrInteger} year - The year for the new local date.
     * @param {NumberOrInteger} month - The month for the new local date.
     * @param {NumberOrInteger} day - The day for the new local date.
     * @param {NumberOrInteger} hour - The hour for the new local time.
     * @param {NumberOrInteger} minute - The minute for the new local time.
     * @param {NumberOrInteger} second - The second for the new local time.
     * @param {NumberOrInteger} nanosecond - The nanosecond for the new local time.
     */
    function LocalDateTime(year, month, day, hour, minute, second, nanosecond) {
        /**
         * The year.
         * @type {NumberOrInteger}
         */
        this.year = util$3.assertValidYear(year);
        /**
         * The month.
         * @type {NumberOrInteger}
         */
        this.month = util$3.assertValidMonth(month);
        /**
         * The day.
         * @type {NumberOrInteger}
         */
        this.day = util$3.assertValidDay(day);
        /**
         * The hour.
         * @type {NumberOrInteger}
         */
        this.hour = util$3.assertValidHour(hour);
        /**
         * The minute.
         * @type {NumberOrInteger}
         */
        this.minute = util$3.assertValidMinute(minute);
        /**
         * The second.
         * @type {NumberOrInteger}
         */
        this.second = util$3.assertValidSecond(second);
        /**
         * The nanosecond.
         * @type {NumberOrInteger}
         */
        this.nanosecond = util$3.assertValidNanosecond(nanosecond);
        Object.freeze(this);
    }
    /**
     * Create a {@link LocalDateTime} object from the given standard JavaScript `Date` and optional nanoseconds.
     * Time zone offset component of the given date is ignored.
     * @param {global.Date} standardDate - The standard JavaScript date to convert.
     * @param {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds.
     * @return {LocalDateTime} New LocalDateTime.
     */
    LocalDateTime.fromStandardDate = function (standardDate, nanosecond) {
        verifyStandardDateAndNanos(standardDate, nanosecond);
        return new LocalDateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), (0, integer_1$1.toNumber)(util$3.totalNanoseconds(standardDate, nanosecond)));
    };
    /**
     * Convert date to standard JavaScript `Date`.
     *
     * @returns {StandardDate} Standard JavaScript `Date` at the local timezone
     */
    LocalDateTime.prototype.toStandardDate = function () {
        return util$3.isoStringToStandardDate(this.toString());
    };
    /**
     * @ignore
     */
    LocalDateTime.prototype.toString = function () {
        return localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond);
    };
    return LocalDateTime;
}());
temporalTypes.LocalDateTime = LocalDateTime;
Object.defineProperty(LocalDateTime.prototype, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES$1);
/**
 * Test if given object is an instance of {@link LocalDateTime} class.
 * @param {Object} obj - The object to test.
 * @return {boolean} `true` if given object is a {@link LocalDateTime}, `false` otherwise.
 */
function isLocalDateTime(obj) {
    return hasIdentifierProperty$1(obj, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY);
}
/**
 * Represents an instant capturing the date, the time and the timezone identifier.
 * Created {@ DateTime} objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var DateTime = /** @class */ (function () {
    /**
     * @constructor
     * @param {NumberOrInteger} year - The year for the new date-time.
     * @param {NumberOrInteger} month - The month for the new date-time.
     * @param {NumberOrInteger} day - The day for the new date-time.
     * @param {NumberOrInteger} hour - The hour for the new date-time.
     * @param {NumberOrInteger} minute - The minute for the new date-time.
     * @param {NumberOrInteger} second - The second for the new date-time.
     * @param {NumberOrInteger} nanosecond - The nanosecond for the new date-time.
     * @param {NumberOrInteger} timeZoneOffsetSeconds - The time zone offset in seconds. Either this argument or `timeZoneId` should be defined.
     * Value represents the difference, in seconds, from UTC to local time.
     * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC.
     * @param {string|null} timeZoneId - The time zone id for the new date-time. Either this argument or `timeZoneOffsetSeconds` should be defined.
     */
    function DateTime(year, month, day, hour, minute, second, nanosecond, timeZoneOffsetSeconds, timeZoneId) {
        /**
         * The year.
         * @type {NumberOrInteger}
         */
        this.year = util$3.assertValidYear(year);
        /**
         * The month.
         * @type {NumberOrInteger}
         */
        this.month = util$3.assertValidMonth(month);
        /**
         * The day.
         * @type {NumberOrInteger}
         */
        this.day = util$3.assertValidDay(day);
        /**
         * The hour.
         * @type {NumberOrInteger}
         */
        this.hour = util$3.assertValidHour(hour);
        /**
         * The minute.
         * @type {NumberOrInteger}
         */
        this.minute = util$3.assertValidMinute(minute);
        /**
         * The second.
         * @type {NumberOrInteger}
         */
        this.second = util$3.assertValidSecond(second);
        /**
         * The nanosecond.
         * @type {NumberOrInteger}
         */
        this.nanosecond = util$3.assertValidNanosecond(nanosecond);
        var _a = __read$x(verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId), 2), offset = _a[0], id = _a[1];
        /**
         * The time zone offset in seconds.
         *
         * *Either this or {@link timeZoneId} is defined.*
         *
         * @type {NumberOrInteger}
         */
        this.timeZoneOffsetSeconds = offset;
        /**
         * The time zone id.
         *
         * *Either this or {@link timeZoneOffsetSeconds} is defined.*
         *
         * @type {string}
         */
        this.timeZoneId = id !== null && id !== void 0 ? id : undefined;
        Object.freeze(this);
    }
    /**
     * Create a {@link DateTime} object from the given standard JavaScript `Date` and optional nanoseconds.
     * @param {global.Date} standardDate - The standard JavaScript date to convert.
     * @param {NumberOrInteger|undefined} nanosecond - The optional amount of nanoseconds.
     * @return {DateTime} New DateTime.
     */
    DateTime.fromStandardDate = function (standardDate, nanosecond) {
        verifyStandardDateAndNanos(standardDate, nanosecond);
        return new DateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), (0, integer_1$1.toNumber)(util$3.totalNanoseconds(standardDate, nanosecond)), util$3.timeZoneOffsetInSeconds(standardDate), null /* no time zone id */);
    };
    /**
     * Convert date to standard JavaScript `Date`.
     *
     * @returns {StandardDate} Standard JavaScript `Date` at the defined time zone offset
     * @throws {Error} If the time zone offset is not defined in the object.
     */
    DateTime.prototype.toStandardDate = function () {
        return util$3.toStandardDate(this._toUTC());
    };
    /**
     * @ignore
     */
    DateTime.prototype.toString = function () {
        var _a;
        var localDateTimeStr = localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond);
        var timeOffset = this.timeZoneOffsetSeconds != null
            ? util$3.timeZoneOffsetToIsoString((_a = this.timeZoneOffsetSeconds) !== null && _a !== void 0 ? _a : 0)
            : '';
        var timeZoneStr = this.timeZoneId != null
            ? "[".concat(this.timeZoneId, "]")
            : '';
        return localDateTimeStr + timeOffset + timeZoneStr;
    };
    /**
     * @private
     * @returns {number}
     */
    DateTime.prototype._toUTC = function () {
        var _a;
        if (this.timeZoneOffsetSeconds === undefined) {
            throw new Error('Requires DateTime created with time zone offset');
        }
        var epochSecond = util$3.localDateTimeToEpochSecond(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond);
        var utcSecond = epochSecond.subtract((_a = this.timeZoneOffsetSeconds) !== null && _a !== void 0 ? _a : 0);
        return (0, integer_1$1.int)(utcSecond)
            .multiply(1000)
            .add((0, integer_1$1.int)(this.nanosecond).div(1000000))
            .toNumber();
    };
    return DateTime;
}());
temporalTypes.DateTime = DateTime;
Object.defineProperty(DateTime.prototype, DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES$1);
/**
 * Test if given object is an instance of {@link DateTime} class.
 * @param {Object} obj - The object to test.
 * @return {boolean} `true` if given object is a {@link DateTime}, `false` otherwise.
 */
function isDateTime(obj) {
    return hasIdentifierProperty$1(obj, DATE_TIME_IDENTIFIER_PROPERTY);
}
function hasIdentifierProperty$1(obj, property) {
    return obj != null && obj[property] === true;
}
function localDateTimeToString(year, month, day, hour, minute, second, nanosecond) {
    return (util$3.dateToIsoString(year, month, day) +
        'T' +
        util$3.timeToIsoString(hour, minute, second, nanosecond));
}
/**
 * @private
 * @param {NumberOrInteger} timeZoneOffsetSeconds
 * @param {string | null } timeZoneId
 * @returns {Array<NumberOrInteger | undefined | null, string | undefined | null>}
 */
function verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId) {
    var offsetDefined = timeZoneOffsetSeconds !== null && timeZoneOffsetSeconds !== undefined;
    var idDefined = timeZoneId !== null && timeZoneId !== undefined && timeZoneId !== '';
    if (!offsetDefined && !idDefined) {
        throw (0, error_1$c.newError)(
        // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
        "Unable to create DateTime without either time zone offset or id. Please specify either of them. Given offset: ".concat(timeZoneOffsetSeconds, " and id: ").concat(timeZoneId));
    }
    var result = [undefined, undefined];
    if (offsetDefined) {
        (0, util_1$7.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds');
        result[0] = timeZoneOffsetSeconds;
    }
    if (idDefined) {
        (0, util_1$7.assertString)(timeZoneId, 'Time zone ID');
        util$3.assertValidZoneId('Time zone ID', timeZoneId);
        result[1] = timeZoneId;
    }
    return result;
}
/**
 * @private
 * @param {StandardDate} standardDate
 * @param {NumberOrInteger} nanosecond
 * @returns {void}
 */
function verifyStandardDateAndNanos(standardDate, nanosecond) {
    (0, util_1$7.assertValidDate)(standardDate, 'Standard date');
    if (nanosecond !== null && nanosecond !== undefined) {
        (0, util_1$7.assertNumberOrInteger)(nanosecond, 'Nanosecond');
    }
}

var graphTypes = {};

Object.defineProperty(graphTypes, "__esModule", { value: true });
graphTypes.PathSegment = graphTypes.Path = graphTypes.UnboundRelationship = graphTypes.Relationship = graphTypes.Node = void 0;
graphTypes.isNode = isNode;
graphTypes.isRelationship = isRelationship;
graphTypes.isUnboundRelationship = isUnboundRelationship;
graphTypes.isPath = isPath;
graphTypes.isPathSegment = isPathSegment;
var json_1$2 = json$3;
var IDENTIFIER_PROPERTY_ATTRIBUTES = {
    value: true,
    enumerable: false,
    configurable: false,
    writable: false
};
var NODE_IDENTIFIER_PROPERTY = '__isNode__';
var RELATIONSHIP_IDENTIFIER_PROPERTY = '__isRelationship__';
var UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY = '__isUnboundRelationship__';
var PATH_IDENTIFIER_PROPERTY = '__isPath__';
var PATH_SEGMENT_IDENTIFIER_PROPERTY = '__isPathSegment__';
function hasIdentifierProperty(obj, property) {
    return obj != null && obj[property] === true;
}
/**
 * Class for Node Type.
 */
var Node = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {NumberOrInteger} identity - Unique identity
     * @param {Array<string>} labels - Array for all labels
     * @param {Properties} properties - Map with node properties
     * @param {string} elementId - Node element identifier
     */
    function Node(identity, labels, properties, elementId) {
        /**
         * Identity of the node.
         * @type {NumberOrInteger}
         * @deprecated use {@link Node#elementId} instead
         */
        this.identity = identity;
        /**
         * Labels of the node.
         * @type {string[]}
         */
        this.labels = labels;
        /**
         * Properties of the node.
         * @type {Properties}
         */
        this.properties = properties;
        /**
         * The Node element identifier.
         * @type {string}
         */
        this.elementId = _valueOrGetDefault(elementId, function () { return identity.toString(); });
    }
    /**
     * @ignore
     */
    Node.prototype.toString = function () {
        var s = '(' + this.elementId;
        for (var i = 0; i < this.labels.length; i++) {
            s += ':' + this.labels[i];
        }
        var keys = Object.keys(this.properties);
        if (keys.length > 0) {
            s += ' {';
            for (var i = 0; i < keys.length; i++) {
                if (i > 0)
                    s += ',';
                s += keys[i] + ':' + (0, json_1$2.stringify)(this.properties[keys[i]]);
            }
            s += '}';
        }
        s += ')';
        return s;
    };
    return Node;
}());
graphTypes.Node = Node;
Object.defineProperty(Node.prototype, NODE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
 * Test if given object is an instance of {@link Node} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link Node}, `false` otherwise.
 */
function isNode(obj) {
    return hasIdentifierProperty(obj, NODE_IDENTIFIER_PROPERTY);
}
/**
 * Class for Relationship Type.
 */
var Relationship = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {NumberOrInteger} identity - Unique identity
     * @param {NumberOrInteger} start - Identity of start Node
     * @param {NumberOrInteger} end - Identity of end Node
     * @param {string} type - Relationship type
     * @param {Properties} properties - Map with relationship properties
     * @param {string} elementId - Relationship element identifier
     * @param {string} startNodeElementId - Start Node element identifier
     * @param {string} endNodeElementId - End Node element identifier
     */
    function Relationship(identity, start, end, type, properties, elementId, startNodeElementId, endNodeElementId) {
        /**
         * Identity of the relationship.
         * @type {NumberOrInteger}
         * @deprecated use {@link Relationship#elementId} instead
         */
        this.identity = identity;
        /**
         * Identity of the start node.
         * @type {NumberOrInteger}
         * @deprecated use {@link Relationship#startNodeElementId} instead
         */
        this.start = start;
        /**
         * Identity of the end node.
         * @type {NumberOrInteger}
         * @deprecated use {@link Relationship#endNodeElementId} instead
         */
        this.end = end;
        /**
         * Type of the relationship.
         * @type {string}
         */
        this.type = type;
        /**
         * Properties of the relationship.
         * @type {Properties}
         */
        this.properties = properties;
        /**
         * The Relationship element identifier.
         * @type {string}
         */
        this.elementId = _valueOrGetDefault(elementId, function () { return identity.toString(); });
        /**
         * The Start Node element identifier.
         * @type {string}
         */
        this.startNodeElementId = _valueOrGetDefault(startNodeElementId, function () { return start.toString(); });
        /**
         * The End Node element identifier.
         * @type {string}
         */
        this.endNodeElementId = _valueOrGetDefault(endNodeElementId, function () { return end.toString(); });
    }
    /**
     * @ignore
     */
    Relationship.prototype.toString = function () {
        var s = '(' + this.startNodeElementId + ')-[:' + this.type;
        var keys = Object.keys(this.properties);
        if (keys.length > 0) {
            s += ' {';
            for (var i = 0; i < keys.length; i++) {
                if (i > 0)
                    s += ',';
                s += keys[i] + ':' + (0, json_1$2.stringify)(this.properties[keys[i]]);
            }
            s += '}';
        }
        s += ']->(' + this.endNodeElementId + ')';
        return s;
    };
    return Relationship;
}());
graphTypes.Relationship = Relationship;
Object.defineProperty(Relationship.prototype, RELATIONSHIP_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
 * Test if given object is an instance of {@link Relationship} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link Relationship}, `false` otherwise.
 */
function isRelationship(obj) {
    return hasIdentifierProperty(obj, RELATIONSHIP_IDENTIFIER_PROPERTY);
}
/**
 * Class for UnboundRelationship Type.
 * @access private
 */
var UnboundRelationship = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {NumberOrInteger} identity - Unique identity
     * @param {string} type - Relationship type
     * @param {Properties} properties - Map with relationship properties
     * @param {string} elementId - Relationship element identifier
     */
    function UnboundRelationship(identity, type, properties, elementId) {
        /**
         * Identity of the relationship.
         * @type {NumberOrInteger}
         * @deprecated use {@link UnboundRelationship#elementId} instead
         */
        this.identity = identity;
        /**
         * Type of the relationship.
         * @type {string}
         */
        this.type = type;
        /**
         * Properties of the relationship.
         * @type {Properties}
         */
        this.properties = properties;
        /**
         * The Relationship element identifier.
         * @type {string}
         */
        this.elementId = _valueOrGetDefault(elementId, function () { return identity.toString(); });
    }
    /**
     * Bind relationship
     *
     * @protected
     * @deprecated use {@link UnboundRelationship#bindTo} instead
     * @param {Integer} start - Identity of start node
     * @param {Integer} end - Identity of end node
     * @return {Relationship} - Created relationship
     */
    UnboundRelationship.prototype.bind = function (start, end) {
        return new Relationship(this.identity, start, end, this.type, this.properties, this.elementId);
    };
    /**
     * Bind relationship
     *
     * @protected
     * @param {Node} start - Start Node
     * @param {Node} end - End Node
     * @return {Relationship} - Created relationship
     */
    UnboundRelationship.prototype.bindTo = function (start, end) {
        return new Relationship(this.identity, start.identity, end.identity, this.type, this.properties, this.elementId, start.elementId, end.elementId);
    };
    /**
     * @ignore
     */
    UnboundRelationship.prototype.toString = function () {
        var s = '-[:' + this.type;
        var keys = Object.keys(this.properties);
        if (keys.length > 0) {
            s += ' {';
            for (var i = 0; i < keys.length; i++) {
                if (i > 0)
                    s += ',';
                s += keys[i] + ':' + (0, json_1$2.stringify)(this.properties[keys[i]]);
            }
            s += '}';
        }
        s += ']->';
        return s;
    };
    return UnboundRelationship;
}());
graphTypes.UnboundRelationship = UnboundRelationship;
Object.defineProperty(UnboundRelationship.prototype, UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
 * Test if given object is an instance of {@link UnboundRelationship} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link UnboundRelationship}, `false` otherwise.
 * @access private
 */
function isUnboundRelationship(obj) {
    return hasIdentifierProperty(obj, UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY);
}
/**
 * Class for PathSegment Type.
 */
var PathSegment = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @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) {
        /**
         * Start node.
         * @type {Node}
         */
        this.start = start;
        /**
         * Relationship.
         * @type {Relationship}
         */
        this.relationship = rel;
        /**
         * End node.
         * @type {Node}
         */
        this.end = end;
    }
    return PathSegment;
}());
graphTypes.PathSegment = PathSegment;
Object.defineProperty(PathSegment.prototype, PATH_SEGMENT_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
 * Test if given object is an instance of {@link PathSegment} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link PathSegment}, `false` otherwise.
 */
function isPathSegment(obj) {
    return hasIdentifierProperty(obj, PATH_SEGMENT_IDENTIFIER_PROPERTY);
}
/**
 * Class for Path Type.
 */
var Path = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {Node} start  - start node
     * @param {Node} end - end node
     * @param {Array<PathSegment>} segments - Array of Segments
     */
    function Path(start, end, segments) {
        /**
         * Start node.
         * @type {Node}
         */
        this.start = start;
        /**
         * End node.
         * @type {Node}
         */
        this.end = end;
        /**
         * Segments.
         * @type {Array<PathSegment>}
         */
        this.segments = segments;
        /**
         * Length of the segments.
         * @type {Number}
         */
        this.length = segments.length;
    }
    return Path;
}());
graphTypes.Path = Path;
Object.defineProperty(Path.prototype, PATH_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES);
/**
 * Test if given object is an instance of {@link Path} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link Path}, `false` otherwise.
 */
function isPath(obj) {
    return hasIdentifierProperty(obj, PATH_IDENTIFIER_PROPERTY);
}
function _valueOrGetDefault(value, getDefault) {
    return value === undefined || value === null ? getDefault() : value;
}

var record = {};

/**
 * 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 __generator$n = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values$c = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read$w = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(record, "__esModule", { value: true });
var error_1$b = error;
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 query. A simple query 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 query 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
 */
var Record = /** @class */ (function () {
    /**
     * Create a new record object.
     * @constructor
     * @protected
     * @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, fieldLookup) {
        /**
         * Field keys, in the order the fields appear in the record.
         * @type {string[]}
         */
        this.keys = keys;
        /**
         * Number of fields
         * @type {Number}
         */
        this.length = keys.length;
        this._fields = fields;
        this._fieldLookup = fieldLookup !== null && fieldLookup !== void 0 ? 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.
     * @returns {void} Nothing
     */
    Record.prototype.forEach = function (visitor) {
        var e_1, _a;
        try {
            for (var _b = __values$c(this.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read$w(_c.value, 2), key = _d[0], value = _d[1];
                visitor(value, key, this);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    };
    /**
     * 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 on each field
     * and return a value that is saved to the returned Array.
     *
     * @returns {Array}
     */
    Record.prototype.map = function (visitor) {
        var e_2, _a;
        var resultArray = [];
        try {
            for (var _b = __values$c(this.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read$w(_c.value, 2), key = _d[0], value = _d[1];
                resultArray.push(visitor(value, key, this));
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_2) throw e_2.error; }
        }
        return resultArray;
    };
    /**
     * Iterate over results. Each iteration will yield an array
     * of exactly two items - the key, and the value (in order).
     *
     * @generator
     * @returns {IterableIterator<Array>}
     */
    Record.prototype.entries = function () {
        var i;
        return __generator$n(this, function (_a) {
            switch (_a.label) {
                case 0:
                    i = 0;
                    _a.label = 1;
                case 1:
                    if (!(i < this.keys.length)) return [3 /*break*/, 4];
                    return [4 /*yield*/, [this.keys[i], this._fields[i]]];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    i++;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/];
            }
        });
    };
    /**
     * Iterate over values.
     *
     * @generator
     * @returns {IterableIterator<Object>}
     */
    Record.prototype.values = function () {
        var i;
        return __generator$n(this, function (_a) {
            switch (_a.label) {
                case 0:
                    i = 0;
                    _a.label = 1;
                case 1:
                    if (!(i < this.keys.length)) return [3 /*break*/, 4];
                    return [4 /*yield*/, this._fields[i]];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    i++;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/];
            }
        });
    };
    /**
     * Iterate over values. Delegates to {@link Record#values}
     *
     * @generator
     * @returns {IterableIterator<Object>}
     */
    Record.prototype[Symbol.iterator] = function () {
        var i;
        return __generator$n(this, function (_a) {
            switch (_a.label) {
                case 0:
                    i = 0;
                    _a.label = 1;
                case 1:
                    if (!(i < this.keys.length)) return [3 /*break*/, 4];
                    return [4 /*yield*/, this._fields[i]];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    i++;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/];
            }
        });
    };
    /**
     * Generates an object out of the current Record
     *
     * @returns {Object}
     */
    Record.prototype.toObject = function () {
        var e_3, _a;
        // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
        var obj = {};
        try {
            for (var _b = __values$c(this.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read$w(_c.value, 2), key = _d[0], value = _d[1];
                obj[key] = value;
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
        return obj;
    };
    /**
     * 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 {*}
     */
    Record.prototype.get = function (key) {
        var index;
        if (!(typeof key === 'number')) {
            index = this._fieldLookup[key];
            if (index === undefined) {
                throw (0, error_1$b.newError)("This record has no field with key '".concat(key.toString(), "', available keys are: [") +
                    this.keys.toString() +
                    '].');
            }
        }
        else {
            index = key;
        }
        if (index > this._fields.length - 1 || index < 0) {
            throw (0, error_1$b.newError)("This record has no field with index '" +
                index.toString() +
                "'. Remember that indexes start at `0`, " +
                'and make sure your query 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}
     */
    Record.prototype.has = function (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;
}());
record.default = Record;

var spatialTypes = {};

Object.defineProperty(spatialTypes, "__esModule", { value: true });
spatialTypes.Point = void 0;
spatialTypes.isPoint = isPoint;
/**
 * 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 util_1$6 = util$4;
var POINT_IDENTIFIER_PROPERTY = '__isPoint__';
/**
 * Represents a single two or three-dimensional point in a particular coordinate reference system.
 * Created `Point` objects are frozen with `Object.freeze()` in constructor and thus immutable.
 */
var Point = /** @class */ (function () {
    /**
     * @constructor
     * @param {T} srid - The coordinate reference system identifier.
     * @param {number} x - The `x` coordinate of the point.
     * @param {number} y - The `y` coordinate of the point.
     * @param {number} [z=undefined] - The `z` coordinate of the point or `undefined` if point has 2 dimensions.
     */
    function Point(srid, x, y, z) {
        /**
         * The coordinate reference system identifier.
         * @type {T}
         */
        this.srid = (0, util_1$6.assertNumberOrInteger)(srid, 'SRID');
        /**
         * The `x` coordinate of the point.
         * @type {number}
         */
        this.x = (0, util_1$6.assertNumber)(x, 'X coordinate');
        /**
         * The `y` coordinate of the point.
         * @type {number}
         */
        this.y = (0, util_1$6.assertNumber)(y, 'Y coordinate');
        /**
         * The `z` coordinate of the point or `undefined` if point is 2-dimensional.
         * @type {number}
         */
        this.z = z === null || z === undefined ? z : (0, util_1$6.assertNumber)(z, 'Z coordinate');
        Object.freeze(this);
    }
    /**
     * @ignore
     */
    Point.prototype.toString = function () {
        return this.z != null && !isNaN(this.z)
            ? "Point{srid=".concat(formatAsFloat(this.srid), ", x=").concat(formatAsFloat(this.x), ", y=").concat(formatAsFloat(this.y), ", z=").concat(formatAsFloat(this.z), "}")
            : "Point{srid=".concat(formatAsFloat(this.srid), ", x=").concat(formatAsFloat(this.x), ", y=").concat(formatAsFloat(this.y), "}");
    };
    return Point;
}());
spatialTypes.Point = Point;
function formatAsFloat(number) {
    return Number.isInteger(number) ? number.toString() + '.0' : number.toString();
}
Object.defineProperty(Point.prototype, POINT_IDENTIFIER_PROPERTY, {
    value: true,
    enumerable: false,
    configurable: false,
    writable: false
});
/**
 * Test if given object is an instance of {@link Point} class.
 * @param {Object} obj the object to test.
 * @return {boolean} `true` if given object is a {@link Point}, `false` otherwise.
 */
function isPoint(obj) {
    var anyObj = obj;
    return obj != null && anyObj[POINT_IDENTIFIER_PROPERTY] === true;
}

var resultSummary = {};

var internal = {};

var observers = {};

/**
 * 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(observers, "__esModule", { value: true });
observers.FailedObserver = observers.CompletedObserver = void 0;
var CompletedObserver$1 = /** @class */ (function () {
    function CompletedObserver() {
    }
    CompletedObserver.prototype.subscribe = function (observer) {
        apply(observer, observer.onKeys, []);
        apply(observer, observer.onCompleted, {});
    };
    CompletedObserver.prototype.cancel = function () {
        // do nothing
    };
    CompletedObserver.prototype.pause = function () {
        // do nothing
    };
    CompletedObserver.prototype.resume = function () {
        // do nothing
    };
    CompletedObserver.prototype.prepareToHandleSingleResponse = function () {
        // do nothing
    };
    CompletedObserver.prototype.markCompleted = function () {
        // do nothing
    };
    CompletedObserver.prototype.onError = function (error) {
        // nothing to do, already finished
        // eslint-disable-next-line
        // @ts-ignore: not available in ES oldest supported version
        throw new Error('CompletedObserver not supposed to call onError', { cause: error });
    };
    return CompletedObserver;
}());
observers.CompletedObserver = CompletedObserver$1;
var FailedObserver$1 = /** @class */ (function () {
    function FailedObserver(_a) {
        var error = _a.error, onError = _a.onError;
        this._error = error;
        this._beforeError = onError;
        this._observers = [];
        this.onError(error);
    }
    FailedObserver.prototype.subscribe = function (observer) {
        apply(observer, observer.onError, this._error);
        this._observers.push(observer);
    };
    FailedObserver.prototype.onError = function (error) {
        apply(this, this._beforeError, error);
        this._observers.forEach(function (o) { return apply(o, o.onError, error); });
    };
    FailedObserver.prototype.cancel = function () {
        // do nothing
    };
    FailedObserver.prototype.pause = function () {
        // do nothing
    };
    FailedObserver.prototype.resume = function () {
        // do nothing
    };
    FailedObserver.prototype.markCompleted = function () {
        // do nothing
    };
    FailedObserver.prototype.prepareToHandleSingleResponse = function () {
        // do nothing
    };
    return FailedObserver;
}());
observers.FailedObserver = FailedObserver$1;
function apply(thisArg, func, param) {
    if (func != null) {
        func.bind(thisArg)(param);
    }
}

var bookmarks$1 = {};

/**
 * 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 __createBinding$a = (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$a = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$a = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$a(result, mod, k[i]);
        __setModuleDefault$a(result, mod);
        return result;
    };
})();
var __read$v = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$o = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(bookmarks$1, "__esModule", { value: true });
bookmarks$1.Bookmarks = void 0;
var util$2 = __importStar$a(util$4);
var BOOKMARKS_KEY = 'bookmarks';
var Bookmarks$4 = /** @class */ (function () {
    /**
     * @constructor
     * @param {string|string[]} values single bookmark as string or multiple bookmarks as a string array.
     */
    function Bookmarks(values) {
        this._values = asStringArray(values);
    }
    Bookmarks.empty = function () {
        return EMPTY_BOOKMARK;
    };
    /**
     * Check if the given Bookmarks holder is meaningful and can be send to the database.
     * @return {boolean} returns `true` bookmarks has a value, `false` otherwise.
     */
    Bookmarks.prototype.isEmpty = function () {
        return this._values.length === 0;
    };
    /**
     * Get all bookmarks values as an array.
     * @return {string[]} all values.
     */
    Bookmarks.prototype.values = function () {
        return this._values;
    };
    Bookmarks.prototype[Symbol.iterator] = function () {
        return this._values[Symbol.iterator]();
    };
    /**
     * Get these bookmarks as an object for begin transaction call.
     * @return {Object} the value of this bookmarks holder as object.
     */
    Bookmarks.prototype.asBeginTransactionParameters = function () {
        var _a;
        if (this.isEmpty()) {
            return {};
        }
        // Driver sends {bookmarks: "max", bookmarks: ["one", "two", "max"]} instead of simple
        // {bookmarks: ["one", "two", "max"]} for backwards compatibility reasons. Old servers can only accept single
        // bookmarks that is why driver has to parse and compare given list of bookmarks. This functionality will
        // eventually be removed.
        return _a = {},
            _a[BOOKMARKS_KEY] = this._values,
            _a;
    };
    return Bookmarks;
}());
bookmarks$1.Bookmarks = Bookmarks$4;
var EMPTY_BOOKMARK = new Bookmarks$4(null);
/**
 * Converts given value to an array.
 * @param {string|string[]|Array} [value=undefined] argument to convert.
 * @return {string[]} value converted to an array.
 */
function asStringArray(value) {
    if (value == null || value === '') {
        return [];
    }
    if (util$2.isString(value)) {
        return [value];
    }
    if (Array.isArray(value)) {
        var result = new Set();
        var flattenedValue = flattenArray(value);
        for (var i = 0; i < flattenedValue.length; i++) {
            var element = flattenedValue[i];
            // if it is undefined or null, ignore it
            if (element !== undefined && element !== null) {
                if (!util$2.isString(element)) {
                    throw new TypeError(
                    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                    "Bookmark value should be a string, given: '".concat(element, "'"));
                }
                result.add(element);
            }
        }
        return __spreadArray$o([], __read$v(result), false);
    }
    throw new TypeError(
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
    "Bookmarks should either be a string or a string array, given: '".concat(value, "'"));
}
/**
 * Recursively flattens an array so that the result becomes a single array
 * of values, which does not include any sub-arrays
 *
 * @param {Array} value
 */
function flattenArray(values) {
    return values.reduce(function (dest, value) {
        return Array.isArray(value)
            ? dest.concat(flattenArray(value))
            : dest.concat(value);
    }, []);
}

var constants$1 = {};

/**
 * 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(constants$1, "__esModule", { value: true });
constants$1.TELEMETRY_APIS = constants$1.BOLT_PROTOCOL_V5_8 = constants$1.BOLT_PROTOCOL_V5_7 = constants$1.BOLT_PROTOCOL_V5_6 = constants$1.BOLT_PROTOCOL_V5_5 = constants$1.BOLT_PROTOCOL_V5_4 = constants$1.BOLT_PROTOCOL_V5_3 = constants$1.BOLT_PROTOCOL_V5_2 = constants$1.BOLT_PROTOCOL_V5_1 = constants$1.BOLT_PROTOCOL_V5_0 = constants$1.BOLT_PROTOCOL_V4_4 = constants$1.BOLT_PROTOCOL_V4_3 = constants$1.BOLT_PROTOCOL_V4_2 = constants$1.BOLT_PROTOCOL_V4_1 = constants$1.BOLT_PROTOCOL_V4_0 = constants$1.BOLT_PROTOCOL_V3 = constants$1.BOLT_PROTOCOL_V2 = constants$1.BOLT_PROTOCOL_V1 = constants$1.DEFAULT_POOL_MAX_SIZE = constants$1.DEFAULT_POOL_ACQUISITION_TIMEOUT = constants$1.DEFAULT_CONNECTION_TIMEOUT_MILLIS = constants$1.ACCESS_MODE_WRITE = constants$1.ACCESS_MODE_READ = constants$1.FETCH_ALL = void 0;
var FETCH_ALL$8 = -1;
constants$1.FETCH_ALL = FETCH_ALL$8;
var DEFAULT_POOL_ACQUISITION_TIMEOUT = 60 * 1000; // 60 seconds
constants$1.DEFAULT_POOL_ACQUISITION_TIMEOUT = DEFAULT_POOL_ACQUISITION_TIMEOUT;
var DEFAULT_POOL_MAX_SIZE = 100;
constants$1.DEFAULT_POOL_MAX_SIZE = DEFAULT_POOL_MAX_SIZE;
var DEFAULT_CONNECTION_TIMEOUT_MILLIS = 30000; // 30 seconds by default
constants$1.DEFAULT_CONNECTION_TIMEOUT_MILLIS = DEFAULT_CONNECTION_TIMEOUT_MILLIS;
var ACCESS_MODE_READ$2 = 'READ';
constants$1.ACCESS_MODE_READ = ACCESS_MODE_READ$2;
var ACCESS_MODE_WRITE$2 = 'WRITE';
constants$1.ACCESS_MODE_WRITE = ACCESS_MODE_WRITE$2;
var BOLT_PROTOCOL_V1$1 = 1;
constants$1.BOLT_PROTOCOL_V1 = BOLT_PROTOCOL_V1$1;
var BOLT_PROTOCOL_V2$1 = 2;
constants$1.BOLT_PROTOCOL_V2 = BOLT_PROTOCOL_V2$1;
var BOLT_PROTOCOL_V3$3 = 3;
constants$1.BOLT_PROTOCOL_V3 = BOLT_PROTOCOL_V3$3;
var BOLT_PROTOCOL_V4_0$3 = 4.0;
constants$1.BOLT_PROTOCOL_V4_0 = BOLT_PROTOCOL_V4_0$3;
var BOLT_PROTOCOL_V4_1$1 = 4.1;
constants$1.BOLT_PROTOCOL_V4_1 = BOLT_PROTOCOL_V4_1$1;
var BOLT_PROTOCOL_V4_2$1 = 4.2;
constants$1.BOLT_PROTOCOL_V4_2 = BOLT_PROTOCOL_V4_2$1;
var BOLT_PROTOCOL_V4_3$1 = 4.3;
constants$1.BOLT_PROTOCOL_V4_3 = BOLT_PROTOCOL_V4_3$1;
var BOLT_PROTOCOL_V4_4$3 = 4.4;
constants$1.BOLT_PROTOCOL_V4_4 = BOLT_PROTOCOL_V4_4$3;
var BOLT_PROTOCOL_V5_0$1 = 5.0;
constants$1.BOLT_PROTOCOL_V5_0 = BOLT_PROTOCOL_V5_0$1;
var BOLT_PROTOCOL_V5_1$3 = 5.1;
constants$1.BOLT_PROTOCOL_V5_1 = BOLT_PROTOCOL_V5_1$3;
var BOLT_PROTOCOL_V5_2$1 = 5.2;
constants$1.BOLT_PROTOCOL_V5_2 = BOLT_PROTOCOL_V5_2$1;
var BOLT_PROTOCOL_V5_3$1 = 5.3;
constants$1.BOLT_PROTOCOL_V5_3 = BOLT_PROTOCOL_V5_3$1;
var BOLT_PROTOCOL_V5_4$1 = 5.4;
constants$1.BOLT_PROTOCOL_V5_4 = BOLT_PROTOCOL_V5_4$1;
var BOLT_PROTOCOL_V5_5$1 = 5.5;
constants$1.BOLT_PROTOCOL_V5_5 = BOLT_PROTOCOL_V5_5$1;
var BOLT_PROTOCOL_V5_6$1 = 5.6;
constants$1.BOLT_PROTOCOL_V5_6 = BOLT_PROTOCOL_V5_6$1;
var BOLT_PROTOCOL_V5_7$1 = 5.7;
constants$1.BOLT_PROTOCOL_V5_7 = BOLT_PROTOCOL_V5_7$1;
var BOLT_PROTOCOL_V5_8$1 = 5.8;
constants$1.BOLT_PROTOCOL_V5_8 = BOLT_PROTOCOL_V5_8$1;
var TELEMETRY_APIS$1 = {
    MANAGED_TRANSACTION: 0,
    UNMANAGED_TRANSACTION: 1,
    AUTO_COMMIT_TRANSACTION: 2,
    EXECUTE_QUERY: 3
};
constants$1.TELEMETRY_APIS = TELEMETRY_APIS$1;

var connectionHolder$1 = {};

var logger$1 = {};

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 _a$i;
Object.defineProperty(logger$1, "__esModule", { value: true });
logger$1.Logger = 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.
 */
var error_1$a = error;
var ERROR = 'error';
var WARN = 'warn';
var INFO = 'info';
var DEBUG = 'debug';
var DEFAULT_LEVEL = INFO;
var levels = (_a$i = {},
    _a$i[ERROR] = 0,
    _a$i[WARN] = 1,
    _a$i[INFO] = 2,
    _a$i[DEBUG] = 3,
    _a$i);
/**
 * Logger used by the driver to notify about various internal events. Single logger should be used per driver.
 */
var Logger$1 = /** @class */ (function () {
    /**
     * @constructor
     * @param {string} level the enabled logging level.
     * @param {function(level: string, message: string)} loggerFunction the function to write the log level and message.
     */
    function Logger(level, loggerFunction) {
        this._level = level;
        this._loggerFunction = loggerFunction;
    }
    /**
     * Create a new logger based on the given driver configuration.
     * @param {Object} driverConfig the driver configuration as supplied by the user.
     * @return {Logger} a new logger instance or a no-op logger when not configured.
     */
    Logger.create = function (driverConfig) {
        if ((driverConfig === null || driverConfig === void 0 ? void 0 : driverConfig.logging) != null) {
            var loggingConfig = driverConfig.logging;
            var level = extractConfiguredLevel(loggingConfig);
            var loggerFunction = extractConfiguredLogger(loggingConfig);
            return new Logger(level, loggerFunction);
        }
        return this.noOp();
    };
    /**
     * Create a no-op logger implementation.
     * @return {Logger} the no-op logger implementation.
     */
    Logger.noOp = function () {
        return noOpLogger;
    };
    /**
     * Check if error logging is enabled, i.e. it is not a no-op implementation.
     * @return {boolean} `true` when enabled, `false` otherwise.
     */
    Logger.prototype.isErrorEnabled = function () {
        return isLevelEnabled(this._level, ERROR);
    };
    /**
     * Log an error message.
     * @param {string} message the message to log.
     */
    Logger.prototype.error = function (message) {
        if (this.isErrorEnabled()) {
            this._loggerFunction(ERROR, message);
        }
    };
    /**
     * Check if warn logging is enabled, i.e. it is not a no-op implementation.
     * @return {boolean} `true` when enabled, `false` otherwise.
     */
    Logger.prototype.isWarnEnabled = function () {
        return isLevelEnabled(this._level, WARN);
    };
    /**
     * Log an warning message.
     * @param {string} message the message to log.
     */
    Logger.prototype.warn = function (message) {
        if (this.isWarnEnabled()) {
            this._loggerFunction(WARN, message);
        }
    };
    /**
     * Check if info logging is enabled, i.e. it is not a no-op implementation.
     * @return {boolean} `true` when enabled, `false` otherwise.
     */
    Logger.prototype.isInfoEnabled = function () {
        return isLevelEnabled(this._level, INFO);
    };
    /**
     * Log an info message.
     * @param {string} message the message to log.
     */
    Logger.prototype.info = function (message) {
        if (this.isInfoEnabled()) {
            this._loggerFunction(INFO, message);
        }
    };
    /**
     * Check if debug logging is enabled, i.e. it is not a no-op implementation.
     * @return {boolean} `true` when enabled, `false` otherwise.
     */
    Logger.prototype.isDebugEnabled = function () {
        return isLevelEnabled(this._level, DEBUG);
    };
    /**
     * Log a debug message.
     * @param {string} message the message to log.
     */
    Logger.prototype.debug = function (message) {
        if (this.isDebugEnabled()) {
            this._loggerFunction(DEBUG, message);
        }
    };
    return Logger;
}());
logger$1.Logger = Logger$1;
var NoOpLogger = /** @class */ (function (_super) {
    __extends$R(NoOpLogger, _super);
    function NoOpLogger() {
        return _super.call(this, INFO, function (level, message) { }) || this;
    }
    NoOpLogger.prototype.isErrorEnabled = function () {
        return false;
    };
    NoOpLogger.prototype.error = function (message) { };
    NoOpLogger.prototype.isWarnEnabled = function () {
        return false;
    };
    NoOpLogger.prototype.warn = function (message) { };
    NoOpLogger.prototype.isInfoEnabled = function () {
        return false;
    };
    NoOpLogger.prototype.info = function (message) { };
    NoOpLogger.prototype.isDebugEnabled = function () {
        return false;
    };
    NoOpLogger.prototype.debug = function (message) { };
    return NoOpLogger;
}(Logger$1));
var noOpLogger = new NoOpLogger();
/**
 * Check if the given logging level is enabled.
 * @param {string} configuredLevel the configured level.
 * @param {string} targetLevel the level to check.
 * @return {boolean} value of `true` when enabled, `false` otherwise.
 */
function isLevelEnabled(configuredLevel, targetLevel) {
    return levels[configuredLevel] >= levels[targetLevel];
}
/**
 * Extract the configured logging level from the driver's logging configuration.
 * @param {Object} loggingConfig the logging configuration.
 * @return {string} the configured log level or default when none configured.
 */
function extractConfiguredLevel(loggingConfig) {
    if ((loggingConfig === null || loggingConfig === void 0 ? void 0 : loggingConfig.level) != null) {
        var configuredLevel = loggingConfig.level;
        var value = levels[configuredLevel];
        if (value == null && value !== 0) {
            throw (0, error_1$a.newError)("Illegal logging level: ".concat(configuredLevel, ". Supported levels are: ").concat(Object.keys(levels).toString()));
        }
        return configuredLevel;
    }
    return DEFAULT_LEVEL;
}
/**
 * Extract the configured logger function from the driver's logging configuration.
 * @param {Object} loggingConfig the logging configuration.
 * @return {function(level: string, message: string)} the configured logging function.
 */
function extractConfiguredLogger(loggingConfig) {
    var _a, _b;
    if ((loggingConfig === null || loggingConfig === void 0 ? void 0 : loggingConfig.logger) != null) {
        var configuredLogger = loggingConfig.logger;
        if (configuredLogger != null && typeof configuredLogger === 'function') {
            return configuredLogger;
        }
    }
    throw (0, error_1$a.newError)("Illegal logger function: ".concat((_b = (_a = loggingConfig === null || loggingConfig === void 0 ? void 0 : loggingConfig.logger) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : 'undefined'));
}

/**
 * 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 @typescript-eslint/promise-function-async */
var __extends$Q = (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 __awaiter$k = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$m = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(connectionHolder$1, "__esModule", { value: true });
connectionHolder$1.EMPTY_CONNECTION_HOLDER = connectionHolder$1.ReadOnlyConnectionHolder = connectionHolder$1.ConnectionHolder = void 0;
var error_1$9 = error;
var util_1$5 = util$4;
var constants_1$4 = constants$1;
var bookmarks_1$3 = bookmarks$1;
var logger_1$2 = logger$1;
/**
 * Utility to lazily initialize connections and return them back to the pool when unused.
 * @private
 */
var ConnectionHolder = /** @class */ (function () {
    /**
     * @constructor
     * @param {object} params
     * @property {string} params.mode - the access mode for new connection holder.
     * @property {string} params.database - the target database name.
     * @property {Bookmarks} params.bookmarks - initial bookmarks
     * @property {ConnectionProvider} params.connectionProvider - the connection provider to acquire connections from.
     * @property {string?} params.impersonatedUser - the user which will be impersonated
     * @property {function(databaseName:string)} params.onDatabaseNameResolved - callback called when the database name is resolved
     * @property {function():Promise<Bookmarks>} params.getConnectionAcquistionBookmarks - called for getting Bookmarks for acquiring connections
     * @property {AuthToken} params.auth - the target auth for the to-be-acquired connection
     */
    function ConnectionHolder(_a) {
        var mode = _a.mode, _b = _a.database, database = _b === void 0 ? '' : _b, bookmarks = _a.bookmarks, connectionProvider = _a.connectionProvider, impersonatedUser = _a.impersonatedUser, onDatabaseNameResolved = _a.onDatabaseNameResolved, getConnectionAcquistionBookmarks = _a.getConnectionAcquistionBookmarks, auth = _a.auth, log = _a.log;
        this._mode = mode !== null && mode !== void 0 ? mode : constants_1$4.ACCESS_MODE_WRITE;
        this._closed = false;
        this._database = database != null ? (0, util_1$5.assertString)(database, 'database') : '';
        this._bookmarks = bookmarks !== null && bookmarks !== void 0 ? bookmarks : bookmarks_1$3.Bookmarks.empty();
        this._connectionProvider = connectionProvider;
        this._impersonatedUser = impersonatedUser;
        this._referenceCount = 0;
        this._connectionPromise = Promise.resolve(null);
        this._onDatabaseNameResolved = onDatabaseNameResolved;
        this._auth = auth;
        this._log = log;
        this._logError = this._logError.bind(this);
        this._getConnectionAcquistionBookmarks = getConnectionAcquistionBookmarks !== null && getConnectionAcquistionBookmarks !== void 0 ? getConnectionAcquistionBookmarks : (function () { return Promise.resolve(bookmarks_1$3.Bookmarks.empty()); });
    }
    ConnectionHolder.prototype.mode = function () {
        return this._mode;
    };
    ConnectionHolder.prototype.database = function () {
        return this._database;
    };
    ConnectionHolder.prototype.setDatabase = function (database) {
        this._database = database;
    };
    ConnectionHolder.prototype.bookmarks = function () {
        return this._bookmarks;
    };
    ConnectionHolder.prototype.connectionProvider = function () {
        return this._connectionProvider;
    };
    ConnectionHolder.prototype.referenceCount = function () {
        return this._referenceCount;
    };
    ConnectionHolder.prototype.initializeConnection = function (homeDatabase) {
        if (this._referenceCount === 0 && (this._connectionProvider != null)) {
            this._connectionPromise = this._createConnectionPromise(this._connectionProvider, homeDatabase);
        }
        else {
            this._referenceCount++;
            return false;
        }
        this._referenceCount++;
        return true;
    };
    ConnectionHolder.prototype._createConnectionPromise = function (connectionProvider, homeDatabase) {
        return __awaiter$k(this, void 0, void 0, function () {
            var _a, _b;
            var _c;
            return __generator$m(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _b = (_a = connectionProvider).acquireConnection;
                        _c = {
                            accessMode: this._mode,
                            database: this._database
                        };
                        return [4 /*yield*/, this._getBookmarks()];
                    case 1: return [4 /*yield*/, _b.apply(_a, [(_c.bookmarks = _d.sent(),
                                _c.impersonatedUser = this._impersonatedUser,
                                _c.onDatabaseNameResolved = this._onDatabaseNameResolved,
                                _c.auth = this._auth,
                                _c.homeDb = homeDatabase,
                                _c)])];
                    case 2: return [2 /*return*/, _d.sent()];
                }
            });
        });
    };
    ConnectionHolder.prototype._getBookmarks = function () {
        return __awaiter$k(this, void 0, void 0, function () {
            return __generator$m(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._getConnectionAcquistionBookmarks()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    ConnectionHolder.prototype.getConnection = function () {
        return this._connectionPromise;
    };
    ConnectionHolder.prototype.releaseConnection = function () {
        if (this._referenceCount === 0) {
            return this._connectionPromise;
        }
        this._referenceCount--;
        if (this._referenceCount === 0) {
            return this._releaseConnection();
        }
        return this._connectionPromise;
    };
    ConnectionHolder.prototype.close = function (hasTx) {
        this._closed = true;
        if (this._referenceCount === 0) {
            return this._connectionPromise;
        }
        this._referenceCount = 0;
        return this._releaseConnection(hasTx);
    };
    ConnectionHolder.prototype.log = function () {
        return this._log;
    };
    /**
     * 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
     */
    ConnectionHolder.prototype._releaseConnection = function (hasTx) {
        this._connectionPromise = this._connectionPromise
            .then(function (connection) {
            if (connection != null) {
                if (connection.isOpen() && (connection.hasOngoingObservableRequests() || hasTx === true)) {
                    return connection
                        .resetAndFlush()
                        .catch(ignoreError)
                        .then(function () { return connection.release().then(function () { return null; }); });
                }
                return connection.release().then(function () { return null; });
            }
            else {
                return Promise.resolve(null);
            }
        })
            .catch(this._logError);
        return this._connectionPromise;
    };
    ConnectionHolder.prototype._logError = function (error) {
        if (this._log.isWarnEnabled()) {
            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
            this._log.warn("ConnectionHolder got an error while releasing the connection. Error ".concat(error, ". Stacktrace: ").concat(error.stack));
        }
        return null;
    };
    return ConnectionHolder;
}());
connectionHolder$1.ConnectionHolder = ConnectionHolder;
/**
 * Provides a interaction with a ConnectionHolder without change it state by
 * releasing or initilizing
 */
var ReadOnlyConnectionHolder = /** @class */ (function (_super) {
    __extends$Q(ReadOnlyConnectionHolder, _super);
    /**
     * Constructor
     * @param {ConnectionHolder} connectionHolder the connection holder which will treat the requests
     */
    function ReadOnlyConnectionHolder(connectionHolder) {
        var _this = _super.call(this, {
            mode: connectionHolder.mode(),
            database: connectionHolder.database(),
            bookmarks: connectionHolder.bookmarks(),
            // @ts-expect-error
            getConnectionAcquistionBookmarks: connectionHolder._getConnectionAcquistionBookmarks,
            connectionProvider: connectionHolder.connectionProvider(),
            log: connectionHolder.log()
        }) || this;
        _this._connectionHolder = connectionHolder;
        return _this;
    }
    /**
     * Return the true if the connection is suppose to be initilized with the command.
     *
     * @return {boolean}
     */
    ReadOnlyConnectionHolder.prototype.initializeConnection = function () {
        if (this._connectionHolder.referenceCount() === 0) {
            return false;
        }
        return true;
    };
    /**
     * Get the current connection promise.
     * @return {Promise<Connection>} promise resolved with the current connection.
     */
    ReadOnlyConnectionHolder.prototype.getConnection = function () {
        return this._connectionHolder.getConnection();
    };
    /**
     * Get the current connection promise, doesn't performs the release
     * @return {Promise<Connection>} promise with the resolved current connection
     */
    ReadOnlyConnectionHolder.prototype.releaseConnection = function () {
        return this._connectionHolder.getConnection().catch(function () { return Promise.resolve(null); });
    };
    /**
     * Get the current connection promise, doesn't performs the connection close
     * @return {Promise<Connection>} promise with the resolved current connection
     */
    ReadOnlyConnectionHolder.prototype.close = function () {
        return this._connectionHolder.getConnection().catch(function () { return Promise.resolve(null); });
    };
    return ReadOnlyConnectionHolder;
}(ConnectionHolder));
connectionHolder$1.ReadOnlyConnectionHolder = ReadOnlyConnectionHolder;
connectionHolder$1.default = ReadOnlyConnectionHolder;
var EmptyConnectionHolder = /** @class */ (function (_super) {
    __extends$Q(EmptyConnectionHolder, _super);
    function EmptyConnectionHolder() {
        return _super.call(this, {
            // Empty logger
            log: logger_1$2.Logger.create({})
        }) || this;
    }
    EmptyConnectionHolder.prototype.mode = function () {
        return undefined;
    };
    EmptyConnectionHolder.prototype.database = function () {
        return undefined;
    };
    EmptyConnectionHolder.prototype.initializeConnection = function () {
        // nothing to initialize
        return true;
    };
    EmptyConnectionHolder.prototype.getConnection = function () {
        return __awaiter$k(this, void 0, void 0, function () {
            return __generator$m(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Promise.reject((0, error_1$9.newError)('This connection holder does not serve connections'))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    EmptyConnectionHolder.prototype.releaseConnection = function () {
        return __awaiter$k(this, void 0, void 0, function () {
            return __generator$m(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Promise.resolve(null)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    EmptyConnectionHolder.prototype.close = function () {
        return __awaiter$k(this, void 0, void 0, function () {
            return __generator$m(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Promise.resolve(null)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    return EmptyConnectionHolder;
}(ConnectionHolder));
/**
 * Connection holder that does not manage any connections.
 * @type {ConnectionHolder}
 * @private
 */
var EMPTY_CONNECTION_HOLDER$1 = new EmptyConnectionHolder();
connectionHolder$1.EMPTY_CONNECTION_HOLDER = EMPTY_CONNECTION_HOLDER$1;
// eslint-disable-next-line n/handle-callback-err
function ignoreError(error) {
    return null;
}

var txConfig$1 = {};

/**
 * 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 __createBinding$9 = (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$9 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$9 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$9(result, mod, k[i]);
        __setModuleDefault$9(result, mod);
        return result;
    };
})();
Object.defineProperty(txConfig$1, "__esModule", { value: true });
txConfig$1.TxConfig = void 0;
var util$1 = __importStar$9(util$4);
var error_1$8 = error;
var integer_1 = integer;
/**
 * Internal holder of the transaction configuration.
 * It performs input validation and value conversion for further serialization by the Bolt protocol layer.
 * Users of the driver provide transaction configuration as regular objects `{timeout: 10, metadata: {key: 'value'}}`.
 * Driver converts such objects to {@link TxConfig} immediately and uses converted values everywhere.
 */
var TxConfig$4 = /** @class */ (function () {
    /**
     * @constructor
     * @param {Object} config the raw configuration object.
     */
    function TxConfig(config, log) {
        assertValidConfig(config);
        this.timeout = extractTimeout(config, log);
        this.metadata = extractMetadata(config);
    }
    /**
     * Get an empty config object.
     * @return {TxConfig} an empty config.
     */
    TxConfig.empty = function () {
        return EMPTY_CONFIG;
    };
    /**
     * Check if this config object is empty. I.e. has no configuration values specified.
     * @return {boolean} `true` if this object is empty, `false` otherwise.
     */
    TxConfig.prototype.isEmpty = function () {
        return Object.values(this).every(function (value) { return value == null; });
    };
    return TxConfig;
}());
txConfig$1.TxConfig = TxConfig$4;
var EMPTY_CONFIG = new TxConfig$4({});
/**
 * @return {Integer|null}
 */
function extractTimeout(config, log) {
    if (util$1.isObject(config) && config.timeout != null) {
        util$1.assertNumberOrInteger(config.timeout, 'Transaction timeout');
        if (isTimeoutFloat(config) && (log === null || log === void 0 ? void 0 : log.isInfoEnabled()) === true) {
            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
            log === null || log === void 0 ? void 0 : log.info("Transaction timeout expected to be an integer, got: ".concat(config.timeout, ". The value will be rounded up."));
        }
        var timeout = (0, integer_1.int)(config.timeout, { ceilFloat: true });
        if (timeout.isNegative()) {
            throw (0, error_1$8.newError)('Transaction timeout should not be negative');
        }
        return timeout;
    }
    return null;
}
function isTimeoutFloat(config) {
    return typeof config.timeout === 'number' && !Number.isInteger(config.timeout);
}
/**
 * @return {object|null}
 */
function extractMetadata(config) {
    if (util$1.isObject(config) && config.metadata != null) {
        var metadata = config.metadata;
        util$1.assertObject(metadata, 'config.metadata');
        if (Object.keys(metadata).length !== 0) {
            // not an empty object
            return metadata;
        }
    }
    return null;
}
function assertValidConfig(config) {
    if (config != null) {
        util$1.assertObject(config, 'Transaction config');
    }
}

var transactionExecutor$1 = {};

var __assign$x = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$x = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$x.apply(this, arguments);
};
var __awaiter$j = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$l = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read$u = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$n = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(transactionExecutor$1, "__esModule", { value: true });
transactionExecutor$1.TransactionExecutor = 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 @typescript-eslint/promise-function-async */
var error_1$7 = error;
var constants_1$3 = constants$1;
var DEFAULT_MAX_RETRY_TIME_MS$1 = 30 * 1000; // 30 seconds
var DEFAULT_INITIAL_RETRY_DELAY_MS$1 = 1000; // 1 seconds
var DEFAULT_RETRY_DELAY_MULTIPLIER$1 = 2.0;
var DEFAULT_RETRY_DELAY_JITTER_FACTOR$1 = 0.2;
function setTimeoutWrapper(callback, ms) {
    var args = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        args[_i - 2] = arguments[_i];
    }
    return setTimeout.apply(void 0, __spreadArray$n([callback, ms], __read$u(args), false));
}
function clearTimeoutWrapper(timeoutId) {
    return clearTimeout(timeoutId);
}
var TransactionExecutor = /** @class */ (function () {
    function TransactionExecutor(maxRetryTimeMs, initialRetryDelayMs, multiplier, jitterFactor, dependencies) {
        if (dependencies === void 0) { dependencies = {
            setTimeout: setTimeoutWrapper,
            clearTimeout: clearTimeoutWrapper
        }; }
        this._maxRetryTimeMs = _valueOrDefault(maxRetryTimeMs, DEFAULT_MAX_RETRY_TIME_MS$1);
        this._initialRetryDelayMs = _valueOrDefault(initialRetryDelayMs, DEFAULT_INITIAL_RETRY_DELAY_MS$1);
        this._multiplier = _valueOrDefault(multiplier, DEFAULT_RETRY_DELAY_MULTIPLIER$1);
        this._jitterFactor = _valueOrDefault(jitterFactor, DEFAULT_RETRY_DELAY_JITTER_FACTOR$1);
        this._setTimeout = dependencies.setTimeout;
        this._clearTimeout = dependencies.clearTimeout;
        this._inFlightTimeoutIds = [];
        this.pipelineBegin = false;
        this.telemetryApi = constants_1$3.TELEMETRY_APIS.MANAGED_TRANSACTION;
        this._verifyAfterConstruction();
    }
    TransactionExecutor.prototype.execute = function (transactionCreator, transactionWork, transactionWrapper) {
        var _this = this;
        var context = {
            apiTransactionConfig: {
                api: this.telemetryApi,
                onTelemetrySuccess: function () {
                    context.apiTransactionConfig = undefined;
                }
            }
        };
        return new Promise(function (resolve, reject) {
            _this._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject, transactionWrapper, context).catch(reject);
        }).catch(function (error) {
            var retryStartTimeMs = Date.now();
            var retryDelayMs = _this._initialRetryDelayMs;
            return _this._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTimeMs, retryDelayMs, transactionWrapper, context);
        });
    };
    TransactionExecutor.prototype.close = function () {
        var _this = this;
        // cancel all existing timeouts to prevent further retries
        this._inFlightTimeoutIds.forEach(function (timeoutId) { return _this._clearTimeout(timeoutId); });
        this._inFlightTimeoutIds = [];
    };
    TransactionExecutor.prototype._retryTransactionPromise = function (transactionCreator, transactionWork, error, retryStartTime, retryDelayMs, transactionWrapper, executionContext) {
        var _this = this;
        var elapsedTimeMs = Date.now() - retryStartTime;
        if (elapsedTimeMs > this._maxRetryTimeMs || !(0, error_1$7.isRetriableError)(error)) {
            return Promise.reject(error);
        }
        return new Promise(function (resolve, reject) {
            var nextRetryTime = _this._computeDelayWithJitter(retryDelayMs);
            var timeoutId = _this._setTimeout(function () {
                // filter out this timeoutId when time has come and function is being executed
                _this._inFlightTimeoutIds = _this._inFlightTimeoutIds.filter(function (id) { return id !== timeoutId; });
                _this._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject, transactionWrapper, executionContext).catch(reject);
            }, nextRetryTime);
            // add newly created timeoutId to the list of all in-flight timeouts
            _this._inFlightTimeoutIds.push(timeoutId);
        }).catch(function (error) {
            var nextRetryDelayMs = retryDelayMs * _this._multiplier;
            return _this._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, nextRetryDelayMs, transactionWrapper, executionContext);
        });
    };
    TransactionExecutor.prototype._executeTransactionInsidePromise = function (transactionCreator, transactionWork, resolve, reject, transactionWrapper, executionContext) {
        return __awaiter$j(this, void 0, void 0, function () {
            var tx, txPromise, _a, error_2, wrap, wrappedTx, resultPromise;
            var _this = this;
            return __generator$l(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 4, , 5]);
                        txPromise = transactionCreator((executionContext === null || executionContext === void 0 ? void 0 : executionContext.apiTransactionConfig) != null
                            ? __assign$x({}, executionContext === null || executionContext === void 0 ? void 0 : executionContext.apiTransactionConfig) : undefined);
                        if (!this.pipelineBegin) return [3 /*break*/, 1];
                        _a = txPromise;
                        return [3 /*break*/, 3];
                    case 1: return [4 /*yield*/, txPromise];
                    case 2:
                        _a = _b.sent();
                        _b.label = 3;
                    case 3:
                        tx = _a;
                        return [3 /*break*/, 5];
                    case 4:
                        error_2 = _b.sent();
                        // failed to create a transaction
                        reject(error_2);
                        return [2 /*return*/];
                    case 5:
                        wrap = transactionWrapper !== null && transactionWrapper !== void 0 ? transactionWrapper : (function (tx) { return tx; });
                        wrappedTx = wrap(tx);
                        resultPromise = this._safeExecuteTransactionWork(wrappedTx, transactionWork);
                        resultPromise
                            .then(function (result) {
                            return _this._handleTransactionWorkSuccess(result, tx, resolve, reject);
                        })
                            .catch(function (error) { return _this._handleTransactionWorkFailure(error, tx, reject); });
                        return [2 /*return*/];
                }
            });
        });
    };
    TransactionExecutor.prototype._safeExecuteTransactionWork = function (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 Promise.resolve(result);
        }
        catch (error) {
            return Promise.reject(error);
        }
    };
    TransactionExecutor.prototype._handleTransactionWorkSuccess = function (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);
        }
    };
    TransactionExecutor.prototype._handleTransactionWorkFailure = function (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
                .catch(reject);
        }
        else {
            // transaction is already rolled back, propagate the error
            reject(error);
        }
    };
    TransactionExecutor.prototype._computeDelayWithJitter = function (delayMs) {
        var jitter = delayMs * this._jitterFactor;
        var min = delayMs - jitter;
        var max = delayMs + jitter;
        return Math.random() * (max - min) + min;
    };
    TransactionExecutor.prototype._verifyAfterConstruction = function () {
        if (this._maxRetryTimeMs < 0) {
            throw (0, error_1$7.newError)('Max retry time should be >= 0: ' + this._maxRetryTimeMs.toString());
        }
        if (this._initialRetryDelayMs < 0) {
            throw (0, error_1$7.newError)('Initial retry delay should >= 0: ' + this._initialRetryDelayMs.toString());
        }
        if (this._multiplier < 1.0) {
            throw (0, error_1$7.newError)('Multiplier should be >= 1.0: ' + this._multiplier.toString());
        }
        if (this._jitterFactor < 0 || this._jitterFactor > 1) {
            throw (0, error_1$7.newError)('Jitter factor should be in [0.0, 1.0]: ' + this._jitterFactor.toFixed());
        }
    };
    return TransactionExecutor;
}());
transactionExecutor$1.TransactionExecutor = TransactionExecutor;
function _valueOrDefault(value, defaultValue) {
    if (value != null) {
        return value;
    }
    return defaultValue;
}

var urlUtil$2 = {};

/**
 * 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 __assign$w = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$w = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$w.apply(this, arguments);
};
var __read$t = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(urlUtil$2, "__esModule", { value: true });
urlUtil$2.Url = void 0;
urlUtil$2.parseDatabaseUrl = parseDatabaseUrl;
urlUtil$2.defaultPortForScheme = defaultPortForScheme;
urlUtil$2.formatIPv4Address = formatIPv4Address;
urlUtil$2.formatIPv6Address = formatIPv6Address;
var util_1$4 = util$4;
var DEFAULT_BOLT_PORT = 7687;
var DEFAULT_HTTP_PORT = 7474;
var DEFAULT_HTTPS_PORT = 7473;
var Url = /** @class */ (function () {
    function Url(scheme, host, port, hostAndPort, query) {
        /**
         * Nullable scheme (protocol) of the URL.
         * Example: 'bolt', 'neo4j', '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;
    }
    return Url;
}());
urlUtil$2.Url = Url;
function parseDatabaseUrl(url) {
    var _a;
    (0, util_1$4.assertString)(url, 'URL');
    var sanitized = sanitizeUrl(url);
    var parsedUrl = uriJsParse(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 = "".concat(formattedHost, ":").concat(port);
    var query = extractQuery(
    // @ts-expect-error
    (_a = parsedUrl.query) !== null && _a !== void 0 ? _a : extractResourceQueryString(parsedUrl.resourceName), url);
    return new Url(scheme, host, port, hostAndPort, query);
}
function extractResourceQueryString(resource) {
    if (typeof resource !== 'string') {
        return null;
    }
    var _a = __read$t(resource.split('?'), 2), query = _a[1];
    return query;
}
function sanitizeUrl(url) {
    url = url.trim();
    if (!url.includes('://')) {
        // url does not contain scheme, add dummy 'none://' to make parser work correctly
        return { schemeMissing: true, url: "none://".concat(url) };
    }
    return { schemeMissing: false, url: url };
}
function extractScheme(scheme) {
    if (scheme != null) {
        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 == null) {
        throw new Error('Unable to extract host from null or undefined URL');
    }
    return host.trim();
}
function extractPort(portString, scheme) {
    var port = typeof portString === 'string' ? parseInt(portString, 10) : portString;
    return port != null && !isNaN(port) ? port : defaultPortForScheme(scheme);
}
function extractQuery(queryString, url) {
    var query = queryString != null ? trimAndSanitizeQuery(queryString) : null;
    var context = {};
    if (query != null) {
        query.split('&').forEach(function (pair) {
            var keyValue = pair.split('=');
            if (keyValue.length !== 2) {
                throw new Error("Invalid parameters: '".concat(keyValue.toString(), "' in URL '").concat(url, "'."));
            }
            var key = trimAndVerifyQueryElement(keyValue[0], 'key', url);
            var value = trimAndVerifyQueryElement(keyValue[1], 'value', url);
            if (context[key] !== undefined) {
                throw new Error("Duplicated query parameters with key '".concat(key, "' in URL '").concat(url, "'"));
            }
            context[key] = value;
        });
    }
    return context;
}
function trimAndSanitizeQuery(query) {
    query = (query !== null && query !== void 0 ? query : '').trim();
    if ((query === null || query === void 0 ? void 0 : query.charAt(0)) === '?') {
        query = query.substring(1, query.length);
    }
    return query;
}
function trimAndVerifyQueryElement(element, name, url) {
    element = (element !== null && element !== void 0 ? element : '').trim();
    if (element === '') {
        throw new Error("Illegal empty ".concat(name, " in URL query '").concat(url, "'"));
    }
    return element;
}
function escapeIPv6Address(address) {
    var startsWithSquareBracket = address.charAt(0) === '[';
    var endsWithSquareBracket = address.charAt(address.length - 1) === ']';
    if (!startsWithSquareBracket && !endsWithSquareBracket) {
        return "[".concat(address, "]");
    }
    else if (startsWithSquareBracket && endsWithSquareBracket) {
        return address;
    }
    else {
        throw new Error("Illegal IPv6 address ".concat(address));
    }
}
function formatHost(host) {
    if (host === '' || host == null) {
        throw new Error("Illegal host ".concat(host));
    }
    var isIPv6Address = host.includes(':');
    return isIPv6Address ? escapeIPv6Address(host) : host;
}
function formatIPv4Address(address, port) {
    return "".concat(address, ":").concat(port);
}
function formatIPv6Address(address, port) {
    var escapedAddress = escapeIPv6Address(address);
    return "".concat(escapedAddress, ":").concat(port);
}
function defaultPortForScheme(scheme) {
    if (scheme === 'http') {
        return DEFAULT_HTTP_PORT;
    }
    else if (scheme === 'https') {
        return DEFAULT_HTTPS_PORT;
    }
    else {
        return DEFAULT_BOLT_PORT;
    }
}
function uriJsParse(value) {
    // JS version of Python partition function
    function partition(s, delimiter) {
        var i = s.indexOf(delimiter);
        if (i >= 0)
            return [s.substring(0, i), s[i], s.substring(i + 1)];
        else
            return [s, '', ''];
    }
    // JS version of Python rpartition function
    function rpartition(s, delimiter) {
        var i = s.lastIndexOf(delimiter);
        if (i >= 0)
            return [s.substring(0, i), s[i], s.substring(i + 1)];
        else
            return ['', '', s];
    }
    function between(s, ldelimiter, rdelimiter) {
        var lpartition = partition(s, ldelimiter);
        var rpartition = partition(lpartition[2], rdelimiter);
        return [rpartition[0], rpartition[2]];
    }
    // Parse an authority string into an object
    // with the following keys:
    // - userInfo (optional, might contain both user name and password)
    // - host
    // - port (optional, included only as a string)
    function parseAuthority(value) {
        var parsed = {};
        var parts;
        // Parse user info
        parts = rpartition(value, '@');
        if (parts[1] === '@') {
            parsed.userInfo = decodeURIComponent(parts[0]);
            value = parts[2];
        }
        // Parse host and port
        var _a = __read$t(between(value, '[', ']'), 2), ipv6Host = _a[0], rest = _a[1];
        if (ipv6Host !== '') {
            parsed.host = ipv6Host;
            parts = partition(rest, ':');
        }
        else {
            parts = partition(value, ':');
            parsed.host = parts[0];
        }
        if (parts[1] === ':') {
            parsed.port = parts[2];
        }
        return parsed;
    }
    var parsed = {};
    var parts;
    // Parse scheme
    parts = partition(value, ':');
    if (parts[1] === ':') {
        parsed.scheme = decodeURIComponent(parts[0]);
        value = parts[2];
    }
    // Parse fragment
    parts = partition(value, '#');
    if (parts[1] === '#') {
        parsed.fragment = decodeURIComponent(parts[2]);
        value = parts[0];
    }
    // Parse query
    parts = partition(value, '?');
    if (parts[1] === '?') {
        parsed.query = parts[2];
        value = parts[0];
    }
    // Parse authority and path
    if (value.startsWith('//')) {
        parts = partition(value.substr(2), '/');
        parsed = __assign$w(__assign$w({}, parsed), parseAuthority(parts[0]));
        parsed.path = parts[1] + parts[2];
    }
    else {
        parsed.path = value;
    }
    return parsed;
}

var serverAddress$1 = {};

var __createBinding$8 = (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$8 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$8 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$8(result, mod, k[i]);
        __setModuleDefault$8(result, mod);
        return result;
    };
})();
Object.defineProperty(serverAddress$1, "__esModule", { value: true });
serverAddress$1.ServerAddress = 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.
 */
var util_1$3 = util$4;
var urlUtil$1 = __importStar$8(urlUtil$2);
var ServerAddress$1 = /** @class */ (function () {
    function ServerAddress(host, resolved, port, hostPort) {
        this._host = (0, util_1$3.assertString)(host, 'host');
        this._resolved = resolved != null ? (0, util_1$3.assertString)(resolved, 'resolved') : null;
        this._port = (0, util_1$3.assertNumber)(port, 'port');
        this._hostPort = hostPort;
        this._stringValue = resolved != null ? "".concat(hostPort, "(").concat(resolved, ")") : "".concat(hostPort);
    }
    ServerAddress.prototype.host = function () {
        return this._host;
    };
    ServerAddress.prototype.resolvedHost = function () {
        return this._resolved != null ? this._resolved : this._host;
    };
    ServerAddress.prototype.port = function () {
        return this._port;
    };
    ServerAddress.prototype.resolveWith = function (resolved) {
        return new ServerAddress(this._host, resolved, this._port, this._hostPort);
    };
    ServerAddress.prototype.asHostPort = function () {
        return this._hostPort;
    };
    ServerAddress.prototype.asKey = function () {
        return this._hostPort;
    };
    ServerAddress.prototype.toString = function () {
        return this._stringValue;
    };
    ServerAddress.fromUrl = function (url) {
        var urlParsed = urlUtil$1.parseDatabaseUrl(url);
        return new ServerAddress(urlParsed.host, null, urlParsed.port, urlParsed.hostAndPort);
    };
    return ServerAddress;
}());
serverAddress$1.ServerAddress = ServerAddress$1;

var resolver$1 = {};

var baseHostNameResolver = {};

/**
 * 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 @typescript-eslint/promise-function-async */
Object.defineProperty(baseHostNameResolver, "__esModule", { value: true });
var BaseHostNameResolver$1 = /** @class */ (function () {
    function BaseHostNameResolver() {
    }
    BaseHostNameResolver.prototype.resolve = function () {
        throw new Error('Abstract function');
    };
    /**
     * @protected
     */
    BaseHostNameResolver.prototype._resolveToItself = function (address) {
        return Promise.resolve([address]);
    };
    return BaseHostNameResolver;
}());
baseHostNameResolver.default = BaseHostNameResolver$1;

var configuredCustomResolver = {};

Object.defineProperty(configuredCustomResolver, "__esModule", { value: true });
/**
 * 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 @typescript-eslint/promise-function-async */
var server_address_1 = serverAddress$1;
function resolveToSelf(address) {
    return Promise.resolve([address]);
}
var ConfiguredCustomResolver = /** @class */ (function () {
    function ConfiguredCustomResolver(resolverFunction) {
        this._resolverFunction = resolverFunction !== null && resolverFunction !== void 0 ? resolverFunction : resolveToSelf;
    }
    ConfiguredCustomResolver.prototype.resolve = function (seedRouter) {
        var _this = this;
        return new Promise(function (resolve) {
            return resolve(_this._resolverFunction(seedRouter.asHostPort()));
        }).then(function (resolved) {
            if (!Array.isArray(resolved)) {
                throw new TypeError('Configured resolver function should either return an array of addresses or a Promise resolved with an array of addresses.' +
                    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                    "Each address is '<host>:<port>'. Got: ".concat(resolved));
            }
            return resolved.map(function (r) { return server_address_1.ServerAddress.fromUrl(r); });
        });
    };
    return ConfiguredCustomResolver;
}());
configuredCustomResolver.default = ConfiguredCustomResolver;

var __importDefault$10 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(resolver$1, "__esModule", { value: true });
resolver$1.ConfiguredCustomResolver = resolver$1.BaseHostNameResolver = 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.
 */
var base_host_name_resolver_1 = __importDefault$10(baseHostNameResolver);
resolver$1.BaseHostNameResolver = base_host_name_resolver_1.default;
var configured_custom_resolver_1$1 = __importDefault$10(configuredCustomResolver);
resolver$1.ConfiguredCustomResolver = configured_custom_resolver_1$1.default;

var browser$1 = {};

var boltAgent$1 = {};

/**
* 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 */
Object.defineProperty(boltAgent$1, "__esModule", { value: true });
boltAgent$1.fromVersion = fromVersion;
/**
 * Constructs a BoltAgent structure from a given product version.
 *
 * @param {string} version The product version
 * @param {function():SystemInfo} getSystemInfo Parameter used of inject system information and mock calls to the APIs.
 * @returns {BoltAgent} The bolt agent
 */
function fromVersion(version, getSystemInfo) {
    if (getSystemInfo === void 0) { getSystemInfo = function () { return ({
        get userAgent() {
            // this should be defined as an `var` since we need to get information
            // came from the global scope which not always will be defined
            // and we don't want to override the information
            var navigator;
            // @ts-ignore: browser code so must be skipped by ts
            return navigator === null || navigator === void 0 ? void 0 : navigator.userAgent;
        }
    }); }; }
    var systemInfo = getSystemInfo();
    //USER_AGENT looks like 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
    var platform = systemInfo.userAgent != null ? systemInfo.userAgent.split("(")[1].split(")")[0] : undefined;
    var languageDetails = systemInfo.userAgent || undefined;
    return {
        product: "neo4j-javascript/".concat(version),
        platform: platform,
        languageDetails: languageDetails
    };
}

(function (exports) {
/**
 * 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 __createBinding = (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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(boltAgent$1, exports);
}(browser$1));

var pool$2 = {};

var poolConfig = {};

/**
 * 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(poolConfig, "__esModule", { value: true });
poolConfig.DEFAULT_ACQUISITION_TIMEOUT = poolConfig.DEFAULT_MAX_SIZE = void 0;
var DEFAULT_MAX_SIZE = 100;
poolConfig.DEFAULT_MAX_SIZE = DEFAULT_MAX_SIZE;
var DEFAULT_ACQUISITION_TIMEOUT = 60 * 1000; // 60 seconds
poolConfig.DEFAULT_ACQUISITION_TIMEOUT = DEFAULT_ACQUISITION_TIMEOUT;
var PoolConfig$1 = /** @class */ (function () {
    function PoolConfig(maxSize, acquisitionTimeout) {
        this.maxSize = valueOrDefault$2(maxSize, DEFAULT_MAX_SIZE);
        this.acquisitionTimeout = valueOrDefault$2(acquisitionTimeout, DEFAULT_ACQUISITION_TIMEOUT);
    }
    PoolConfig.defaultConfig = function () {
        return new PoolConfig(DEFAULT_MAX_SIZE, DEFAULT_ACQUISITION_TIMEOUT);
    };
    PoolConfig.fromDriverConfig = function (config) {
        var maxSize = isConfigured(config.maxConnectionPoolSize)
            ? config.maxConnectionPoolSize
            : DEFAULT_MAX_SIZE;
        var acquisitionTimeout = isConfigured(config.connectionAcquisitionTimeout)
            ? config.connectionAcquisitionTimeout
            : DEFAULT_ACQUISITION_TIMEOUT;
        return new PoolConfig(maxSize, acquisitionTimeout);
    };
    return PoolConfig;
}());
poolConfig.default = PoolConfig$1;
function valueOrDefault$2(value, defaultValue) {
    return isConfigured(value) ? value : defaultValue;
}
function isConfigured(value) {
    return value === 0 || value != null;
}

var pool$1 = {};

/**
 * 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 __awaiter$i = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$k = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$$ = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(pool$1, "__esModule", { value: true });
var pool_config_1 = __importDefault$$(poolConfig);
var error_1$6 = error;
var logger_1$1 = logger$1;
var Pool$1 = /** @class */ (function () {
    /**
     * @param {function(acquisitionContext: object, address: ServerAddress, function(address: ServerAddress, resource: object): Promise<object>): Promise<object>} create
     *                an allocation function that creates a promise with a new resource. It's given an address for which to
     *                allocate the connection and 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(acquisitionContext: object, resource: object): boolean} validateOnAcquire
     *                called at various times when an instance is acquired
     *                If this returns false, the resource will be evicted
     * @param {function(resource: object): boolean} validateOnRelease
     *                called at various times when an instance is released
     *                If this returns false, the resource will be evicted
     * @param {function(resource: object): Promise<void>} destroy
     *                called with the resource when it is evicted from this pool
     * @param {function(resource: object, observer: { onError }): void} installIdleObserver
     *                called when the resource is released back to pool
     * @param {function(resource: object): void} removeIdleObserver
     *                called when the resource is acquired from the pool
     * @param {PoolConfig} config configuration for the new driver.
     * @param {Logger} log the driver logger.
     */
    function Pool(_a) {
        var _b = _a.create, create = _b === void 0 ? function (acquisitionContext, address, release) { return __awaiter$i(_this, void 0, void 0, function () { return __generator$k(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Promise.reject(new Error('Not implemented'))];
                case 1: return [2 /*return*/, _a.sent()];
            }
        }); }); } : _b, _c = _a.destroy, destroy = _c === void 0 ? function (conn) { return __awaiter$i(_this, void 0, void 0, function () { return __generator$k(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Promise.resolve()];
                case 1: return [2 /*return*/, _a.sent()];
            }
        }); }); } : _c, _d = _a.validateOnAcquire, validateOnAcquire = _d === void 0 ? function (acquisitionContext, conn) { return true; } : _d, _e = _a.validateOnRelease, validateOnRelease = _e === void 0 ? function (conn) { return true; } : _e, _f = _a.installIdleObserver, installIdleObserver = _f === void 0 ? function (conn, observer) { } : _f, _g = _a.removeIdleObserver, removeIdleObserver = _g === void 0 ? function (conn) { } : _g, _h = _a.config, config = _h === void 0 ? pool_config_1.default.defaultConfig() : _h, _j = _a.log, log = _j === void 0 ? logger_1$1.Logger.noOp() : _j;
        var _this = this;
        this._create = create;
        this._destroy = destroy;
        this._validateOnAcquire = validateOnAcquire;
        this._validateOnRelease = validateOnRelease;
        this._installIdleObserver = installIdleObserver;
        this._removeIdleObserver = removeIdleObserver;
        this._maxSize = config.maxSize;
        this._acquisitionTimeout = config.acquisitionTimeout;
        this._pools = {};
        this._pendingCreates = {};
        this._acquireRequests = {};
        this._activeResourceCounts = {};
        this._release = this._release.bind(this);
        this._log = log;
        this._closed = false;
    }
    /**
     * Acquire and idle resource fom the pool or create a new one.
     * @param {object} acquisitionContext the acquisition context used for create and validateOnAcquire connection
     * @param {ServerAddress} address the address for which we're acquiring.
     * @param {object} config the config
     * @param {boolean} config.requireNew Indicate it requires a new resource
     * @return {Promise<Object>} resource that is ready to use.
     */
    Pool.prototype.acquire = function (acquisitionContext, address, config) {
        return __awaiter$i(this, void 0, void 0, function () {
            var key, allRequests, requests;
            var _this = this;
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = address.asKey();
                        allRequests = this._acquireRequests;
                        requests = allRequests[key];
                        if (requests == null) {
                            allRequests[key] = [];
                        }
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                var timeoutId = setTimeout(function () {
                                    // acquisition timeout fired
                                    // remove request from the queue of pending requests, if it's still there
                                    // request might've been taken out by the release operation
                                    var pendingRequests = allRequests[key];
                                    if (pendingRequests != null) {
                                        allRequests[key] = pendingRequests.filter(function (item) { return item !== request; });
                                    }
                                    if (request.isCompleted()) ;
                                    else {
                                        // request is still pending and needs to be failed
                                        var activeCount = _this.activeResourceCount(address);
                                        var idleCount = _this.has(address) ? _this._pools[key].length : 0;
                                        request.reject((0, error_1$6.newError)("Connection acquisition timed out in ".concat(_this._acquisitionTimeout, " ms. Pool status: Active conn count = ").concat(activeCount, ", Idle conn count = ").concat(idleCount, ".")));
                                    }
                                }, _this._acquisitionTimeout);
                                if (typeof timeoutId === 'object') {
                                    // eslint-disable-next-line
                                    // @ts-ignore
                                    timeoutId.unref();
                                }
                                var request = new PendingRequest(key, acquisitionContext, config, resolve, reject, timeoutId, _this._log);
                                allRequests[key].push(request);
                                _this._processPendingAcquireRequests(address);
                            })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Destroy all idle resources for the given address.
     * @param {ServerAddress} address the address of the server to purge its pool.
     * @returns {Promise<void>} A promise that is resolved when the resources are purged
     */
    Pool.prototype.purge = function (address) {
        return __awaiter$i(this, void 0, void 0, function () {
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._purgeKey(address.asKey())];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    Pool.prototype.apply = function (address, resourceConsumer) {
        var key = address.asKey();
        if (key in this._pools) {
            this._pools[key].apply(resourceConsumer);
        }
    };
    /**
     * Destroy all idle resources in this pool.
     * @returns {Promise<void>} A promise that is resolved when the resources are purged
     */
    Pool.prototype.close = function () {
        return __awaiter$i(this, void 0, void 0, function () {
            var _this = this;
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._closed = true;
                        return [4 /*yield*/, Promise.all(Object.keys(this._pools).map(function (key) { return __awaiter$i(_this, void 0, void 0, function () { return __generator$k(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this._purgeKey(key)];
                                    case 1: return [2 /*return*/, _a.sent()];
                                }
                            }); }); })).then()];
                    case 1: 
                    /**
                     * The lack of Promise consuming was making the driver do not close properly in the scenario
                     * captured at result.test.js:it('should handle missing onCompleted'). The test was timing out
                     * because while waiting for the driver close.
                     *
                     * Consuming the Promise.all or by calling then or by awaiting in the result inside this method solved
                     * the issue somehow.
                     *
                     * PS: the return of this method was already awaited at PooledConnectionProvider.close, but the await bellow
                     * seems to be need also.
                     */
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Keep the idle resources for the provided addresses and purge the rest.
     * @returns {Promise<void>} A promise that is resolved when the other resources are purged
     */
    Pool.prototype.keepAll = function (addresses) {
        return __awaiter$i(this, void 0, void 0, function () {
            var keysToKeep, keysPresent, keysToPurge;
            var _this = this;
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        keysToKeep = addresses.map(function (a) { return a.asKey(); });
                        keysPresent = Object.keys(this._pools);
                        keysToPurge = keysPresent.filter(function (k) { return !keysToKeep.includes(k); });
                        return [4 /*yield*/, Promise.all(keysToPurge.map(function (key) { return __awaiter$i(_this, void 0, void 0, function () { return __generator$k(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this._purgeKey(key)];
                                    case 1: return [2 /*return*/, _a.sent()];
                                }
                            }); }); })).then()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Check if this pool contains resources for the given address.
     * @param {ServerAddress} address the address of the server to check.
     * @return {boolean} `true` when pool contains entries for the given key, <code>false</code> otherwise.
     */
    Pool.prototype.has = function (address) {
        return address.asKey() in this._pools;
    };
    /**
     * Get count of active (checked out of the pool) resources for the given key.
     * @param {ServerAddress} address the address of the server to check.
     * @return {number} count of resources acquired by clients.
     */
    Pool.prototype.activeResourceCount = function (address) {
        var _a;
        return (_a = this._activeResourceCounts[address.asKey()]) !== null && _a !== void 0 ? _a : 0;
    };
    Pool.prototype._getOrInitializePoolFor = function (key) {
        var pool = this._pools[key];
        if (pool == null) {
            pool = new SingleAddressPool();
            this._pools[key] = pool;
            this._pendingCreates[key] = 0;
        }
        return pool;
    };
    Pool.prototype._acquire = function (acquisitionContext, address, requireNew) {
        return __awaiter$i(this, void 0, void 0, function () {
            var key, pool, resource_1, valid, e_1, numConnections, resource, numConnections, resource_2;
            var _this = this;
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this._closed) {
                            throw (0, error_1$6.newError)('Pool is closed, it is no more able to serve requests.');
                        }
                        key = address.asKey();
                        pool = this._getOrInitializePoolFor(key);
                        if (!!requireNew) return [3 /*break*/, 10];
                        _a.label = 1;
                    case 1:
                        if (!(pool.length > 0)) return [3 /*break*/, 10];
                        resource_1 = pool.pop();
                        if (resource_1 == null) {
                            return [3 /*break*/, 1];
                        }
                        resourceAcquired(key, this._activeResourceCounts);
                        if (this._removeIdleObserver != null) {
                            this._removeIdleObserver(resource_1);
                        }
                        valid = false;
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 6]);
                        return [4 /*yield*/, this._validateOnAcquire(acquisitionContext, resource_1)];
                    case 3:
                        valid = _a.sent();
                        return [3 /*break*/, 6];
                    case 4:
                        e_1 = _a.sent();
                        resourceReleased(key, this._activeResourceCounts);
                        pool.removeInUse(resource_1);
                        return [4 /*yield*/, this._destroy(resource_1)];
                    case 5:
                        _a.sent();
                        throw e_1;
                    case 6:
                        if (!valid) return [3 /*break*/, 7];
                        // idle resource is valid and can be acquired
                        if (this._log.isDebugEnabled()) {
                            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                            this._log.debug("".concat(resource_1, " acquired from the pool ").concat(key));
                        }
                        return [2 /*return*/, { resource: resource_1, pool: pool }];
                    case 7:
                        resourceReleased(key, this._activeResourceCounts);
                        pool.removeInUse(resource_1);
                        return [4 /*yield*/, this._destroy(resource_1)];
                    case 8:
                        _a.sent();
                        _a.label = 9;
                    case 9: return [3 /*break*/, 1];
                    case 10:
                        // Ensure requested max pool size
                        if (this._maxSize > 0) {
                            numConnections = this.activeResourceCount(address) + this._pendingCreates[key];
                            if (numConnections >= this._maxSize) {
                                // Will put this request in queue instead since the pool is full
                                return [2 /*return*/, { resource: null, pool: pool }];
                            }
                        }
                        // there exist no idle valid resources, create a new one for acquisition
                        // Keep track of how many pending creates there are to avoid making too many connections.
                        this._pendingCreates[key] = this._pendingCreates[key] + 1;
                        _a.label = 11;
                    case 11:
                        _a.trys.push([11, , 15, 16]);
                        numConnections = this.activeResourceCount(address) + pool.length;
                        if (!(numConnections >= this._maxSize && requireNew)) return [3 /*break*/, 13];
                        resource_2 = pool.pop();
                        if (!(resource_2 != null)) return [3 /*break*/, 13];
                        if (this._removeIdleObserver != null) {
                            this._removeIdleObserver(resource_2);
                        }
                        pool.removeInUse(resource_2);
                        return [4 /*yield*/, this._destroy(resource_2)];
                    case 12:
                        _a.sent();
                        _a.label = 13;
                    case 13: return [4 /*yield*/, this._create(acquisitionContext, address, function (address, resource) { return __awaiter$i(_this, void 0, void 0, function () { return __generator$k(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, this._release(address, resource, pool)];
                                case 1: return [2 /*return*/, _a.sent()];
                            }
                        }); }); })];
                    case 14:
                        // Invoke callback that creates actual connection
                        resource = _a.sent();
                        pool.pushInUse(resource);
                        resourceAcquired(key, this._activeResourceCounts);
                        if (this._log.isDebugEnabled()) {
                            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                            this._log.debug("".concat(resource, " created for the pool ").concat(key));
                        }
                        return [3 /*break*/, 16];
                    case 15:
                        this._pendingCreates[key] = this._pendingCreates[key] - 1;
                        return [7 /*endfinally*/];
                    case 16: return [2 /*return*/, { resource: resource, pool: pool }];
                }
            });
        });
    };
    Pool.prototype._release = function (address, resource, pool) {
        return __awaiter$i(this, void 0, void 0, function () {
            var key;
            var _this = this;
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        key = address.asKey();
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 9, 10]);
                        if (!pool.isActive()) return [3 /*break*/, 6];
                        return [4 /*yield*/, this._validateOnRelease(resource)];
                    case 2:
                        if (!!(_a.sent())) return [3 /*break*/, 4];
                        if (this._log.isDebugEnabled()) {
                            this._log.debug(
                            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                            "".concat(resource, " destroyed and can't be released to the pool ").concat(key, " because it is not functional"));
                        }
                        pool.removeInUse(resource);
                        return [4 /*yield*/, this._destroy(resource)];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        if (this._installIdleObserver != null) {
                            this._installIdleObserver(resource, {
                                onError: function (error) {
                                    _this._log.debug(
                                    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                                    "Idle connection ".concat(resource, " destroyed because of error: ").concat(error));
                                    var pool = _this._pools[key];
                                    if (pool != null) {
                                        _this._pools[key] = pool.filter(function (r) { return r !== resource; });
                                        pool.removeInUse(resource);
                                    }
                                    // let's not care about background clean-ups due to errors but just trigger the destroy
                                    // process for the resource, we especially catch any errors and ignore them to avoid
                                    // unhandled promise rejection warnings
                                    _this._destroy(resource).catch(function () { });
                                }
                            });
                        }
                        pool.push(resource);
                        if (this._log.isDebugEnabled()) {
                            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                            this._log.debug("".concat(resource, " released to the pool ").concat(key));
                        }
                        _a.label = 5;
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        // key has been purged, don't put it back, just destroy the resource
                        if (this._log.isDebugEnabled()) {
                            this._log.debug(
                            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                            "".concat(resource, " destroyed and can't be released to the pool ").concat(key, " because pool has been purged"));
                        }
                        pool.removeInUse(resource);
                        return [4 /*yield*/, this._destroy(resource)];
                    case 7:
                        _a.sent();
                        _a.label = 8;
                    case 8: return [3 /*break*/, 10];
                    case 9:
                        resourceReleased(key, this._activeResourceCounts);
                        this._processPendingAcquireRequests(address);
                        return [7 /*endfinally*/];
                    case 10: return [2 /*return*/];
                }
            });
        });
    };
    Pool.prototype._purgeKey = function (key) {
        return __awaiter$i(this, void 0, void 0, function () {
            var pool, destructionList, resource;
            return __generator$k(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        pool = this._pools[key];
                        destructionList = [];
                        if (!(pool != null)) return [3 /*break*/, 2];
                        while (pool.length > 0) {
                            resource = pool.pop();
                            if (resource == null) {
                                continue;
                            }
                            if (this._removeIdleObserver != null) {
                                this._removeIdleObserver(resource);
                            }
                            destructionList.push(this._destroy(resource));
                        }
                        pool.close();
                        // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
                        delete this._pools[key];
                        return [4 /*yield*/, Promise.all(destructionList)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    Pool.prototype._processPendingAcquireRequests = function (address) {
        var _this = this;
        var key = address.asKey();
        var requests = this._acquireRequests[key];
        if (requests != null) {
            var pendingRequest_1 = requests.shift(); // pop a pending acquire request
            if (pendingRequest_1 != null) {
                this._acquire(pendingRequest_1.context, address, pendingRequest_1.requireNew)
                    .catch(function (error) {
                    // failed to acquire/create a new connection to resolve the pending acquire request
                    // propagate the error by failing the pending request
                    pendingRequest_1.reject(error);
                    return { resource: null, pool: null };
                })
                    .then(function (_a) {
                    var resource = _a.resource, pool = _a.pool;
                    // there is not situation where the pool resource is not null and the
                    // pool is null.
                    if (resource != null && pool != null) {
                        // managed to acquire a valid resource from the pool
                        if (pendingRequest_1.isCompleted()) {
                            // request has been completed, most likely failed by a timeout
                            // return the acquired resource back to the pool
                            _this._release(address, resource, pool)
                                .catch(function (error) {
                                if (_this._log.isDebugEnabled()) {
                                    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
                                    _this._log.debug("".concat(resource, " could not be release back to the pool. Cause: ").concat(error));
                                }
                            });
                        }
                        else {
                            // request is still pending and can be resolved with the newly acquired resource
                            pendingRequest_1.resolve(resource); // resolve the pending request with the acquired resource
                        }
                    }
                    else {
                        // failed to acquire a valid resource from the pool
                        // return the pending request back to the pool
                        if (!pendingRequest_1.isCompleted()) {
                            if (_this._acquireRequests[key] == null) {
                                _this._acquireRequests[key] = [];
                            }
                            _this._acquireRequests[key].unshift(pendingRequest_1);
                        }
                    }
                }).catch(function (error) { return pendingRequest_1.reject(error); });
            }
            else {
                // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
                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 _a;
    var currentCount = (_a = activeResourceCounts[key]) !== null && _a !== void 0 ? _a : 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 _a;
    var currentCount = (_a = activeResourceCounts[key]) !== null && _a !== void 0 ? _a : 0;
    var nextCount = currentCount - 1;
    if (nextCount > 0) {
        activeResourceCounts[key] = nextCount;
    }
    else {
        // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
        delete activeResourceCounts[key];
    }
}
var PendingRequest = /** @class */ (function () {
    function PendingRequest(key, context, config, resolve, reject, timeoutId, log) {
        this._key = key;
        this._context = context;
        this._resolve = resolve;
        this._reject = reject;
        this._timeoutId = timeoutId;
        this._log = log;
        this._completed = false;
        this._config = config !== null && config !== void 0 ? config : {};
    }
    Object.defineProperty(PendingRequest.prototype, "context", {
        get: function () {
            return this._context;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PendingRequest.prototype, "requireNew", {
        get: function () {
            var _a;
            return (_a = this._config.requireNew) !== null && _a !== void 0 ? _a : false;
        },
        enumerable: false,
        configurable: true
    });
    PendingRequest.prototype.isCompleted = function () {
        return this._completed;
    };
    PendingRequest.prototype.resolve = function (resource) {
        if (this._completed) {
            return;
        }
        this._completed = true;
        clearTimeout(this._timeoutId);
        if (this._log.isDebugEnabled()) {
            // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
            this._log.debug("".concat(resource, " acquired from the pool ").concat(this._key));
        }
        this._resolve(resource);
    };
    PendingRequest.prototype.reject = function (error) {
        if (this._completed) {
            return;
        }
        this._completed = true;
        clearTimeout(this._timeoutId);
        this._reject(error);
    };
    return PendingRequest;
}());
var SingleAddressPool = /** @class */ (function () {
    function SingleAddressPool() {
        this._active = true;
        this._elements = [];
        this._elementsInUse = new Set();
    }
    SingleAddressPool.prototype.isActive = function () {
        return this._active;
    };
    SingleAddressPool.prototype.close = function () {
        this._active = false;
        this._elements = [];
        this._elementsInUse = new Set();
    };
    SingleAddressPool.prototype.filter = function (predicate) {
        this._elements = this._elements.filter(predicate);
        return this;
    };
    SingleAddressPool.prototype.apply = function (resourceConsumer) {
        this._elements.forEach(resourceConsumer);
        this._elementsInUse.forEach(resourceConsumer);
    };
    Object.defineProperty(SingleAddressPool.prototype, "length", {
        get: function () {
            return this._elements.length;
        },
        enumerable: false,
        configurable: true
    });
    SingleAddressPool.prototype.pop = function () {
        var element = this._elements.pop();
        if (element != null) {
            this._elementsInUse.add(element);
        }
        return element;
    };
    SingleAddressPool.prototype.push = function (element) {
        this._elementsInUse.delete(element);
        return this._elements.push(element);
    };
    SingleAddressPool.prototype.pushInUse = function (element) {
        this._elementsInUse.add(element);
    };
    SingleAddressPool.prototype.removeInUse = function (element) {
        this._elementsInUse.delete(element);
    };
    return SingleAddressPool;
}());
pool$1.default = Pool$1;

(function (exports) {
/**
 * 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 __createBinding = (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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_MAX_SIZE = exports.DEFAULT_ACQUISITION_TIMEOUT = exports.PoolConfig = exports.Pool = void 0;
var pool_config_1 = __importStar(poolConfig);
exports.PoolConfig = pool_config_1.default;
Object.defineProperty(exports, "DEFAULT_ACQUISITION_TIMEOUT", { enumerable: true, get: function () { return pool_config_1.DEFAULT_ACQUISITION_TIMEOUT; } });
Object.defineProperty(exports, "DEFAULT_MAX_SIZE", { enumerable: true, get: function () { return pool_config_1.DEFAULT_MAX_SIZE; } });
var pool_1 = __importDefault(pool$1);
exports.Pool = pool_1.default;
exports.default = pool_1.default;
}(pool$2));

/**
 * 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 __createBinding$7 = (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$7 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$7 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$7(result, mod, k[i]);
        __setModuleDefault$7(result, mod);
        return result;
    };
})();
Object.defineProperty(internal, "__esModule", { value: true });
internal.pool = internal.boltAgent = internal.objectUtil = internal.resolver = internal.serverAddress = internal.urlUtil = internal.logger = internal.transactionExecutor = internal.txConfig = internal.connectionHolder = internal.constants = internal.bookmarks = internal.observer = internal.temporalUtil = internal.util = void 0;
var util = __importStar$7(util$4);
internal.util = util;
var temporalUtil = __importStar$7(temporalUtil$1);
internal.temporalUtil = temporalUtil;
var observer = __importStar$7(observers);
internal.observer = observer;
var bookmarks = __importStar$7(bookmarks$1);
internal.bookmarks = bookmarks;
var constants = __importStar$7(constants$1);
internal.constants = constants;
var connectionHolder = __importStar$7(connectionHolder$1);
internal.connectionHolder = connectionHolder;
var txConfig = __importStar$7(txConfig$1);
internal.txConfig = txConfig;
var transactionExecutor = __importStar$7(transactionExecutor$1);
internal.transactionExecutor = transactionExecutor;
var logger = __importStar$7(logger$1);
internal.logger = logger;
var urlUtil = __importStar$7(urlUtil$2);
internal.urlUtil = urlUtil;
var serverAddress = __importStar$7(serverAddress$1);
internal.serverAddress = serverAddress;
var resolver = __importStar$7(resolver$1);
internal.resolver = resolver;
var objectUtil$1 = __importStar$7(objectUtil$2);
internal.objectUtil = objectUtil$1;
var boltAgent = __importStar$7(browser$1);
internal.boltAgent = boltAgent;
var pool = __importStar$7(pool$2);
internal.pool = pool;

var notification = {};

var __assign$v = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$v = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$v.apply(this, arguments);
};
var __createBinding$6 = (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$6 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$6 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$6(result, mod, k[i]);
        __setModuleDefault$6(result, mod);
        return result;
    };
})();
var __read$s = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$m = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(notification, "__esModule", { value: true });
notification.GqlStatusObject = notification.Notification = notification.notificationClassification = notification.notificationCategory = notification.notificationSeverityLevel = void 0;
notification.polyfillGqlStatusObject = polyfillGqlStatusObject;
notification.polyfillNotification = polyfillNotification;
notification.buildGqlStatusObjectFromMetadata = buildGqlStatusObjectFromMetadata;
notification.buildNotificationsFromMetadata = buildNotificationsFromMetadata;
/**
 * 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 json$1 = __importStar$6(json$3);
var internal_1$3 = internal;
var gql_constants_1 = gqlConstants;
var unknownGqlStatus = {
    WARNING: {
        gql_status: '01N42',
        status_description: 'warn: unknown warning'
    },
    NO_DATA: {
        gql_status: '02N42',
        status_description: 'note: no data - unknown subcondition'
    },
    INFORMATION: {
        gql_status: '03N42',
        status_description: 'info: unknown notification'
    },
    ERROR: {
        gql_status: '50N42',
        status_description: 'error: general processing exception - unexpected error'
    }
};
/**
 * @typedef {'WARNING' | 'INFORMATION' | 'UNKNOWN'} NotificationSeverityLevel
 */
/**
 * Constants that represents the Severity level in the {@link Notification}
 */
var notificationSeverityLevel = {
    WARNING: 'WARNING',
    INFORMATION: 'INFORMATION',
    UNKNOWN: 'UNKNOWN'
};
notification.notificationSeverityLevel = notificationSeverityLevel;
Object.freeze(notificationSeverityLevel);
var severityLevels = Object.values(notificationSeverityLevel);
/**
 * @typedef {'HINT' | 'UNRECOGNIZED' | 'UNSUPPORTED' |'PERFORMANCE' | 'TOPOLOGY' | 'SECURITY' | 'DEPRECATION' | 'GENERIC' | 'SCHEMA' | 'UNKNOWN' } NotificationCategory
 */
/**
 * Constants that represents the Category in the {@link Notification}
 */
var notificationCategory = {
    HINT: 'HINT',
    UNRECOGNIZED: 'UNRECOGNIZED',
    UNSUPPORTED: 'UNSUPPORTED',
    PERFORMANCE: 'PERFORMANCE',
    DEPRECATION: 'DEPRECATION',
    TOPOLOGY: 'TOPOLOGY',
    SECURITY: 'SECURITY',
    GENERIC: 'GENERIC',
    SCHEMA: 'SCHEMA',
    UNKNOWN: 'UNKNOWN'
};
notification.notificationCategory = notificationCategory;
Object.freeze(notificationCategory);
var categories = Object.values(notificationCategory);
/**
 * @typedef {NotificationCategory} NotificationClassification
 * @experimental
 */
/**
 * Constants that represents the Classification in the {@link GqlStatusObject}
 * @type {notificationCategory}
 * @experimental
 */
var notificationClassification = notificationCategory;
notification.notificationClassification = notificationClassification;
/**
 * Class for Cypher notifications
 * @access public
 */
var Notification$1 = /** @class */ (function () {
    /**
     * Create a Notification instance
     * @constructor
     * @param {Object} notification - Object with notification data
     */
    function Notification(notification) {
        /**
         * The code
         * @type {string}
         * @public
         */
        this.code = notification.code;
        /**
         * The title
         * @type {string}
         * @public
         */
        this.title = notification.title;
        /**
         * The description
         * @type {string}
         * @public
         */
        this.description = notification.description;
        /**
         * The raw severity
         *
         * Use {@link Notification#rawSeverityLevel} for the raw value or {@link Notification#severityLevel} for an enumerated value.
         *
         * @type {string}
         * @public
         * @deprecated This property will be removed in 6.0.
         */
        this.severity = notification.severity;
        /**
         * The position which the notification had occur.
         *
         * @type {NotificationPosition}
         * @public
         */
        this.position = _constructPosition(notification.position);
        /**
         * The severity level
         *
         * @type {NotificationSeverityLevel}
         * @public
         * @example
         * const { summary } = await session.run("RETURN 1")
         *
         * for (const notification of summary.notifications) {
         *     switch(notification.severityLevel) {
         *         case neo4j.notificationSeverityLevel.INFORMATION: // or simply 'INFORMATION'
         *             console.info(`${notification.title} - ${notification.description}`)
         *             break
         *         case neo4j.notificationSeverityLevel.WARNING: // or simply 'WARNING'
         *             console.warn(`${notification.title} - ${notification.description}`)
         *             break
         *         case neo4j.notificationSeverityLevel.UNKNOWN: // or simply 'UNKNOWN'
         *         default:
         *             // the raw info came from the server could be found at notification.rawSeverityLevel
         *             console.log(`${notification.title} - ${notification.description}`)
         *             break
         *     }
         * }
         */
        this.severityLevel = _asEnumerableSeverity(notification.severity);
        /**
         * The severity level returned by the server without any validation.
         *
         * @type {string}
         * @public
         */
        this.rawSeverityLevel = notification.severity;
        /**
         * The category
         *
         * @type {NotificationCategory}
         * @public
         * @example
         * const { summary } = await session.run("RETURN 1")
         *
         * for (const notification of summary.notifications) {
         *     switch(notification.category) {
         *         case neo4j.notificationCategory.QUERY: // or simply 'QUERY'
         *             console.info(`${notification.title} - ${notification.description}`)
         *             break
         *         case neo4j.notificationCategory.PERFORMANCE: // or simply 'PERFORMANCE'
         *             console.warn(`${notification.title} - ${notification.description}`)
         *             break
         *         case neo4j.notificationCategory.UNKNOWN: // or simply 'UNKNOWN'
         *         default:
         *             // the raw info came from the server could be found at notification.rawCategory
         *             console.log(`${notification.title} - ${notification.description}`)
         *             break
         *     }
         * }
         */
        this.category = _asEnumerableClassification(notification.category);
        /**
         * The category returned by the server without any validation.
         *
         * @type {string|undefined}
         * @public
         */
        this.rawCategory = notification.category;
    }
    return Notification;
}());
notification.Notification = Notification$1;
/**
 * Representation for GqlStatusObject found when executing a query.
 * <p>
 * This object represents a status of query execution.
 * This status is a superset of {@link Notification}.
 *
 * @experimental
 * @public
 */
var GqlStatusObject = /** @class */ (function () {
    /**
     *
     * @param rawGqlStatusObject
     * @private
     */
    function GqlStatusObject(rawGqlStatusObject) {
        var _a;
        /**
         * The GQLSTATUS
         *
         * @type {string}
         * @public
         */
        this.gqlStatus = rawGqlStatusObject.gql_status;
        /**
         * The GQLSTATUS description
         *
         * @type {string}
         * @public
         */
        this.statusDescription = rawGqlStatusObject.status_description;
        /**
         * The diagnostic record as it is.
         *
         * @type {object}
         * @public
         */
        this.diagnosticRecord = (_a = rawGqlStatusObject.diagnostic_record) !== null && _a !== void 0 ? _a : {};
        /**
         * The position at which the notification had occurred.
         *
         * @type {NotificationPosition | undefined}
         * @public
         */
        this.position = this.diagnosticRecord._position != null ? _constructPosition(this.diagnosticRecord._position) : undefined;
        /**
         * The severity
         *
         * @type {NotificationSeverityLevel}
         * @public
         * @example
         * const { summary } = await session.run("RETURN 1")
         *
         * for (const gqlStatusObject of summary.gqlStatusObjects) {
         *     switch(gqlStatusObject.severity) {
         *         case neo4j.notificationSeverityLevel.INFORMATION: // or simply 'INFORMATION'
         *             console.info(gqlStatusObject.statusDescription)
         *             break
         *         case neo4j.notificationSeverityLevel.WARNING: // or simply 'WARNING'
         *             console.warn(gqlStatusObject.statusDescription)
         *             break
         *         case neo4j.notificationSeverityLevel.UNKNOWN: // or simply 'UNKNOWN'
         *         default:
         *             // the raw info came from the server could be found at gqlStatusObject.rawSeverity
         *             console.log(gqlStatusObject.statusDescription)
         *             break
         *     }
         * }
         */
        this.severity = _asEnumerableSeverity(this.diagnosticRecord._severity);
        /**
         * The severity returned in the diagnostic record from the server without any validation.
         *
         * @type {string | undefined}
         * @public
         */
        this.rawSeverity = this.diagnosticRecord._severity;
        /**
         * The classification
         *
         * @type {NotificationClassification}
         * @public
         * @example
         * const { summary } = await session.run("RETURN 1")
         *
         * for (const gqlStatusObject of summary.gqlStatusObjects) {
         *     switch(gqlStatusObject.classification) {
         *         case neo4j.notificationClassification.QUERY: // or simply 'QUERY'
         *             console.info(gqlStatusObject.statusDescription)
         *             break
         *         case neo4j.notificationClassification.PERFORMANCE: // or simply 'PERFORMANCE'
         *             console.warn(gqlStatusObject.statusDescription)
         *             break
         *         case neo4j.notificationClassification.UNKNOWN: // or simply 'UNKNOWN'
         *         default:
         *             // the raw info came from the server can be found at notification.rawCategory
         *             console.log(gqlStatusObject.statusDescription)
         *             break
         *     }
         * }
         */
        this.classification = _asEnumerableClassification(this.diagnosticRecord._classification);
        /**
         * The category returned by the server without any validation.
         *
         * @type {string|undefined}
         * @public
         */
        this.rawClassification = this.diagnosticRecord._classification;
        /**
         * Indicates if this object represents a notification and it can be filtered using
         * NotificationFilter.
         *
         * Only GqlStatusObject which is Notification has meaningful position, severity and
         * classification.
         *
         * @type {boolean}
         * @public
         */
        this.isNotification = rawGqlStatusObject.neo4j_code != null;
        Object.freeze(this);
    }
    Object.defineProperty(GqlStatusObject.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}
         * @public
         */
        get: function () {
            return json$1.stringify(this.diagnosticRecord, { useCustomToString: true });
        },
        enumerable: false,
        configurable: true
    });
    return GqlStatusObject;
}());
notification.GqlStatusObject = GqlStatusObject;
/**
 *
 * @private
 * @param status
 * @returns {Notification|undefined}
 */
function polyfillNotification(status) {
    var _a, _b, _c;
    // Non notification status should have neo4j_code
    if (status.neo4j_code == null) {
        return undefined;
    }
    return new Notification$1({
        code: status.neo4j_code,
        title: status.title,
        description: status.description,
        severity: (_a = status.diagnostic_record) === null || _a === void 0 ? void 0 : _a._severity,
        category: (_b = status.diagnostic_record) === null || _b === void 0 ? void 0 : _b._classification,
        position: (_c = status.diagnostic_record) === null || _c === void 0 ? void 0 : _c._position
    });
}
/**
 * @private
 * @param notification
 * @returns {GqlStatusObject}
 */
function polyfillGqlStatusObject(notification) {
    var _a;
    var defaultStatus = notification.severity === notificationSeverityLevel.WARNING ? unknownGqlStatus.WARNING : unknownGqlStatus.INFORMATION;
    var polyfilledRawObj = {
        gql_status: defaultStatus.gql_status,
        status_description: (_a = notification.description) !== null && _a !== void 0 ? _a : defaultStatus.status_description,
        neo4j_code: notification.code,
        title: notification.title,
        diagnostic_record: __assign$v({}, gql_constants_1.rawPolyfilledDiagnosticRecord)
    };
    if (notification.severity != null) {
        polyfilledRawObj.diagnostic_record._severity = notification.severity;
    }
    if (notification.category != null) {
        polyfilledRawObj.diagnostic_record._classification = notification.category;
    }
    if (notification.position != null) {
        polyfilledRawObj.diagnostic_record._position = notification.position;
    }
    return new GqlStatusObject(polyfilledRawObj);
}
/**
 * This objects are used for polyfilling the first status on the status list
 *
 * @private
 */
var staticGqlStatusObjects = {
    SUCCESS: new GqlStatusObject({
        gql_status: '00000',
        status_description: 'note: successful completion',
        diagnostic_record: gql_constants_1.rawPolyfilledDiagnosticRecord
    }),
    NO_DATA: new GqlStatusObject({
        gql_status: '02000',
        status_description: 'note: no data',
        diagnostic_record: gql_constants_1.rawPolyfilledDiagnosticRecord
    }),
    NO_DATA_UNKNOWN_SUBCONDITION: new GqlStatusObject(__assign$v(__assign$v({}, unknownGqlStatus.NO_DATA), { diagnostic_record: gql_constants_1.rawPolyfilledDiagnosticRecord })),
    OMITTED_RESULT: new GqlStatusObject({
        gql_status: '00001',
        status_description: 'note: successful completion - omitted result',
        diagnostic_record: gql_constants_1.rawPolyfilledDiagnosticRecord
    })
};
Object.freeze(staticGqlStatusObjects);
/**
 *
 * @private
 * @param metadata
 * @returns
 */
function buildGqlStatusObjectFromMetadata(metadata) {
    var _a, _b;
    function getGqlStatusObjectFromStreamSummary(summary) {
        if ((summary === null || summary === void 0 ? void 0 : summary.have_records_streamed) === true) {
            return staticGqlStatusObjects.SUCCESS;
        }
        if ((summary === null || summary === void 0 ? void 0 : summary.has_keys) === false) {
            return staticGqlStatusObjects.OMITTED_RESULT;
        }
        if ((summary === null || summary === void 0 ? void 0 : summary.pulled) === true) {
            return staticGqlStatusObjects.NO_DATA;
        }
        return staticGqlStatusObjects.NO_DATA_UNKNOWN_SUBCONDITION;
    }
    if (metadata.statuses != null) {
        return metadata.statuses.map(function (status) { return new GqlStatusObject(status); });
    }
    var clientGenerated = getGqlStatusObjectFromStreamSummary(metadata.stream_summary);
    var polyfilledObjects = __spreadArray$m([clientGenerated], __read$s(((_b = (_a = metadata.notifications) === null || _a === void 0 ? void 0 : _a.map(polyfillGqlStatusObject)) !== null && _b !== void 0 ? _b : [])), false);
    return polyfilledObjects.sort(function (a, b) { return calculateWeight(a) - calculateWeight(b); });
}
var gqlStatusWeightByClass = Object.freeze({
    '02': 0,
    '01': 1,
    '00': 2
});
/**
 * GqlStatus weight
 *
 * @private
 */
function calculateWeight(gqlStatusObject) {
    var _a, _b;
    var gqlClass = (_a = gqlStatusObject.gqlStatus) === null || _a === void 0 ? void 0 : _a.slice(0, 2);
    // @ts-expect-error
    return (_b = gqlStatusWeightByClass[gqlClass]) !== null && _b !== void 0 ? _b : 9999;
}
/**
 *
 * @private
 * @param metadata
 * @returns
 */
function buildNotificationsFromMetadata(metadata) {
    if (metadata.notifications != null) {
        return metadata.notifications.map(function (n) { return new Notification$1(n); });
    }
    if (metadata.statuses != null) {
        return metadata.statuses.map(polyfillNotification).filter(function (n) { return n != null; });
    }
    return [];
}
/**
 *
 * @private
 * @param pos
 * @returns {NotificationPosition}
 */
function _constructPosition(pos) {
    if (pos == null) {
        return {};
    }
    /* eslint-disable @typescript-eslint/no-non-null-assertion */
    return {
        offset: internal_1$3.util.toNumber(pos.offset),
        line: internal_1$3.util.toNumber(pos.line),
        column: internal_1$3.util.toNumber(pos.column)
    };
    /* eslint-enable @typescript-eslint/no-non-null-assertion */
}
function _asEnumerableSeverity(severity) {
    return severityLevels.includes(severity)
        ? severity
        : notificationSeverityLevel.UNKNOWN;
}
function _asEnumerableClassification(classification) {
    return categories.includes(classification)
        ? classification
        : notificationClassification.UNKNOWN;
}
notification.default = Notification$1;

/**
 * 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(resultSummary, "__esModule", { value: true });
resultSummary.Stats = resultSummary.QueryStatistics = resultSummary.ProfiledPlan = resultSummary.Plan = resultSummary.ServerInfo = resultSummary.queryType = void 0;
var internal_1$2 = internal;
var notification_1 = notification;
/**
 * A ResultSummary instance contains structured metadata for a {@link Result}.
 * @access public
 */
var ResultSummary = /** @class */ (function () {
    /**
     * @constructor
     * @param {string} query - The query this summary is for
     * @param {Object} parameters - Parameters for the query
     * @param {Object} metadata - Query metadata
     * @param {number|undefined} protocolVersion - Bolt Protocol Version
     */
    function ResultSummary(query, parameters, metadata, protocolVersion) {
        var _a, _b, _c;
        /**
         * The query and parameters this summary is for.
         * @type {{text: string, parameters: Object}}
         * @public
         */
        this.query = { text: query, parameters: parameters };
        /**
         * The type of query executed. Can be "r" for read-only query, "rw" for read-write query,
         * "w" for write-only query and "s" for schema-write query.
         * String constants are available in {@link queryType} object.
         * @type {string}
         * @public
         */
        this.queryType = metadata.type;
        /**
         * Counters for operations the query triggered.
         * @type {QueryStatistics}
         * @public
         */
        this.counters = new QueryStatistics((_a = metadata.stats) !== null && _a !== void 0 ? _a : {});
        // for backwards compatibility, remove in future version
        /**
         * Use {@link ResultSummary.counters} instead.
         * @type {QueryStatistics}
         * @deprecated
         */
        this.updateStatistics = this.counters;
        /**
         * This describes how the database will execute the query.
         * Query plan for the executed query if available, otherwise undefined.
         * Will only be populated for queries that start with "EXPLAIN".
         * @type {Plan|false}
         * @public
         */
        this.plan =
            metadata.plan != null || metadata.profile != null
                ? new Plan((_b = metadata.plan) !== null && _b !== void 0 ? _b : metadata.profile)
                : false;
        /**
         * This describes how the database did execute your query. This will contain detailed information about what
         * each step of the plan did. Profiled query plan for the executed query if available, otherwise undefined.
         * Will only be populated for queries that start with "PROFILE".
         * @type {ProfiledPlan}
         * @public
         */
        this.profile = metadata.profile != null ? new ProfiledPlan(metadata.profile) : false;
        /**
         * An array of notifications that might arise when executing the query. Notifications can be warnings about
         * problematic queries or other valuable information that can be presented in a client. Unlike failures
         * or errors, notifications do not affect the execution of a query.
         * @type {Array<Notification>}
         * @public
         */
        this.notifications = (0, notification_1.buildNotificationsFromMetadata)(metadata);
        /**
         * A list of GqlStatusObjects that arise when executing the query.
         *
         * The list always contains at least 1 status representing the Success, No Data or Omitted Result.
         *
         * When discarding records while connected to a non-gql aware server and using a RxSession,
         * the driver might not be able to tell apart Success and No Data.
         *
         * All other status are notifications like warnings about problematic queries or other valuable
         * information that can be presented in a client.
         *
         * The GqlStatusObjects will be presented in the following order:
         *
         * - A “no data” (02xxx) has precedence over a warning;
         * - A warning (01xxx) has precedence over a success.
         * - A success (00xxx) has precedence over anything informational (03xxx)
         *
         * @type {Array<GqlStatusObject>}
         * @public
         * @experimental
         */
        this.gqlStatusObjects = (0, notification_1.buildGqlStatusObjectFromMetadata)(metadata);
        /**
         * The basic information of the server where the result is obtained from.
         * @type {ServerInfo}
         * @public
         */
        this.server = new ServerInfo(metadata.server, protocolVersion);
        /**
         * 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;
        /**
         * The database name where this summary is obtained from.
         * @type {{name: string}}
         * @public
         */
        this.database = { name: (_c = metadata.db) !== null && _c !== void 0 ? _c : null };
    }
    /**
     * Check if the result summary has a plan
     * @return {boolean}
     */
    ResultSummary.prototype.hasPlan = function () {
        return this.plan instanceof Plan;
    };
    /**
     * Check if the result summary has a profile
     * @return {boolean}
     */
    ResultSummary.prototype.hasProfile = function () {
        return this.profile instanceof ProfiledPlan;
    };
    return ResultSummary;
}());
/**
 * Class for execution plan received by prepending Cypher with EXPLAIN.
 * @access public
 */
var Plan = /** @class */ (function () {
    /**
     * Create a Plan instance
     * @constructor
     * @param {Object} plan - Object with plan data
     */
    function Plan(plan) {
        this.operatorType = plan.operatorType;
        this.identifiers = plan.identifiers;
        this.arguments = plan.args;
        this.children = plan.children != null
            ? plan.children.map(function (child) { return new Plan(child); })
            : [];
    }
    return Plan;
}());
resultSummary.Plan = Plan;
/**
 * Class for execution plan received by prepending Cypher with PROFILE.
 * @access public
 */
var ProfiledPlan = /** @class */ (function () {
    /**
     * Create a ProfiledPlan instance
     * @constructor
     * @param {Object} profile - Object with profile data
     */
    function ProfiledPlan(profile) {
        this.operatorType = profile.operatorType;
        this.identifiers = profile.identifiers;
        this.arguments = profile.args;
        this.dbHits = valueOrDefault$1('dbHits', profile);
        this.rows = valueOrDefault$1('rows', profile);
        this.pageCacheMisses = valueOrDefault$1('pageCacheMisses', profile);
        this.pageCacheHits = valueOrDefault$1('pageCacheHits', profile);
        this.pageCacheHitRatio = valueOrDefault$1('pageCacheHitRatio', profile);
        this.time = valueOrDefault$1('time', profile);
        this.children = profile.children != null
            ? profile.children.map(function (child) { return new ProfiledPlan(child); })
            : [];
    }
    ProfiledPlan.prototype.hasPageCacheStats = function () {
        return (this.pageCacheMisses > 0 ||
            this.pageCacheHits > 0 ||
            this.pageCacheHitRatio > 0);
    };
    return ProfiledPlan;
}());
resultSummary.ProfiledPlan = ProfiledPlan;
/**
 * Stats Query statistics dictionary for a {@link QueryStatistics}
 * @public
 */
var Stats = /** @class */ (function () {
    /**
     * @constructor
     * @private
     */
    function Stats() {
        /**
         * nodes created
         * @type {number}
         * @public
         */
        this.nodesCreated = 0;
        /**
         * nodes deleted
         * @type {number}
         * @public
         */
        this.nodesDeleted = 0;
        /**
         * relationships created
         * @type {number}
         * @public
         */
        this.relationshipsCreated = 0;
        /**
         * relationships deleted
         * @type {number}
         * @public
         */
        this.relationshipsDeleted = 0;
        /**
         * properties set
         * @type {number}
         * @public
         */
        this.propertiesSet = 0;
        /**
         * labels added
         * @type {number}
         * @public
         */
        this.labelsAdded = 0;
        /**
         * labels removed
         * @type {number}
         * @public
         */
        this.labelsRemoved = 0;
        /**
         * indexes added
         * @type {number}
         * @public
         */
        this.indexesAdded = 0;
        /**
         * indexes removed
         * @type {number}
         * @public
         */
        this.indexesRemoved = 0;
        /**
         * constraints added
         * @type {number}
         * @public
         */
        this.constraintsAdded = 0;
        /**
         * constraints removed
         * @type {number}
         * @public
         */
        this.constraintsRemoved = 0;
    }
    return Stats;
}());
resultSummary.Stats = Stats;
/**
 * Get statistical information for a {@link Result}.
 * @access public
 */
var QueryStatistics = /** @class */ (function () {
    /**
     * Structurize the statistics
     * @constructor
     * @param {Object} statistics - Result statistics
     */
    function QueryStatistics(statistics) {
        var _this = this;
        this._stats = {
            nodesCreated: 0,
            nodesDeleted: 0,
            relationshipsCreated: 0,
            relationshipsDeleted: 0,
            propertiesSet: 0,
            labelsAdded: 0,
            labelsRemoved: 0,
            indexesAdded: 0,
            indexesRemoved: 0,
            constraintsAdded: 0,
            constraintsRemoved: 0
        };
        this._systemUpdates = 0;
        Object.keys(statistics).forEach(function (index) {
            // To camelCase
            var camelCaseIndex = index.replace(/(-\w)/g, function (m) { return m[1].toUpperCase(); });
            if (camelCaseIndex in _this._stats) {
                _this._stats[camelCaseIndex] = internal_1$2.util.toNumber(statistics[index]);
            }
            else if (camelCaseIndex === 'systemUpdates') {
                _this._systemUpdates = internal_1$2.util.toNumber(statistics[index]);
            }
            else if (camelCaseIndex === 'containsSystemUpdates') {
                _this._containsSystemUpdates = statistics[index];
            }
            else if (camelCaseIndex === 'containsUpdates') {
                _this._containsUpdates = statistics[index];
            }
        });
        this._stats = Object.freeze(this._stats);
    }
    /**
     * Did the database get updated?
     * @return {boolean}
     */
    QueryStatistics.prototype.containsUpdates = function () {
        var _this = this;
        return this._containsUpdates !== undefined
            ? this._containsUpdates
            : (Object.keys(this._stats).reduce(function (last, current) {
                return last + _this._stats[current];
            }, 0) > 0);
    };
    /**
     * Returns the query statistics updates in a dictionary.
     * @returns {Stats}
     */
    QueryStatistics.prototype.updates = function () {
        return this._stats;
    };
    /**
     * Return true if the system database get updated, otherwise false
     * @returns {boolean} - If the system database get updated or not.
     */
    QueryStatistics.prototype.containsSystemUpdates = function () {
        return this._containsSystemUpdates !== undefined
            ? this._containsSystemUpdates
            : this._systemUpdates > 0;
    };
    /**
     * @returns {number} - Number of system updates
     */
    QueryStatistics.prototype.systemUpdates = function () {
        return this._systemUpdates;
    };
    return QueryStatistics;
}());
resultSummary.QueryStatistics = QueryStatistics;
/**
 * Class for exposing server info from a result.
 * @access public
 */
var ServerInfo = /** @class */ (function () {
    /**
     * Create a ServerInfo instance
     * @constructor
     * @param {Object} serverMeta - Object with serverMeta data
     * @param {Object} connectionInfo - Bolt connection info
     * @param {number} protocolVersion - Bolt Protocol Version
     */
    function ServerInfo(serverMeta, protocolVersion) {
        if (serverMeta != null) {
            /**
             * The server adress
             * @type {string}
             * @public
             */
            this.address = serverMeta.address;
            /**
             * The server user agent string
             * @type {string}
             * @public
             */
            this.agent = serverMeta.version;
        }
        /**
         * The protocol version used by the connection
         * @type {number}
         * @public
         */
        this.protocolVersion = protocolVersion;
    }
    return ServerInfo;
}());
resultSummary.ServerInfo = ServerInfo;
function valueOrDefault$1(key, values, defaultValue) {
    if (defaultValue === void 0) { defaultValue = 0; }
    if (values !== false && key in values) {
        var value = values[key];
        return internal_1$2.util.toNumber(value);
    }
    else {
        return defaultValue;
    }
}
/**
 * The constants for query types
 * @type {{SCHEMA_WRITE: string, WRITE_ONLY: string, READ_ONLY: string, READ_WRITE: string}}
 */
var queryType = {
    READ_ONLY: 'r',
    READ_WRITE: 'rw',
    WRITE_ONLY: 'w',
    SCHEMA_WRITE: 's'
};
resultSummary.queryType = queryType;
resultSummary.default = ResultSummary;

var notificationFilter = {};

Object.defineProperty(notificationFilter, "__esModule", { value: true });
notificationFilter.notificationFilterDisabledClassification = notificationFilter.notificationFilterDisabledCategory = notificationFilter.notificationFilterMinimumSeverityLevel = void 0;
/**
 * @typedef {'WARNING' | 'INFORMATION' | 'OFF'} NotificationFilterMinimumSeverityLevel
 */
/**
 * Constants that represents the minimum Severity level in the {@link NotificationFilter}
 */
var notificationFilterMinimumSeverityLevel = {
    OFF: 'OFF',
    WARNING: 'WARNING',
    INFORMATION: 'INFORMATION'
};
notificationFilter.notificationFilterMinimumSeverityLevel = notificationFilterMinimumSeverityLevel;
Object.freeze(notificationFilterMinimumSeverityLevel);
/**
 * @typedef {'HINT' | 'UNRECOGNIZED' | 'UNSUPPORTED' |'PERFORMANCE' | 'TOPOLOGY' | 'SECURITY' | 'DEPRECATION' | 'GENERIC' | 'SCHEMA'} NotificationFilterDisabledCategory
 */
/**
 * Constants that represents the disabled categories in the {@link NotificationFilter}
 */
var notificationFilterDisabledCategory = {
    HINT: 'HINT',
    UNRECOGNIZED: 'UNRECOGNIZED',
    UNSUPPORTED: 'UNSUPPORTED',
    PERFORMANCE: 'PERFORMANCE',
    TOPOLOGY: 'TOPOLOGY',
    SECURITY: 'SECURITY',
    DEPRECATION: 'DEPRECATION',
    GENERIC: 'GENERIC',
    SCHEMA: 'SCHEMA'
};
notificationFilter.notificationFilterDisabledCategory = notificationFilterDisabledCategory;
Object.freeze(notificationFilterDisabledCategory);
/**
 * @typedef {NotificationFilterDisabledCategory} NotificationFilterDisabledClassification
 * @experimental
 */
/**
 * Constants that represents the disabled classifications in the {@link NotificationFilter}
 *
 * @type {notificationFilterDisabledCategory}
 * @experimental
 */
var notificationFilterDisabledClassification = notificationFilterDisabledCategory;
notificationFilter.notificationFilterDisabledClassification = notificationFilterDisabledClassification;
/**
 * The notification filter object which can be configured in
 * the session and driver creation.
 *
 * Values not defined are interpreted as default.
 *
 * @interface
 */
var NotificationFilter = /** @class */ (function () {
    /**
     * @constructor
     * @private
     */
    function NotificationFilter() {
        /**
         * The minimum level of all notifications to receive.
         *
         * @public
         * @type {?NotificationFilterMinimumSeverityLevel}
         */
        this.minimumSeverityLevel = undefined;
        /**
         * Categories the user would like to opt-out of receiving.
         *
         *
         * This property is equivalent to {@link NotificationFilter#disabledClassifications}
         * and it must not be enabled at same time.
         *
         * @type {?NotificationFilterDisabledCategory[]}
         */
        this.disabledCategories = undefined;
        /**
         * Classifications the user would like to opt-out of receiving.
         *
         * This property is equivalent to {@link NotificationFilter#disabledCategories}
         * and it must not be enabled at same time.
         *
         * @type {?NotificationFilterDisabledClassification[]}
         * @experimental
         */
        this.disabledClassifications = undefined;
        throw new Error('Not implemented');
    }
    return NotificationFilter;
}());
notificationFilter.default = NotificationFilter;

var result = {};

/**
 * 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 __awaiter$h = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$j = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$_ = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a$h;
Object.defineProperty(result, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/promise-function-async */
var result_summary_1 = __importDefault$_(resultSummary);
var internal_1$1 = internal;
var error_1$5 = error;
var EMPTY_CONNECTION_HOLDER = internal_1$1.connectionHolder.EMPTY_CONNECTION_HOLDER;
/**
 * @private
 * @param {Error} error The error
 * @returns {void}
 */
var DEFAULT_ON_ERROR = function (error) {
    // eslint-disable-next-line @typescript-eslint/restrict-plus-operands, @typescript-eslint/no-base-to-string
    console.log('Uncaught error when processing result: ' + error);
};
/**
 * @private
 * @param {ResultSummary} summary
 * @returns {void}
 */
var DEFAULT_ON_COMPLETED = function (summary) { };
/**
 * @private
 * @param {string[]} keys List of keys of the record in the result
 * @return {void}
 */
var DEFAULT_ON_KEYS = function (keys) { };
/**
 * A stream of {@link Record} representing the result of a query.
 * 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 {@link Result#subscribe} function.
 * @access public
 */
var Result = /** @class */ (function () {
    /**
     * Inject the observer to be used.
     * @constructor
     * @access private
     * @param {Promise<observer.ResultStreamObserver>} streamObserverPromise
     * @param {mixed} query - Cypher query to execute
     * @param {Object} parameters - Map with parameters to use in query
     * @param {ConnectionHolder} connectionHolder - to be notified when result is either fully consumed or error happened.
     */
    function Result(streamObserverPromise, query, parameters, connectionHolder, watermarks) {
        if (watermarks === void 0) { watermarks = { high: Number.MAX_VALUE, low: Number.MAX_VALUE }; }
        /**
         * Called when finally the result is done
         *
         * *Should not be combined with {@link Result#subscribe} function.*
         * @param {function()|null} onfinally - function when the promise finished
         * @return {Promise} promise.
         */
        this[_a$h] = 'Result';
        this._stack = captureStacktrace();
        this._streamObserverPromise = streamObserverPromise;
        this._p = null;
        this._query = query;
        this._parameters = parameters !== null && parameters !== void 0 ? parameters : {};
        this._connectionHolder = connectionHolder !== null && connectionHolder !== void 0 ? connectionHolder : EMPTY_CONNECTION_HOLDER;
        this._keys = null;
        this._summary = null;
        this._error = null;
        this._watermarks = watermarks;
    }
    /**
     * Returns a promise for the field keys.
     *
     * *Should not be combined with {@link Result#subscribe} function.*
     *
     * @public
     * @returns {Promise<string[]>} - Field keys, in the order they will appear in records.
     }
     */
    Result.prototype.keys = function () {
        var _this = this;
        if (this._keys !== null) {
            return Promise.resolve(this._keys);
        }
        else if (this._error !== null) {
            return Promise.reject(this._error);
        }
        return new Promise(function (resolve, reject) {
            _this._streamObserverPromise
                .then(function (observer) {
                return observer.subscribe(_this._decorateObserver({
                    onKeys: function (keys) { return resolve(keys); },
                    onError: function (err) { return reject(err); }
                }));
            })
                .catch(reject);
        });
    };
    /**
     * Returns a promise for the result summary.
     *
     * *Should not be combined with {@link Result#subscribe} function.*
     *
     * @public
     * @returns {Promise<ResultSummary<T>>} - Result summary.
     *
     */
    Result.prototype.summary = function () {
        var _this = this;
        if (this._summary !== null) {
            // This type casting is needed since we are defining the number type of
            // summary in Result template
            return Promise.resolve(this._summary);
        }
        else if (this._error !== null) {
            return Promise.reject(this._error);
        }
        return new Promise(function (resolve, reject) {
            _this._streamObserverPromise
                .then(function (o) {
                o.cancel();
                o.subscribe(_this._decorateObserver({
                    // This type casting is needed since we are defining the number type of
                    // summary in Result template
                    onCompleted: function (summary) { return resolve(summary); },
                    onError: function (err) { return reject(err); }
                }));
            })
                .catch(reject);
        });
    };
    /**
     * Create and return new Promise
     *
     * @private
     * @return {Promise} new Promise.
     */
    Result.prototype._getOrCreatePromise = function () {
        var _this = this;
        if (this._p == null) {
            this._p = new Promise(function (resolve, reject) {
                var records = [];
                var observer = {
                    onNext: function (record) {
                        records.push(record);
                    },
                    onCompleted: function (summary) {
                        resolve({ records: records, summary: summary });
                    },
                    onError: function (error) {
                        reject(error);
                    }
                };
                _this.subscribe(observer);
            });
        }
        return this._p;
    };
    /**
     * Provides a async iterator over the records in the result.
     *
     * *Should not be combined with {@link Result#subscribe} or {@link Result#then} functions.*
     *
     * @public
     * @returns {PeekableAsyncIterator<Record<R>, ResultSummary>} The async iterator for the Results
     */
    Result.prototype[Symbol.asyncIterator] = function () {
        var _this = this;
        if (!this.isOpen()) {
            var error_2 = (0, error_1$5.newError)('Result is already consumed');
            return {
                next: function () { return Promise.reject(error_2); },
                peek: function () { return Promise.reject(error_2); }
            };
        }
        var state = { paused: true, firstRun: true, finished: false };
        var controlFlow = function () {
            var _b, _c;
            if (state.streaming == null) {
                return;
            }
            var size = (_c = (_b = state.queuedObserver) === null || _b === void 0 ? void 0 : _b.size) !== null && _c !== void 0 ? _c : 0;
            var queueSizeIsOverHighOrEqualWatermark = size >= _this._watermarks.high;
            var queueSizeIsBellowOrEqualLowWatermark = size <= _this._watermarks.low;
            if (queueSizeIsOverHighOrEqualWatermark && !state.paused) {
                state.paused = true;
                state.streaming.pause();
            }
            else if ((queueSizeIsBellowOrEqualLowWatermark && state.paused) || (state.firstRun && !queueSizeIsOverHighOrEqualWatermark)) {
                state.firstRun = false;
                state.paused = false;
                state.streaming.resume();
            }
        };
        var initializeObserver = function () { return __awaiter$h(_this, void 0, void 0, function () {
            var _b;
            return __generator$j(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!(state.queuedObserver === undefined)) return [3 /*break*/, 2];
                        state.queuedObserver = this._createQueuedResultObserver(controlFlow);
                        _b = state;
                        return [4 /*yield*/, this._subscribe(state.queuedObserver, true).catch(function () { return undefined; })];
                    case 1:
                        _b.streaming = _c.sent();
                        controlFlow();
                        _c.label = 2;
                    case 2: return [2 /*return*/, state.queuedObserver];
                }
            });
        }); };
        var assertSummary = function (summary) {
            if (summary === undefined) {
                throw (0, error_1$5.newError)('InvalidState: Result stream finished without Summary', error_1$5.PROTOCOL_ERROR);
            }
            return true;
        };
        return {
            next: function () { return __awaiter$h(_this, void 0, void 0, function () {
                var queuedObserver, next;
                return __generator$j(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (state.finished) {
                                if (assertSummary(state.summary)) {
                                    return [2 /*return*/, { done: true, value: state.summary }];
                                }
                            }
                            return [4 /*yield*/, initializeObserver()];
                        case 1:
                            queuedObserver = _b.sent();
                            return [4 /*yield*/, queuedObserver.dequeue()];
                        case 2:
                            next = _b.sent();
                            if (next.done === true) {
                                state.finished = next.done;
                                state.summary = next.value;
                            }
                            return [2 /*return*/, next];
                    }
                });
            }); },
            return: function (value) { return __awaiter$h(_this, void 0, void 0, function () {
                var queuedObserver, last;
                var _b;
                return __generator$j(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (state.finished) {
                                if (assertSummary(state.summary)) {
                                    return [2 /*return*/, { done: true, value: value !== null && value !== void 0 ? value : state.summary }];
                                }
                            }
                            (_b = state.streaming) === null || _b === void 0 ? void 0 : _b.cancel();
                            return [4 /*yield*/, initializeObserver()];
                        case 1:
                            queuedObserver = _c.sent();
                            return [4 /*yield*/, queuedObserver.dequeueUntilDone()];
                        case 2:
                            last = _c.sent();
                            state.finished = true;
                            last.value = value !== null && value !== void 0 ? value : last.value;
                            state.summary = last.value;
                            return [2 /*return*/, last];
                    }
                });
            }); },
            peek: function () { return __awaiter$h(_this, void 0, void 0, function () {
                var queuedObserver;
                return __generator$j(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (state.finished) {
                                if (assertSummary(state.summary)) {
                                    return [2 /*return*/, { done: true, value: state.summary }];
                                }
                            }
                            return [4 /*yield*/, initializeObserver()];
                        case 1:
                            queuedObserver = _b.sent();
                            return [4 /*yield*/, queuedObserver.head()];
                        case 2: return [2 /*return*/, _b.sent()];
                    }
                });
            }); }
        };
    };
    /**
     * Waits for all results and calls the passed in function with the results.
     *
     * *Should not be combined with {@link Result#subscribe} 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.
     */
    Result.prototype.then = function (onFulfilled, onRejected) {
        return this._getOrCreatePromise().then(onFulfilled, onRejected);
    };
    /**
     * Catch errors when using promises.
     *
     * *Should not be combined with {@link Result#subscribe} function.*
     *
     * @param {function(error: Neo4jError)} onRejected - Function to be called upon errors.
     * @return {Promise} promise.
     */
    Result.prototype.catch = function (onRejected) {
        return this._getOrCreatePromise().catch(onRejected);
    };
    Result.prototype.finally = function (onfinally) {
        return this._getOrCreatePromise().finally(onfinally);
    };
    /**
     * 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(keys: string[])} observer.onKeys - handle stream head, the field keys.
     * @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 {void}
     */
    Result.prototype.subscribe = function (observer) {
        this._subscribe(observer)
            .catch(function () { });
    };
    /**
     * Check if this result is active, i.e., neither a summary nor an error has been received by the result.
     * @return {boolean} `true` when neither a summary or nor an error has been received by the result.
     */
    Result.prototype.isOpen = function () {
        return this._summary === null && this._error === null;
    };
    /**
     * 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.
     *
     * @access private
     * @param {ResultObserver} observer The observer to send records to.
     * @param {boolean} paused The flag to indicate if the stream should be started paused
     * @returns {Promise<observer.ResultStreamObserver>} The result stream observer.
     */
    Result.prototype._subscribe = function (observer, paused) {
        if (paused === void 0) { paused = false; }
        var _observer = this._decorateObserver(observer);
        return this._streamObserverPromise
            .then(function (o) {
            if (paused) {
                o.pause();
            }
            o.subscribe(_observer);
            return o;
        })
            .catch(function (error) {
            if (_observer.onError != null) {
                _observer.onError(error);
            }
            return Promise.reject(error);
        });
    };
    /**
     * Decorates the ResultObserver with the necessary methods.
     *
     * @access private
     * @param {ResultObserver} observer The ResultObserver to decorate.
     * @returns The decorated result observer
     */
    Result.prototype._decorateObserver = function (observer) {
        var _this = this;
        var _b, _c, _d;
        var onCompletedOriginal = (_b = observer.onCompleted) !== null && _b !== void 0 ? _b : DEFAULT_ON_COMPLETED;
        var onErrorOriginal = (_c = observer.onError) !== null && _c !== void 0 ? _c : DEFAULT_ON_ERROR;
        var onKeysOriginal = (_d = observer.onKeys) !== null && _d !== void 0 ? _d : DEFAULT_ON_KEYS;
        var onCompletedWrapper = function (metadata) {
            _this._releaseConnectionAndGetSummary(metadata).then(function (summary) {
                if (_this._summary !== null) {
                    return onCompletedOriginal.call(observer, _this._summary);
                }
                _this._summary = summary;
                return onCompletedOriginal.call(observer, summary);
            }).catch(onErrorOriginal);
        };
        var onErrorWrapper = function (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
            _this._connectionHolder.releaseConnection().then(function () {
                replaceStacktrace(error, _this._stack);
                _this._error = error;
                onErrorOriginal.call(observer, error);
            }).catch(onErrorOriginal);
        };
        var onKeysWrapper = function (keys) {
            _this._keys = keys;
            return onKeysOriginal.call(observer, keys);
        };
        return {
            onNext: (observer.onNext != null) ? observer.onNext.bind(observer) : undefined,
            onKeys: onKeysWrapper,
            onCompleted: onCompletedWrapper,
            onError: onErrorWrapper
        };
    };
    /**
     * Signals the stream observer that the future records should be discarded on the server.
     *
     * @protected
     * @since 4.0.0
     * @returns {void}
     */
    Result.prototype._cancel = function () {
        if (this._summary === null && this._error === null) {
            this._streamObserverPromise.then(function (o) { return o.cancel(); })
                .catch(function () { });
        }
    };
    /**
     * @access private
     * @param metadata
     * @returns
     */
    Result.prototype._releaseConnectionAndGetSummary = function (metadata) {
        var _b = internal_1$1.util.validateQueryAndParameters(this._query, this._parameters, {
            skipAsserts: true
        }), query = _b.validatedQuery, parameters = _b.params;
        var connectionHolder = this._connectionHolder;
        return connectionHolder
            .getConnection()
            .then(
        // onFulfilled:
        function (connection) {
            return connectionHolder
                .releaseConnection()
                .then(function () {
                return connection === null || connection === void 0 ? void 0 : connection.getProtocolVersion();
            });
        }, 
        // onRejected:
        function (_) { return undefined; })
            .then(function (protocolVersion) {
            return new result_summary_1.default(query, parameters, metadata, protocolVersion);
        });
    };
    /**
     * @access private
     */
    Result.prototype._createQueuedResultObserver = function (onQueueSizeChanged) {
        var _this = this;
        function createResolvablePromise() {
            var resolvablePromise = {};
            resolvablePromise.promise = new Promise(function (resolve, reject) {
                resolvablePromise.resolve = resolve;
                resolvablePromise.reject = reject;
            });
            return resolvablePromise;
        }
        function isError(elementOrError) {
            return elementOrError instanceof Error;
        }
        function dequeue() {
            return __awaiter$h(this, void 0, void 0, function () {
                var element;
                var _b;
                return __generator$j(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            if (buffer.length > 0) {
                                element = (_b = buffer.shift()) !== null && _b !== void 0 ? _b : (0, error_1$5.newError)('Unexpected empty buffer', error_1$5.PROTOCOL_ERROR);
                                onQueueSizeChanged();
                                if (isError(element)) {
                                    throw element;
                                }
                                return [2 /*return*/, element];
                            }
                            promiseHolder.resolvable = createResolvablePromise();
                            return [4 /*yield*/, promiseHolder.resolvable.promise];
                        case 1: return [2 /*return*/, _c.sent()];
                    }
                });
            });
        }
        var buffer = [];
        var promiseHolder = { resolvable: null };
        var observer = {
            onNext: function (record) {
                observer._push({ done: false, value: record });
            },
            onCompleted: function (summary) {
                observer._push({ done: true, value: summary });
            },
            onError: function (error) {
                observer._push(error);
            },
            _push: function (element) {
                if (promiseHolder.resolvable !== null) {
                    var resolvable = promiseHolder.resolvable;
                    promiseHolder.resolvable = null;
                    if (isError(element)) {
                        resolvable.reject(element);
                    }
                    else {
                        resolvable.resolve(element);
                    }
                }
                else {
                    buffer.push(element);
                    onQueueSizeChanged();
                }
            },
            dequeue: dequeue,
            dequeueUntilDone: function () { return __awaiter$h(_this, void 0, void 0, function () {
                var element;
                return __generator$j(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            return [4 /*yield*/, dequeue()];
                        case 1:
                            element = _b.sent();
                            if (element.done === true) {
                                return [2 /*return*/, element];
                            }
                            return [3 /*break*/, 0];
                        case 2: return [2 /*return*/];
                    }
                });
            }); },
            head: function () { return __awaiter$h(_this, void 0, void 0, function () {
                var element, element, error_3;
                return __generator$j(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (buffer.length > 0) {
                                element = buffer[0];
                                if (isError(element)) {
                                    throw element;
                                }
                                return [2 /*return*/, element];
                            }
                            promiseHolder.resolvable = createResolvablePromise();
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 3, 4, 5]);
                            return [4 /*yield*/, promiseHolder.resolvable.promise];
                        case 2:
                            element = _b.sent();
                            buffer.unshift(element);
                            return [2 /*return*/, element];
                        case 3:
                            error_3 = _b.sent();
                            buffer.unshift(error_3);
                            throw error_3;
                        case 4:
                            onQueueSizeChanged();
                            return [7 /*endfinally*/];
                        case 5: return [2 /*return*/];
                    }
                });
            }); },
            get size() {
                return buffer.length;
            }
        };
        return observer;
    };
    return Result;
}());
_a$h = Symbol.toStringTag;
function captureStacktrace() {
    var error = new Error('');
    if (error.stack != null) {
        return error.stack.replace(/^Error(\n\r)*/, ''); // we don't need the 'Error\n' part, if only it exists
    }
    return null;
}
/**
 * @private
 * @param {Error} error The error
 * @param {string| null} newStack The newStack
 * @returns {void}
 */
function replaceStacktrace(error, newStack) {
    if (newStack != null) {
        // Error.prototype.toString() concatenates error.name and error.message nicely
        // then we add the rest of the stack trace
        // eslint-disable-next-line @typescript-eslint/no-base-to-string
        error.stack = error.toString() + '\n' + newStack;
    }
}
result.default = Result;

var resultEager = {};

/**
 * 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(resultEager, "__esModule", { value: true });
/**
 * Represents the fully streamed result
 */
var EagerResult = /** @class */ (function () {
    /**
     * @constructor
     * @private
     * @param {string[]} keys The records keys
     * @param {Record[]} records The resulted records
     * @param {ResultSummary[]} summary The result Summary
     */
    function EagerResult(keys, records, summary) {
        /**
         * Field keys, in the order the fields appear in the records.
         * @type {string[]}
         */
        this.keys = keys;
        /**
         * Field records, in the order the records arrived from the server.
         * @type {Record[]}
         */
        this.records = records;
        /**
         * Field summary
         * @type {ResultSummary}
         */
        this.summary = summary;
    }
    return EagerResult;
}());
resultEager.default = EagerResult;

var connectionProvider$1 = {};

/**
 * 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 @typescript-eslint/promise-function-async */
Object.defineProperty(connectionProvider$1, "__esModule", { value: true });
connectionProvider$1.Releasable = void 0;
/**
 * Interface define a releasable resource shape
 *
 * @private
 * @interface
 */
var Releasable = /** @class */ (function () {
    function Releasable() {
    }
    /**
     * @returns {Promise<void>}
     */
    Releasable.prototype.release = function () {
        throw new Error('Not implemented');
    };
    return Releasable;
}());
connectionProvider$1.Releasable = Releasable;
/**
 * Interface define a common way to acquire a connection
 *
 * @private
 */
var ConnectionProvider = /** @class */ (function () {
    function ConnectionProvider() {
    }
    /**
     * This method acquires a connection against the specified database.
     *
     * Access mode and Bookmarks only applies to routing driver. Access mode only
     * differentiates the target server for the connection, where WRITE selects a
     * WRITER server, whereas READ selects a READ server. Bookmarks, when specified,
     * is only passed to the routing discovery procedure, for the system database to
     * synchronize on creation of databases and is never used in direct drivers.
     *
     * @param {object} param - object parameter
     * @property {string} param.accessMode - the access mode for the to-be-acquired connection
     * @property {string} param.database - the target database for the to-be-acquired connection
     * @property {Bookmarks} param.bookmarks - the bookmarks to send to routing discovery
     * @property {string} param.impersonatedUser - the impersonated user
     * @property {function (databaseName:string)} param.onDatabaseNameResolved - Callback called when the database name get resolved
     * @property {AuthToken} param.auth - auth token used to authorize for connection acquisition
     * @property {string} param.homeDb - the driver's best guess at the current home database for the user
     * @returns {Promise<Connection>}
     */
    ConnectionProvider.prototype.acquireConnection = function (param) {
        throw Error('Not implemented');
    };
    /**
     * This method checks whether the backend database supports multi database functionality
     * by checking protocol handshake result.
     *
     * @returns {Promise<boolean>}
     */
    ConnectionProvider.prototype.supportsMultiDb = function () {
        throw Error('Not implemented');
    };
    /**
     * This method checks whether the backend database supports transaction config functionality
     * by checking protocol handshake result.
     *
     * @returns {Promise<boolean>}
     */
    ConnectionProvider.prototype.supportsTransactionConfig = function () {
        throw Error('Not implemented');
    };
    /**
     * This method checks whether the backend database supports user impersonation functionality
     * by checking protocol handshake result.
     *
     * @returns {Promise<boolean>}
     */
    ConnectionProvider.prototype.supportsUserImpersonation = function () {
        throw Error('Not implemented');
    };
    /**
     * This method checks whether the driver session re-auth functionality
     * by checking protocol handshake result
     *
     * @returns {Promise<boolean>}
     */
    ConnectionProvider.prototype.supportsSessionAuth = function () {
        throw Error('Not implemented');
    };
    ConnectionProvider.prototype.SSREnabled = function () {
        return false;
    };
    /**
     * This method verifies the connectivity of the database by trying to acquire a connection
     * for each server available in the cluster.
     *
     * @param {object} param - object parameter
     * @property {string} param.database - the target database for the to-be-acquired connection
     * @property {string} param.accessMode - the access mode for the to-be-acquired connection
     *
     * @returns {Promise<ServerInfo>} promise resolved with server info or rejected with error.
     */
    ConnectionProvider.prototype.verifyConnectivityAndGetServerInfo = function (param) {
        throw Error('Not implemented');
    };
    /**
     * This method verifies the authorization credentials work by trying to acquire a connection
     * to one of the servers with the given credentials.
     *
     * @param {object} param - object parameter
     * @property {AuthToken} param.auth - the target auth for the to-be-acquired connection
     * @property {string} param.database - the target database for the to-be-acquired connection
     * @property {string} param.accessMode - the access mode for the to-be-acquired connection
     *
     * @returns {Promise<boolean>} promise resolved with true if succeed, false if failed with
     *  authentication issue and rejected with error if non-authentication error happens.
     */
    ConnectionProvider.prototype.verifyAuthentication = function (param) {
        throw Error('Not implemented');
    };
    /**
     * Returns the protocol version negotiated via handshake.
     *
     * Note that this function call _always_ causes a round-trip to the server.
     *
     * @returns {Promise<number>} the protocol version negotiated via handshake.
     * @throws {Error} When protocol negotiation fails
     */
    ConnectionProvider.prototype.getNegotiatedProtocolVersion = function () {
        throw Error('Not Implemented');
    };
    /**
     * Closes this connection provider along with its internals (connections, pools, etc.)
     *
     * @returns {Promise<void>}
     */
    ConnectionProvider.prototype.close = function () {
        throw Error('Not implemented');
    };
    return ConnectionProvider;
}());
connectionProvider$1.default = ConnectionProvider;

var connection$2 = {};

/**
 * 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 @typescript-eslint/promise-function-async */
Object.defineProperty(connection$2, "__esModule", { value: true });
/**
 * Interface which defines a connection for the core driver object.
 *
 *
 * This connection exposes only methods used by the code module.
 * Methods with connection implementation details can be defined and used
 * by the implementation layer.
 *
 * @private
 * @interface
 */
var Connection$1 = /** @class */ (function () {
    function Connection() {
    }
    /**
     *
     * @param config
     * @returns {ResultStreamObserver}
     */
    Connection.prototype.beginTransaction = function (config) {
        throw new Error('Not implemented');
    };
    /**
     *
     * @param query
     * @param parameters
     * @param config
     * @returns {ResultStreamObserver}
     */
    Connection.prototype.run = function (query, parameters, config) {
        throw new Error('Not implemented');
    };
    /**
     *
     * @param config
     * @returns {ResultStreamObserver}
     */
    Connection.prototype.commitTransaction = function (config) {
        throw new Error('Not implemented');
    };
    /**
     *
     * @param config
     * @returns {ResultStreamObserver}
     */
    Connection.prototype.rollbackTransaction = function (config) {
        throw new Error('Not implemented');
    };
    /**
     *
     * @returns {Promise<void>}
     */
    Connection.prototype.resetAndFlush = function () {
        throw new Error('Not implemented');
    };
    /**
     *
     * @returns {boolean}
     */
    Connection.prototype.isOpen = function () {
        throw new Error('Not implemented');
    };
    /**
     *
     * @returns {number}
     */
    Connection.prototype.getProtocolVersion = function () {
        throw new Error('Not implemented');
    };
    /**
     *
     * @returns {boolean}
     */
    Connection.prototype.hasOngoingObservableRequests = function () {
        throw new Error('Not implemented');
    };
    return Connection;
}());
connection$2.default = Connection$1;

var transaction = {};

/**
 * 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 __awaiter$g = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$i = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$Z = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(transaction, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/promise-function-async */
var util_1$2 = util$4;
var connection_holder_1$1 = connectionHolder$1;
var bookmarks_1$2 = bookmarks$1;
var tx_config_1$1 = txConfig$1;
var observers_1$1 = observers;
var error_1$4 = error;
var result_1$1 = __importDefault$Z(result);
/**
 * Represents a transaction in the Neo4j database.
 *
 * @access public
 */
var Transaction = /** @class */ (function () {
    /**
     * @constructor
     * @param {object} args
     * @param {ConnectionHolder} args.connectionHolder - the connection holder to get connection from.
     * @param {function()} args.onClose - Function to be called when transaction is committed or rolled back.
     * @param {function(bookmarks: Bookmarks)} args.onBookmarks callback invoked when new bookmark is produced.
     * @param {function()} args.onConnection - Function to be called when a connection is obtained to ensure the conneciton
     * is not yet released.
     * @param {boolean} args.reactive whether this transaction generates reactive streams
     * @param {number} args.fetchSize - the record fetch size in each pulling batch.
     * @param {string} args.impersonatedUser - The name of the user which should be impersonated for the duration of the session.
     * @param {number} args.highRecordWatermark - The high watermark for the record buffer.
     * @param {number} args.lowRecordWatermark - The low watermark for the record buffer.
     * @param {NotificationFilter} args.notificationFilter - The notification filter used for this transaction.
     * @param {NonAutoCommitApiTelemetryConfig} args.apiTelemetryConfig - The api telemetry configuration. Empty/Null for disabling telemetry
     */
    function Transaction(_a) {
        var connectionHolder = _a.connectionHolder, onClose = _a.onClose, onBookmarks = _a.onBookmarks, onConnection = _a.onConnection, reactive = _a.reactive, fetchSize = _a.fetchSize, impersonatedUser = _a.impersonatedUser, highRecordWatermark = _a.highRecordWatermark, lowRecordWatermark = _a.lowRecordWatermark, notificationFilter = _a.notificationFilter, apiTelemetryConfig = _a.apiTelemetryConfig;
        var _this = this;
        this._connectionHolder = connectionHolder;
        this._reactive = reactive;
        this._state = _states$1.ACTIVE;
        this._onClose = onClose;
        this._onBookmarks = onBookmarks;
        this._onConnection = onConnection;
        this._onError = this._onErrorCallback.bind(this);
        this._fetchSize = fetchSize;
        this._onComplete = this._onCompleteCallback.bind(this);
        this._results = [];
        this._impersonatedUser = impersonatedUser;
        this._lowRecordWatermak = lowRecordWatermark;
        this._highRecordWatermark = highRecordWatermark;
        this._bookmarks = bookmarks_1$2.Bookmarks.empty();
        this._notificationFilter = notificationFilter;
        this._apiTelemetryConfig = apiTelemetryConfig;
        this._acceptActive = function () { }; // satisfy DenoJS
        this._activePromise = new Promise(function (resolve, reject) {
            _this._acceptActive = resolve;
        });
    }
    /**
     * @private
     * @param {Bookmarks | string |  string []} bookmarks
     * @param {TxConfig} txConfig
     * @param {Object} events List of observers to events
     * @returns {void}
     */
    Transaction.prototype._begin = function (getBookmarks, txConfig, events) {
        var _this = this;
        this._connectionHolder
            .getConnection()
            .then(function (connection) { return __awaiter$g(_this, void 0, void 0, function () {
            var _a;
            var _this = this;
            return __generator$i(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this._onConnection();
                        if (!(connection != null)) return [3 /*break*/, 2];
                        _a = this;
                        return [4 /*yield*/, getBookmarks()];
                    case 1:
                        _a._bookmarks = _b.sent();
                        return [2 /*return*/, connection.beginTransaction({
                                bookmarks: this._bookmarks,
                                txConfig: txConfig,
                                mode: this._connectionHolder.mode(),
                                database: this._connectionHolder.database(),
                                impersonatedUser: this._impersonatedUser,
                                notificationFilter: this._notificationFilter,
                                apiTelemetryConfig: this._apiTelemetryConfig,
                                beforeError: function (error) {
                                    if (events != null) {
                                        events.onError(error);
                                    }
                                    _this._onError(error).catch(function () { });
                                },
                                afterComplete: function (metadata) {
                                    if (events != null) {
                                        events.onComplete(metadata);
                                    }
                                    if (metadata.db !== undefined && ((events === null || events === void 0 ? void 0 : events.onDB) != null)) {
                                        events.onDB(metadata.db);
                                    }
                                    _this._onComplete(metadata);
                                }
                            })];
                    case 2: throw (0, error_1$4.newError)('No connection available');
                }
            });
        }); })
            .catch(function (error) {
            if (events != null) {
                events.onError(error);
            }
            _this._onError(error).catch(function () { });
        })
            // It should make the transaction active anyway
            // further errors will be treated by the existing
            // observers
            .finally(function () { return _this._acceptActive(); });
    };
    /**
     * Run Cypher query
     * Could be called with a query object i.e.: `{text: "MATCH ...", parameters: {param: 1}}`
     * or with the query and parameters as separate arguments.
     * @param {mixed} query - Cypher query to execute
     * @param {Object} parameters - Map with parameters to use in query
     * @return {Result} New Result
     */
    Transaction.prototype.run = function (query, parameters) {
        var _a = (0, util_1$2.validateQueryAndParameters)(query, parameters), validatedQuery = _a.validatedQuery, params = _a.params;
        var result = this._state.run(validatedQuery, params, {
            connectionHolder: this._connectionHolder,
            onError: this._onError,
            onComplete: this._onComplete,
            onConnection: this._onConnection,
            reactive: this._reactive,
            fetchSize: this._fetchSize,
            highRecordWatermark: this._highRecordWatermark,
            lowRecordWatermark: this._lowRecordWatermak,
            preparationJob: this._activePromise
        });
        this._results.push(result);
        return result;
    };
    /**
     * Commits the transaction and returns the result.
     *
     * After committing the transaction can no longer be used.
     *
     * @returns {Promise<void>} An empty promise if committed successfully or error if any error happened during commit.
     */
    Transaction.prototype.commit = function () {
        var _this = this;
        var committed = this._state.commit({
            connectionHolder: this._connectionHolder,
            onError: this._onError,
            onComplete: function (meta) { return _this._onCompleteCallback(meta, _this._bookmarks); },
            onConnection: this._onConnection,
            pendingResults: this._results,
            preparationJob: this._activePromise
        });
        this._state = committed.state;
        // clean up
        this._onClose();
        return new Promise(function (resolve, reject) {
            committed.result.subscribe({
                onCompleted: function () { return resolve(); },
                onError: function (error) { return reject(error); }
            });
        });
    };
    /**
     * Rollbacks the transaction.
     *
     * After rolling back, the transaction can no longer be used.
     *
     * @returns {Promise<void>} An empty promise if rolled back successfully or error if any error happened during
     * rollback.
     */
    Transaction.prototype.rollback = function () {
        var rolledback = this._state.rollback({
            connectionHolder: this._connectionHolder,
            onError: this._onError,
            onComplete: this._onComplete,
            onConnection: this._onConnection,
            pendingResults: this._results,
            preparationJob: this._activePromise
        });
        this._state = rolledback.state;
        // clean up
        this._onClose();
        return new Promise(function (resolve, reject) {
            rolledback.result.subscribe({
                onCompleted: function () { return resolve(); },
                onError: function (error) { return reject(error); }
            });
        });
    };
    /**
     * Check if this transaction is active, which means commit and rollback did not happen.
     * @return {boolean} `true` when not committed and not rolled back, `false` otherwise.
     */
    Transaction.prototype.isOpen = function () {
        return this._state === _states$1.ACTIVE;
    };
    /**
     * Closes the transaction
     *
     * This method will roll back the transaction if it is not already committed or rolled back.
     *
     * @returns {Promise<void>} An empty promise if closed successfully or error if any error happened during
     */
    Transaction.prototype.close = function () {
        return __awaiter$g(this, void 0, void 0, function () {
            return __generator$i(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.isOpen()) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.rollback()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    // eslint-disable-next-line
    // @ts-ignore
    Transaction.prototype[Symbol.asyncDispose] = function () {
        return this.close();
    };
    Transaction.prototype._onErrorCallback = function (error) {
        // error will be "acknowledged" by sending a RESET message
        // database will then forget about this transaction and cleanup all corresponding resources
        // it is thus safe to move this transaction to a FAILED state and disallow any further interactions with it
        if (this._state === _states$1.FAILED) {
            // already failed, nothing to do
            // if we call onError for each result again, we might run into an infinite loop, that causes an OOM eventually
            return Promise.resolve(null);
        }
        this._state = _states$1.FAILED;
        this._onClose();
        this._results.forEach(function (result) {
            if (result.isOpen()) {
                // @ts-expect-error
                result._streamObserverPromise
                    .then(function (resultStreamObserver) { return resultStreamObserver.onError(error); })
                    // Nothing to do since we don't have a observer to notify the error
                    // the result will be already broke in other ways.
                    .catch(function (_) { });
            }
        });
        // release connection back to the pool
        return this._connectionHolder.releaseConnection();
    };
    /**
     * @private
     * @param {object} meta The meta with bookmarks
     * @returns {void}
     */
    Transaction.prototype._onCompleteCallback = function (meta, previousBookmarks) {
        this._onBookmarks(new bookmarks_1$2.Bookmarks(meta === null || meta === void 0 ? void 0 : meta.bookmark), previousBookmarks !== null && previousBookmarks !== void 0 ? previousBookmarks : bookmarks_1$2.Bookmarks.empty(), meta === null || meta === void 0 ? void 0 : meta.db);
    };
    return Transaction;
}());
var _states$1 = {
    // The transaction is running with no explicit success or failure marked
    ACTIVE: {
        commit: function (_a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError, onComplete = _a.onComplete, onConnection = _a.onConnection, pendingResults = _a.pendingResults, preparationJob = _a.preparationJob;
            return {
                result: finishTransaction(true, connectionHolder, onError, onComplete, onConnection, pendingResults, preparationJob),
                state: _states$1.SUCCEEDED
            };
        },
        rollback: function (_a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError, onComplete = _a.onComplete, onConnection = _a.onConnection, pendingResults = _a.pendingResults, preparationJob = _a.preparationJob;
            return {
                result: finishTransaction(false, connectionHolder, onError, onComplete, onConnection, pendingResults, preparationJob),
                state: _states$1.ROLLED_BACK
            };
        },
        run: function (query, parameters, _a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError, onComplete = _a.onComplete, onConnection = _a.onConnection, reactive = _a.reactive, fetchSize = _a.fetchSize, highRecordWatermark = _a.highRecordWatermark, lowRecordWatermark = _a.lowRecordWatermark, preparationJob = _a.preparationJob;
            // RUN in explicit transaction can't contain bookmarks and transaction configuration
            // No need to include mode and database name as it shall be included in begin
            var requirements = preparationJob !== null && preparationJob !== void 0 ? preparationJob : Promise.resolve();
            var observerPromise = connectionHolder.getConnection()
                .then(function (conn) { return requirements.then(function () { return conn; }); })
                .then(function (conn) {
                onConnection();
                if (conn != null) {
                    return conn.run(query, parameters, {
                        bookmarks: bookmarks_1$2.Bookmarks.empty(),
                        txConfig: tx_config_1$1.TxConfig.empty(),
                        beforeError: onError,
                        afterComplete: onComplete,
                        reactive: reactive,
                        fetchSize: fetchSize,
                        highRecordWatermark: highRecordWatermark,
                        lowRecordWatermark: lowRecordWatermark
                    });
                }
                else {
                    throw (0, error_1$4.newError)('No connection available');
                }
            })
                .catch(function (error) { return new observers_1$1.FailedObserver({ error: error, onError: onError }); });
            return newCompletedResult(observerPromise, query, parameters, connectionHolder, highRecordWatermark, lowRecordWatermark);
        }
    },
    // An error has occurred, transaction can no longer be used and no more messages will
    // be sent for this transaction.
    FAILED: {
        commit: function (_a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return {
                result: newCompletedResult(new observers_1$1.FailedObserver({
                    error: (0, error_1$4.newError)('Cannot commit this transaction, because it has been rolled back either because of an error or explicit termination.'),
                    onError: onError
                }), 'COMMIT', {}, connectionHolder, 0, // high watermark
                0 // low watermark
                ),
                state: _states$1.FAILED
            };
        },
        rollback: function (_a) {
            var connectionHolder = _a.connectionHolder; _a.onError; _a.onComplete;
            return {
                result: newCompletedResult(new observers_1$1.CompletedObserver(), 'ROLLBACK', {}, connectionHolder, 0, // high watermark
                0 // low watermark
                ),
                state: _states$1.FAILED
            };
        },
        run: function (query, parameters, _a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return newCompletedResult(new observers_1$1.FailedObserver({
                error: (0, error_1$4.newError)('Cannot run query in this transaction, because it has been rolled back either because of an error or explicit termination.'),
                onError: onError
            }), query, parameters, connectionHolder, 0, // high watermark
            0 // low watermark
            );
        }
    },
    // This transaction has successfully committed
    SUCCEEDED: {
        commit: function (_a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return {
                result: newCompletedResult(new observers_1$1.FailedObserver({
                    error: (0, error_1$4.newError)('Cannot commit this transaction, because it has already been committed.'),
                    onError: onError
                }), 'COMMIT', {}, connection_holder_1$1.EMPTY_CONNECTION_HOLDER, 0, // high watermark
                0 // low watermark
                ),
                state: _states$1.SUCCEEDED,
                connectionHolder: connectionHolder
            };
        },
        rollback: function (_a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return {
                result: newCompletedResult(new observers_1$1.FailedObserver({
                    error: (0, error_1$4.newError)('Cannot rollback this transaction, because it has already been committed.'),
                    onError: onError
                }), 'ROLLBACK', {}, connection_holder_1$1.EMPTY_CONNECTION_HOLDER, 0, // high watermark
                0 // low watermark
                ),
                state: _states$1.SUCCEEDED,
                connectionHolder: connectionHolder
            };
        },
        run: function (query, parameters, _a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return newCompletedResult(new observers_1$1.FailedObserver({
                error: (0, error_1$4.newError)('Cannot run query in this transaction, because it has already been committed.'),
                onError: onError
            }), query, parameters, connectionHolder, 0, // high watermark
            0 // low watermark
            );
        }
    },
    // This transaction has been rolled back
    ROLLED_BACK: {
        commit: function (_a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return {
                result: newCompletedResult(new observers_1$1.FailedObserver({
                    error: (0, error_1$4.newError)('Cannot commit this transaction, because it has already been rolled back.'),
                    onError: onError
                }), 'COMMIT', {}, connectionHolder, 0, // high watermark
                0 // low watermark
                ),
                state: _states$1.ROLLED_BACK
            };
        },
        rollback: function (_a) {
            var connectionHolder = _a.connectionHolder; _a.onError; _a.onComplete;
            return {
                result: newCompletedResult(new observers_1$1.FailedObserver({
                    error: (0, error_1$4.newError)('Cannot rollback this transaction, because it has already been rolled back.')
                }), 'ROLLBACK', {}, connectionHolder, 0, // high watermark
                0 // low watermark
                ),
                state: _states$1.ROLLED_BACK
            };
        },
        run: function (query, parameters, _a) {
            var connectionHolder = _a.connectionHolder, onError = _a.onError; _a.onComplete;
            return newCompletedResult(new observers_1$1.FailedObserver({
                error: (0, error_1$4.newError)('Cannot run query in this transaction, because it has already been rolled back.'),
                onError: onError
            }), query, parameters, connectionHolder, 0, // high watermark
            0 // low watermark
            );
        }
    }
};
/**
 *
 * @param {boolean} commit
 * @param {ConnectionHolder} connectionHolder
 * @param {function(err:Error): any} onError
 * @param {function(metadata:object): any} onComplete
 * @param {function() : any} onConnection
 * @param {list<Result>>}pendingResults all run results in this transaction
 */
function finishTransaction(commit, connectionHolder, onError, onComplete, onConnection, pendingResults, preparationJob) {
    var requirements = preparationJob !== null && preparationJob !== void 0 ? preparationJob : Promise.resolve();
    var observerPromise = connectionHolder.getConnection()
        .then(function (conn) { return requirements.then(function () { return conn; }); })
        .then(function (connection) {
        onConnection();
        pendingResults.forEach(function (r) { return r._cancel(); });
        return Promise.all(pendingResults.map(function (result) { return result.summary(); })).then(function (results) {
            if (connection != null) {
                if (commit) {
                    return connection.commitTransaction({
                        beforeError: onError,
                        afterComplete: onComplete
                    });
                }
                else {
                    return connection.rollbackTransaction({
                        beforeError: onError,
                        afterComplete: onComplete
                    });
                }
            }
            else {
                throw (0, error_1$4.newError)('No connection available');
            }
        });
    })
        .catch(function (error) { return new observers_1$1.FailedObserver({ error: error, onError: onError }); });
    // 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 result_1$1.default(observerPromise, commit ? 'COMMIT' : 'ROLLBACK', {}, connectionHolder, {
        high: Number.MAX_VALUE,
        low: Number.MAX_VALUE
    });
}
/**
 * Creates a {@link Result} 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 {ResultStreamObserver} observer - an observer for the created result.
 * @param {string} query - the cypher query that produced the result.
 * @param {Object} parameters - the parameters for cypher query that produced the result.
 * @param {ConnectionHolder} connectionHolder - the connection holder used to get the result
 * @return {Result} new result.
 * @private
 */
function newCompletedResult(observerPromise, query, parameters, connectionHolder, highRecordWatermark, lowRecordWatermark) {
    if (connectionHolder === void 0) { connectionHolder = connection_holder_1$1.EMPTY_CONNECTION_HOLDER; }
    return new result_1$1.default(Promise.resolve(observerPromise), query, parameters, new connection_holder_1$1.ReadOnlyConnectionHolder(connectionHolder !== null && connectionHolder !== void 0 ? connectionHolder : connection_holder_1$1.EMPTY_CONNECTION_HOLDER), {
        low: lowRecordWatermark,
        high: highRecordWatermark
    });
}
transaction.default = Transaction;

var transactionManaged = {};

/**
 * 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(transactionManaged, "__esModule", { value: true });
/**
 * Represents a transaction that is managed by the transaction executor.
 *
 * @public
 */
var ManagedTransaction = /** @class */ (function () {
    /**
     * @private
     */
    function ManagedTransaction(_a) {
        var run = _a.run;
        /**
         * @private
         */
        this._run = run;
    }
    /**
     * @private
     * @param {Transaction} tx - Transaction to wrap
     * @returns {ManagedTransaction} the ManagedTransaction
     */
    ManagedTransaction.fromTransaction = function (tx) {
        return new ManagedTransaction({
            run: tx.run.bind(tx)
        });
    };
    /**
     * Run Cypher query
     * Could be called with a query object i.e.: `{text: "MATCH ...", parameters: {param: 1}}`
     * or with the query and parameters as separate arguments.
     * @param {mixed} query - Cypher query to execute
     * @param {Object} parameters - Map with parameters to use in query
     * @return {Result} New Result
     */
    ManagedTransaction.prototype.run = function (query, parameters) {
        return this._run(query, parameters);
    };
    return ManagedTransaction;
}());
transactionManaged.default = ManagedTransaction;

var transactionPromise = {};

/**
 * 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$P = (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 __assign$u = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$u = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$u.apply(this, arguments);
};
var __importDefault$Y = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a$g;
Object.defineProperty(transactionPromise, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/promise-function-async */
var transaction_1 = __importDefault$Y(transaction);
/**
 * Represents a Promise<{@link Transaction}> object and a {@link Transaction} object.
 *
 * Resolving this object promise verifies the result of the transaction begin and returns the {@link Transaction} object in case of success.
 *
 * The object can still also used as {@link Transaction} for convenience. The result of begin will be checked
 * during the next API calls in the object as it is in the transaction.
 *
 * @access public
 */
var TransactionPromise = /** @class */ (function (_super) {
    __extends$P(TransactionPromise, _super);
    /**
     * @constructor
     * @param {object} args
     * @param {ConnectionHolder} args.connectionHolder - the connection holder to get connection from.
     * @param {function()} args.onClose - Function to be called when transaction is committed or rolled back.
     * @param {function(bookmarks: Bookmarks)} args.onBookmarks callback invoked when new bookmark is produced.
     * @param {function()} args.onConnection - Function to be called when a connection is obtained to ensure the connection
     * is not yet released.
     * @param {boolean} args.reactive whether this transaction generates reactive streams
     * @param {number} args.fetchSize - the record fetch size in each pulling batch.
     * @param {string} args.impersonatedUser - The name of the user which should be impersonated for the duration of the session.
     * @param {NotificationFilter} args.notificationFilter - The notification filter used for this transaction.
     * @param {NonAutoCommitApiTelemetryConfig} args.apiTelemetryConfig - The api telemetry configuration. Empty/Null for disabling telemetry
     */
    function TransactionPromise(_b) {
        var connectionHolder = _b.connectionHolder, onClose = _b.onClose, onBookmarks = _b.onBookmarks, onConnection = _b.onConnection, reactive = _b.reactive, fetchSize = _b.fetchSize, impersonatedUser = _b.impersonatedUser, highRecordWatermark = _b.highRecordWatermark, lowRecordWatermark = _b.lowRecordWatermark, notificationFilter = _b.notificationFilter, apiTelemetryConfig = _b.apiTelemetryConfig, onDbCallback = _b.onDbCallback;
        var _this = _super.call(this, {
            connectionHolder: connectionHolder,
            onClose: onClose,
            onBookmarks: onBookmarks,
            onConnection: onConnection,
            reactive: reactive,
            fetchSize: fetchSize,
            impersonatedUser: impersonatedUser,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark,
            notificationFilter: notificationFilter,
            apiTelemetryConfig: apiTelemetryConfig
        }) || this;
        _this[_a$g] = 'TransactionPromise';
        _this._onDbCallback = onDbCallback;
        return _this;
    }
    /**
     * Waits for the begin to complete.
     *
     * @param {function(transaction: Transaction)} onFulfilled - function to be called when finished.
     * @param {function(error: {message:string, code:string})} onRejected - function to be called upon errors.
     * @return {Promise} promise.
     */
    TransactionPromise.prototype.then = function (onfulfilled, onrejected) {
        return this._getOrCreateBeginPromise().then(onfulfilled, onrejected);
    };
    /**
     * Catch errors when using promises.
     *
     * @param {function(error: Neo4jError)} onRejected - Function to be called upon errors.
     * @return {Promise} promise.
     */
    TransactionPromise.prototype.catch = function (onrejected) {
        return this._getOrCreateBeginPromise().catch(onrejected);
    };
    /**
     * Called when finally the begin is done
     *
     * @param {function()|null} onfinally - function when the promise finished
     * @return {Promise} promise.
     */
    TransactionPromise.prototype.finally = function (onfinally) {
        return this._getOrCreateBeginPromise().finally(onfinally);
    };
    TransactionPromise.prototype._getOrCreateBeginPromise = function () {
        var _this = this;
        if (this._beginPromise == null) {
            this._beginPromise = new Promise(function (resolve, reject) {
                _this._resolve = resolve;
                _this._reject = reject;
                if (_this._beginError != null) {
                    reject(_this._beginError);
                }
                if (_this._beginMetadata != null) {
                    resolve(_this._toTransaction());
                }
            });
        }
        return this._beginPromise;
    };
    /**
     * @access private
     */
    TransactionPromise.prototype._toTransaction = function () {
        return __assign$u(__assign$u({}, this), { run: _super.prototype.run.bind(this), commit: _super.prototype.commit.bind(this), rollback: _super.prototype.rollback.bind(this), close: _super.prototype.close.bind(this), isOpen: _super.prototype.isOpen.bind(this), _begin: this._begin.bind(this) });
    };
    /**
     * @access private
     */
    TransactionPromise.prototype._begin = function (bookmarks, txConfig) {
        return _super.prototype._begin.call(this, bookmarks, txConfig, {
            onError: this._onBeginError.bind(this),
            onComplete: this._onBeginMetadata.bind(this),
            onDB: this._onDbCallback
        });
    };
    /**
     * @access private
     * @returns {void}
     */
    TransactionPromise.prototype._onBeginError = function (error) {
        this._beginError = error;
        if (this._reject != null) {
            this._reject(error);
        }
    };
    /**
     * @access private
     * @returns {void}
     */
    TransactionPromise.prototype._onBeginMetadata = function (metadata) {
        this._beginMetadata = metadata !== null && metadata !== void 0 ? metadata : {};
        if (this._resolve != null) {
            this._resolve(this._toTransaction());
        }
    };
    return TransactionPromise;
}(transaction_1.default));
_a$g = Symbol.toStringTag;
transactionPromise.default = TransactionPromise;

var session = {};

var authUtil = {};

/**
 * 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(authUtil, "__esModule", { value: true });
authUtil.cacheKey = cacheKey;
var json_1$1 = json$3;
function cacheKey(auth, impersonatedUser) {
    var _a;
    if (impersonatedUser != null) {
        return 'basic:' + impersonatedUser;
    }
    if (auth === undefined) {
        return 'DEFAULT';
    }
    if (auth.scheme === 'basic') {
        return 'basic:' + ((_a = auth.principal) !== null && _a !== void 0 ? _a : '');
    }
    if (auth.scheme === 'kerberos') {
        return 'kerberos:' + auth.credentials;
    }
    if (auth.scheme === 'bearer') {
        return 'bearer:' + auth.credentials;
    }
    if (auth.scheme === 'none') {
        return 'none';
    }
    return (0, json_1$1.stringify)(auth, { sortedElements: true });
}

/**
 * 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 __awaiter$f = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$h = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read$r = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$l = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault$X = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(session, "__esModule", { value: true });
/* eslint-disable @typescript-eslint/promise-function-async */
var observers_1 = observers;
var util_1$1 = util$4;
var constants_1$2 = constants$1;
var error_1$3 = error;
var result_1 = __importDefault$X(result);
var connection_holder_1 = connectionHolder$1;
var transaction_executor_1 = transactionExecutor$1;
var bookmarks_1$1 = bookmarks$1;
var tx_config_1 = txConfig$1;
var transaction_promise_1 = __importDefault$X(transactionPromise);
var transaction_managed_1 = __importDefault$X(transactionManaged);
var auth_util_1$1 = authUtil;
/**
 * A Session instance is used for handling the connection and
 * sending queries through the connection.
 * In a single session, multiple queries will be executed serially.
 * In order to execute parallel queries, multiple sessions are required.
 * @access public
 */
var Session = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {Object} args
     * @param {string} args.mode the default access mode for this session.
     * @param {ConnectionProvider} args.connectionProvider - The connection provider to acquire connections from.
     * @param {Bookmarks} args.bookmarks - The initial bookmarks for this session.
     * @param {string} args.database the database name
     * @param {Object} args.config={} - This driver configuration.
     * @param {boolean} args.reactive - Whether this session should create reactive streams
     * @param {number} args.fetchSize - Defines how many records is pulled in each pulling batch
     * @param {string} args.impersonatedUser - The username which the user wants to impersonate for the duration of the session.
     * @param {BookmarkManager} args.bookmarkManager - The bookmark manager used for this session.
     * @param {NotificationFilter} args.notificationFilter - The notification filter used for this session.
     * @param {AuthToken} args.auth - the target auth for the to-be-acquired connection
     * @param {Logger} args.log - the logger used for logs in this session.
     * @param {(user:string, database:string) => void} args.homeDatabaseCallback - callback used to update the home database cache
     */
    function Session(_a) {
        var mode = _a.mode, connectionProvider = _a.connectionProvider, bookmarks = _a.bookmarks, database = _a.database, config = _a.config, reactive = _a.reactive, fetchSize = _a.fetchSize, impersonatedUser = _a.impersonatedUser, bookmarkManager = _a.bookmarkManager, notificationFilter = _a.notificationFilter, auth = _a.auth, log = _a.log, homeDatabaseCallback = _a.homeDatabaseCallback;
        var _b;
        this._mode = mode;
        this._database = database;
        this._reactive = reactive;
        this._fetchSize = fetchSize;
        this._homeDatabaseCallback = homeDatabaseCallback;
        this._auth = auth;
        this._getConnectionAcquistionBookmarks = this._getConnectionAcquistionBookmarks.bind(this);
        this._readConnectionHolder = new connection_holder_1.ConnectionHolder({
            mode: constants_1$2.ACCESS_MODE_READ,
            auth: auth,
            database: database,
            bookmarks: bookmarks,
            connectionProvider: connectionProvider,
            impersonatedUser: impersonatedUser,
            onDatabaseNameResolved: this._onDatabaseNameResolved.bind(this),
            getConnectionAcquistionBookmarks: this._getConnectionAcquistionBookmarks,
            log: log
        });
        this._writeConnectionHolder = new connection_holder_1.ConnectionHolder({
            mode: constants_1$2.ACCESS_MODE_WRITE,
            auth: auth,
            database: database,
            bookmarks: bookmarks,
            connectionProvider: connectionProvider,
            impersonatedUser: impersonatedUser,
            onDatabaseNameResolved: this._onDatabaseNameResolved.bind(this),
            getConnectionAcquistionBookmarks: this._getConnectionAcquistionBookmarks,
            log: log
        });
        this._open = true;
        this._hasTx = false;
        this._impersonatedUser = impersonatedUser;
        this._lastBookmarks = bookmarks !== null && bookmarks !== void 0 ? bookmarks : bookmarks_1$1.Bookmarks.empty();
        this._configuredBookmarks = this._lastBookmarks;
        this._transactionExecutor = _createTransactionExecutor(config);
        this._databaseNameResolved = this._database !== '';
        var calculatedWatermaks = this._calculateWatermaks();
        this._lowRecordWatermark = calculatedWatermaks.low;
        this._highRecordWatermark = calculatedWatermaks.high;
        this._results = [];
        this._bookmarkManager = bookmarkManager;
        this._notificationFilter = notificationFilter;
        this._log = log;
        this._databaseGuess = config === null || config === void 0 ? void 0 : config.cachedHomeDatabase;
        this._isRoutingSession = (_b = config === null || config === void 0 ? void 0 : config.routingDriver) !== null && _b !== void 0 ? _b : false;
    }
    /**
     * Run Cypher query
     * Could be called with a query object i.e.: `{text: "MATCH ...", parameters: {param: 1}}`
     * or with the query and parameters as separate arguments.
     *
     * @public
     * @param {mixed} query - Cypher query to execute
     * @param {Object} parameters - Map with parameters to use in query
     * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction.
     * @return {Result} New Result.
     */
    Session.prototype.run = function (query, parameters, transactionConfig) {
        var _this = this;
        var _a = (0, util_1$1.validateQueryAndParameters)(query, parameters), validatedQuery = _a.validatedQuery, params = _a.params;
        var autoCommitTxConfig = (transactionConfig != null)
            ? new tx_config_1.TxConfig(transactionConfig, this._log)
            : tx_config_1.TxConfig.empty();
        var result = this._run(validatedQuery, params, function (connection) { return __awaiter$f(_this, void 0, void 0, function () {
            var bookmarks;
            var _this = this;
            return __generator$h(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._bookmarks()];
                    case 1:
                        bookmarks = _a.sent();
                        this._assertSessionIsOpen();
                        return [2 /*return*/, connection.run(validatedQuery, params, {
                                bookmarks: bookmarks,
                                txConfig: autoCommitTxConfig,
                                mode: this._mode,
                                database: this._database,
                                apiTelemetryConfig: {
                                    api: constants_1$2.TELEMETRY_APIS.AUTO_COMMIT_TRANSACTION
                                },
                                impersonatedUser: this._impersonatedUser,
                                afterComplete: function (meta) { return _this._onCompleteCallback(meta, bookmarks); },
                                reactive: this._reactive,
                                fetchSize: this._fetchSize,
                                lowRecordWatermark: this._lowRecordWatermark,
                                highRecordWatermark: this._highRecordWatermark,
                                notificationFilter: this._notificationFilter,
                                onDb: this._onDatabaseNameResolved.bind(this)
                            })];
                }
            });
        }); });
        this._results.push(result);
        return result;
    };
    Session.prototype._run = function (query, parameters, customRunner) {
        var _a = this._acquireAndConsumeConnection(customRunner), connectionHolder = _a.connectionHolder, resultPromise = _a.resultPromise;
        var observerPromise = resultPromise.catch(function (error) { return Promise.resolve(new observers_1.FailedObserver({ error: error })); });
        var watermarks = { high: this._highRecordWatermark, low: this._lowRecordWatermark };
        return new result_1.default(observerPromise, query, parameters, connectionHolder, watermarks);
    };
    /**
     * This method is used by Rediscovery on the neo4j-driver-bolt-protocol package.
     *
     * @private
     * @param {function()} connectionConsumer The method which will use the connection
     * @returns {Promise<T>} A connection promise
     */
    Session.prototype._acquireConnection = function (connectionConsumer) {
        var _this = this;
        var _a = this._acquireAndConsumeConnection(connectionConsumer), connectionHolder = _a.connectionHolder, resultPromise = _a.resultPromise;
        return resultPromise.then(function (result) { return __awaiter$f(_this, void 0, void 0, function () {
            return __generator$h(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, connectionHolder.releaseConnection()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        }); });
    };
    /**
     * Acquires a {@link Connection}, consume it and return a promise of the result along with
     * the {@link ConnectionHolder} used in the process.
     *
     * @private
     * @param connectionConsumer
     * @returns {object} The connection holder and connection promise.
     */
    Session.prototype._acquireAndConsumeConnection = function (connectionConsumer) {
        var resultPromise;
        var connectionHolder = this._connectionHolderWithMode(this._mode);
        if (!this._open) {
            resultPromise = Promise.reject((0, error_1$3.newError)('Cannot run query in a closed session.'));
        }
        else if (!this._hasTx && connectionHolder.initializeConnection(this._databaseGuess)) {
            resultPromise = connectionHolder
                .getConnection()
                // Connection won't be null at this point since the initialize method
                // return
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                .then(function (connection) { return connectionConsumer(connection); });
        }
        else {
            resultPromise = Promise.reject((0, error_1$3.newError)('Queries cannot be run directly on a ' +
                'session with an open transaction; either run from within the ' +
                'transaction or use a different session.'));
        }
        return { connectionHolder: connectionHolder, resultPromise: resultPromise };
    };
    /**
     * 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 queries outside the transaction.
     *
     * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction.
     * @returns {TransactionPromise} New Transaction.
     */
    Session.prototype.beginTransaction = function (transactionConfig) {
        // this function needs to support bookmarks parameter for backwards compatibility
        // parameter was of type {string|string[]} and represented either a single or multiple bookmarks
        // that's why we need to check parameter type and decide how to interpret the value
        var arg = transactionConfig;
        var txConfig = tx_config_1.TxConfig.empty();
        if (arg != null) {
            txConfig = new tx_config_1.TxConfig(arg, this._log);
        }
        return this._beginTransaction(this._mode, txConfig, { api: constants_1$2.TELEMETRY_APIS.UNMANAGED_TRANSACTION });
    };
    Session.prototype._beginTransaction = function (accessMode, txConfig, apiTelemetryConfig) {
        var _this = this;
        if (!this._open) {
            throw (0, error_1$3.newError)('Cannot begin a transaction on a closed session.');
        }
        if (this._hasTx) {
            throw (0, error_1$3.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 = Session._validateSessionMode(accessMode);
        var connectionHolder = this._connectionHolderWithMode(mode);
        connectionHolder.initializeConnection(this._databaseGuess);
        this._hasTx = true;
        var tx = new transaction_promise_1.default({
            connectionHolder: connectionHolder,
            impersonatedUser: this._impersonatedUser,
            onClose: this._transactionClosed.bind(this),
            onBookmarks: function (newBm, oldBm, db) { return _this._updateBookmarks(newBm, oldBm, db); },
            onConnection: this._assertSessionIsOpen.bind(this),
            reactive: this._reactive,
            fetchSize: this._fetchSize,
            lowRecordWatermark: this._lowRecordWatermark,
            highRecordWatermark: this._highRecordWatermark,
            notificationFilter: this._notificationFilter,
            apiTelemetryConfig: apiTelemetryConfig,
            onDbCallback: this._onDatabaseNameResolved.bind(this)
        });
        tx._begin(function () { return _this._bookmarks(); }, txConfig);
        return tx;
    };
    /**
     * @private
     * @returns {void}
     */
    Session.prototype._assertSessionIsOpen = function () {
        if (!this._open) {
            throw (0, error_1$3.newError)('You cannot run more transactions on a closed session.');
        }
    };
    /**
     * @private
     * @returns {void}
     */
    Session.prototype._transactionClosed = function () {
        this._hasTx = false;
    };
    /**
     * Return the bookmarks received following the last completed {@link Transaction}.
     *
     * @deprecated This method will be removed in version 6.0. Please, use {@link Session#lastBookmarks} instead.
     *
     * @return {string[]} A reference to a previous transaction.
     * @see {@link Session#lastBookmarks}
     */
    Session.prototype.lastBookmark = function () {
        return this.lastBookmarks();
    };
    /**
     * Return the bookmarks received following the last completed {@link Transaction}.
     *
     * @return {string[]} A reference to a previous transaction.
     */
    Session.prototype.lastBookmarks = function () {
        return this._lastBookmarks.values();
    };
    Session.prototype._bookmarks = function () {
        return __awaiter$f(this, void 0, void 0, function () {
            var bookmarks;
            var _a;
            return __generator$h(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, ((_a = this._bookmarkManager) === null || _a === void 0 ? void 0 : _a.getBookmarks())];
                    case 1:
                        bookmarks = _b.sent();
                        if (bookmarks === undefined) {
                            return [2 /*return*/, this._lastBookmarks];
                        }
                        return [2 /*return*/, new bookmarks_1$1.Bookmarks(__spreadArray$l(__spreadArray$l([], __read$r(bookmarks), false), __read$r(this._configuredBookmarks), false))];
                }
            });
        });
    };
    /**
     * 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
     * `maxTransactionRetryTime` property in milliseconds.
     *
     * @deprecated This method will be removed in version 6.0. Please, use {@link Session#executeRead} instead.
     *
     * @param {function(tx: Transaction): Promise} transactionWork - Callback that executes operations against
     * a given {@link Transaction}.
     * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work.
     * @return {Promise} Resolved promise as returned by the given function or rejected promise when given
     * function or commit fails.
     * @see {@link Session#executeRead}
     */
    Session.prototype.readTransaction = function (transactionWork, transactionConfig) {
        var config = new tx_config_1.TxConfig(transactionConfig, this._log);
        return this._runTransaction(constants_1$2.ACCESS_MODE_READ, config, 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
     * `maxTransactionRetryTime` property in milliseconds.
     *
     * @deprecated This method will be removed in version 6.0. Please, use {@link Session#executeWrite} instead.
     *
     * @param {function(tx: Transaction): Promise} transactionWork - Callback that executes operations against
     * a given {@link Transaction}.
     * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work.
     * @return {Promise} Resolved promise as returned by the given function or rejected promise when given
     * function or commit fails.
     * @see {@link Session#executeWrite}
     */
    Session.prototype.writeTransaction = function (transactionWork, transactionConfig) {
        var config = new tx_config_1.TxConfig(transactionConfig, this._log);
        return this._runTransaction(constants_1$2.ACCESS_MODE_WRITE, config, transactionWork);
    };
    Session.prototype._runTransaction = function (accessMode, transactionConfig, transactionWork) {
        var _this = this;
        return this._transactionExecutor.execute(function (apiTelemetryConfig) { return _this._beginTransaction(accessMode, transactionConfig, apiTelemetryConfig); }, transactionWork);
    };
    /**
     * 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
     * `maxTransactionRetryTime` property in milliseconds.
     *
     * NOTE: Because it is an explicit transaction from the server point of view, Cypher queries using
     * "CALL {} IN TRANSACTIONS" or the older "USING PERIODIC COMMIT" construct will not work (call
     * {@link Session#run} for these).
     *
     * @param {function(tx: ManagedTransaction): Promise} transactionWork - Callback that executes operations against
     * a given {@link Transaction}.
     * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work.
     * @return {Promise} Resolved promise as returned by the given function or rejected promise when given
     * function or commit fails.
     */
    Session.prototype.executeRead = function (transactionWork, transactionConfig) {
        var config = new tx_config_1.TxConfig(transactionConfig, this._log);
        return this._executeInTransaction(constants_1$2.ACCESS_MODE_READ, config, 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
     * `maxTransactionRetryTime` property in milliseconds.
     *
     * NOTE: Because it is an explicit transaction from the server point of view, Cypher queries using
     * "CALL {} IN TRANSACTIONS" or the older "USING PERIODIC COMMIT" construct will not work (call
     * {@link Session#run} for these).
     *
     * @param {function(tx: ManagedTransaction): Promise} transactionWork - Callback that executes operations against
     * a given {@link Transaction}.
     * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work.
     * @return {Promise} Resolved promise as returned by the given function or rejected promise when given
     * function or commit fails.
     */
    Session.prototype.executeWrite = function (transactionWork, transactionConfig) {
        var config = new tx_config_1.TxConfig(transactionConfig, this._log);
        return this._executeInTransaction(constants_1$2.ACCESS_MODE_WRITE, config, transactionWork);
    };
    /**
     * @private
     * @param {SessionMode} accessMode
     * @param {TxConfig} transactionConfig
     * @param {ManagedTransactionWork} transactionWork
     * @returns {Promise}
     */
    Session.prototype._executeInTransaction = function (accessMode, transactionConfig, transactionWork) {
        var _this = this;
        return this._transactionExecutor.execute(function (apiTelemetryConfig) { return _this._beginTransaction(accessMode, transactionConfig, apiTelemetryConfig); }, transactionWork, transaction_managed_1.default.fromTransaction);
    };
    /**
     * Sets the resolved database name in the session context.
     * @private
     * @param {string|undefined} database The resolved database name
     * @returns {void}
     */
    Session.prototype._onDatabaseNameResolved = function (database) {
        if (this._isRoutingSession) {
            this._databaseGuess = database;
            if (!this._databaseNameResolved) {
                var normalizedDatabase = database !== null && database !== void 0 ? database : '';
                this._database = normalizedDatabase;
                this._readConnectionHolder.setDatabase(normalizedDatabase);
                this._writeConnectionHolder.setDatabase(normalizedDatabase);
                this._databaseNameResolved = true;
                if (this._homeDatabaseCallback != null) {
                    this._homeDatabaseCallback((0, auth_util_1$1.cacheKey)(this._auth, this._impersonatedUser), database);
                }
            }
        }
    };
    Session.prototype._getConnectionAcquistionBookmarks = function () {
        return __awaiter$f(this, void 0, void 0, function () {
            var bookmarks;
            var _a;
            return __generator$h(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, ((_a = this._bookmarkManager) === null || _a === void 0 ? void 0 : _a.getBookmarks())];
                    case 1:
                        bookmarks = _b.sent();
                        if (bookmarks === undefined) {
                            return [2 /*return*/, this._lastBookmarks];
                        }
                        return [2 /*return*/, new bookmarks_1$1.Bookmarks(__spreadArray$l(__spreadArray$l([], __read$r(this._configuredBookmarks), false), __read$r(bookmarks), false))];
                }
            });
        });
    };
    /**
     * Update value of the last bookmarks.
     * @private
     * @param {Bookmarks} newBookmarks - The new bookmarks.
     * @returns {void}
     */
    Session.prototype._updateBookmarks = function (newBookmarks, previousBookmarks, database) {
        var _a, _b, _c;
        if ((newBookmarks != null) && !newBookmarks.isEmpty()) {
            (_a = this._bookmarkManager) === null || _a === void 0 ? void 0 : _a.updateBookmarks((_b = previousBookmarks === null || previousBookmarks === void 0 ? void 0 : previousBookmarks.values()) !== null && _b !== void 0 ? _b : [], (_c = newBookmarks === null || newBookmarks === void 0 ? void 0 : newBookmarks.values()) !== null && _c !== void 0 ? _c : []).catch(function () { });
            this._lastBookmarks = newBookmarks;
            this._configuredBookmarks = bookmarks_1$1.Bookmarks.empty();
        }
    };
    /**
     * Close this session.
     * @return {Promise}
     */
    Session.prototype.close = function () {
        return __awaiter$f(this, void 0, void 0, function () {
            return __generator$h(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this._open) return [3 /*break*/, 3];
                        this._open = false;
                        this._results.forEach(function (result) { return result._cancel(); });
                        this._transactionExecutor.close();
                        return [4 /*yield*/, this._readConnectionHolder.close(this._hasTx)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this._writeConnectionHolder.close(this._hasTx)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    // eslint-disable-next-line
    // @ts-ignore
    Session.prototype[Symbol.asyncDispose] = function () {
        return this.close();
    };
    Session.prototype._connectionHolderWithMode = function (mode) {
        if (mode === constants_1$2.ACCESS_MODE_READ) {
            return this._readConnectionHolder;
        }
        else if (mode === constants_1$2.ACCESS_MODE_WRITE) {
            return this._writeConnectionHolder;
        }
        else {
            throw (0, error_1$3.newError)('Unknown access mode: ' + mode);
        }
    };
    /**
     * @private
     * @param {Object} meta Connection metadatada
     * @returns {void}
     */
    Session.prototype._onCompleteCallback = function (meta, previousBookmarks) {
        this._updateBookmarks(new bookmarks_1$1.Bookmarks(meta.bookmark), previousBookmarks, meta.db);
    };
    /**
     * @private
     * @returns {void}
     */
    Session.prototype._calculateWatermaks = function () {
        if (this._fetchSize === constants_1$2.FETCH_ALL) {
            return {
                low: Number.MAX_VALUE, // we shall always lower than this number to enable auto pull
                high: Number.MAX_VALUE // we shall never reach this number to disable auto pull
            };
        }
        return {
            low: 0.3 * this._fetchSize,
            high: 0.7 * this._fetchSize
        };
    };
    /**
     * Configure the transaction executor
     *
     * This used by {@link Driver#executeQuery}
     * @private
     * @returns {void}
     */
    Session.prototype._configureTransactionExecutor = function (pipelined, telemetryApi) {
        this._transactionExecutor.pipelineBegin = pipelined;
        this._transactionExecutor.telemetryApi = telemetryApi;
    };
    /**
     * @protected
     */
    Session._validateSessionMode = function (rawMode) {
        var mode = rawMode !== null && rawMode !== void 0 ? rawMode : constants_1$2.ACCESS_MODE_WRITE;
        if (mode !== constants_1$2.ACCESS_MODE_READ && mode !== constants_1$2.ACCESS_MODE_WRITE) {
            throw (0, error_1$3.newError)('Illegal session mode ' + mode);
        }
        return mode;
    };
    return Session;
}());
/**
 * @private
 * @param {object} config
 * @returns {TransactionExecutor} The transaction executor
 */
function _createTransactionExecutor(config) {
    var _a;
    var maxRetryTimeMs = (_a = config === null || config === void 0 ? void 0 : config.maxTransactionRetryTime) !== null && _a !== void 0 ? _a : null;
    return new transaction_executor_1.TransactionExecutor(maxRetryTimeMs);
}
session.default = Session;

var driver = {};

var bookmarkManager$1 = {};

/**
 * 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 __awaiter$e = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$g = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values$b = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read$q = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$k = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(bookmarkManager$1, "__esModule", { value: true });
bookmarkManager$1.bookmarkManager = bookmarkManager;
/**
 * Interface for the piece of software responsible for keeping track of current active bookmarks accross the driver.
 * @interface
 * @since 5.0
 */
var BookmarkManager = /** @class */ (function () {
    /**
     * @constructor
     * @private
     */
    function BookmarkManager() {
        throw new Error('Not implemented');
    }
    /**
     * Method called when the bookmarks get updated when a transaction finished.
     *
     * This method will be called when auto-commit queries finish and when explicit transactions
     * get committed.
     *
     * @param {Iterable<string>} previousBookmarks The bookmarks used when starting the transaction
     * @param {Iterable<string>} newBookmarks The new bookmarks received at the end of the transaction.
     * @returns {void}
    */
    BookmarkManager.prototype.updateBookmarks = function (previousBookmarks, newBookmarks) {
        return __awaiter$e(this, void 0, void 0, function () {
            return __generator$g(this, function (_a) {
                throw new Error('Not implemented');
            });
        });
    };
    /**
     * Method called by the driver to get the bookmarks.
     *
     * @returns {Iterable<string>} The set of bookmarks
     */
    BookmarkManager.prototype.getBookmarks = function () {
        return __awaiter$e(this, void 0, void 0, function () {
            return __generator$g(this, function (_a) {
                throw new Error('Not implemented');
            });
        });
    };
    return BookmarkManager;
}());
bookmarkManager$1.default = BookmarkManager;
/**
 * @typedef {Object} BookmarkManagerConfig
 *
 * @since 5.0
 * @property {Iterable<string>} [initialBookmarks] Defines the initial set of bookmarks. The key is the database name and the values are the bookmarks.
 * @property {function():Promise<Iterable<string>>} [bookmarksSupplier] Called for supplying extra bookmarks to the BookmarkManager
 * @property {function(bookmarks: Iterable<string>): Promise<void>} [bookmarksConsumer] Called when the set of bookmarks  get updated
 */
/**
 * Provides an configured {@link BookmarkManager} instance.
 *
 * @since 5.0
 * @param {BookmarkManagerConfig} [config={}]
 * @returns {BookmarkManager}
 */
function bookmarkManager(config) {
    if (config === void 0) { config = {}; }
    var initialBookmarks = new Set(config.initialBookmarks);
    return new Neo4jBookmarkManager(initialBookmarks, config.bookmarksSupplier, config.bookmarksConsumer);
}
var Neo4jBookmarkManager = /** @class */ (function () {
    function Neo4jBookmarkManager(_bookmarks, _bookmarksSupplier, _bookmarksConsumer) {
        this._bookmarks = _bookmarks;
        this._bookmarksSupplier = _bookmarksSupplier;
        this._bookmarksConsumer = _bookmarksConsumer;
    }
    Neo4jBookmarkManager.prototype.updateBookmarks = function (previousBookmarks, newBookmarks) {
        return __awaiter$e(this, void 0, void 0, function () {
            var bookmarks, previousBookmarks_1, previousBookmarks_1_1, bm, newBookmarks_1, newBookmarks_1_1, bm;
            var e_1, _a, e_2, _b;
            return __generator$g(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        bookmarks = this._bookmarks;
                        try {
                            for (previousBookmarks_1 = __values$b(previousBookmarks), previousBookmarks_1_1 = previousBookmarks_1.next(); !previousBookmarks_1_1.done; previousBookmarks_1_1 = previousBookmarks_1.next()) {
                                bm = previousBookmarks_1_1.value;
                                bookmarks.delete(bm);
                            }
                        }
                        catch (e_1_1) { e_1 = { error: e_1_1 }; }
                        finally {
                            try {
                                if (previousBookmarks_1_1 && !previousBookmarks_1_1.done && (_a = previousBookmarks_1.return)) _a.call(previousBookmarks_1);
                            }
                            finally { if (e_1) throw e_1.error; }
                        }
                        try {
                            for (newBookmarks_1 = __values$b(newBookmarks), newBookmarks_1_1 = newBookmarks_1.next(); !newBookmarks_1_1.done; newBookmarks_1_1 = newBookmarks_1.next()) {
                                bm = newBookmarks_1_1.value;
                                bookmarks.add(bm);
                            }
                        }
                        catch (e_2_1) { e_2 = { error: e_2_1 }; }
                        finally {
                            try {
                                if (newBookmarks_1_1 && !newBookmarks_1_1.done && (_b = newBookmarks_1.return)) _b.call(newBookmarks_1);
                            }
                            finally { if (e_2) throw e_2.error; }
                        }
                        if (!(typeof this._bookmarksConsumer === 'function')) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._bookmarksConsumer(__spreadArray$k([], __read$q(bookmarks), false))];
                    case 1:
                        _c.sent();
                        _c.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    Neo4jBookmarkManager.prototype.getBookmarks = function () {
        return __awaiter$e(this, void 0, void 0, function () {
            var bookmarks, suppliedBookmarks, suppliedBookmarks_1, suppliedBookmarks_1_1, bm;
            var e_3, _a;
            var _b;
            return __generator$g(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        bookmarks = new Set(this._bookmarks);
                        if (!(typeof this._bookmarksSupplier === 'function')) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._bookmarksSupplier()];
                    case 1:
                        suppliedBookmarks = (_b = _c.sent()) !== null && _b !== void 0 ? _b : [];
                        try {
                            for (suppliedBookmarks_1 = __values$b(suppliedBookmarks), suppliedBookmarks_1_1 = suppliedBookmarks_1.next(); !suppliedBookmarks_1_1.done; suppliedBookmarks_1_1 = suppliedBookmarks_1.next()) {
                                bm = suppliedBookmarks_1_1.value;
                                bookmarks.add(bm);
                            }
                        }
                        catch (e_3_1) { e_3 = { error: e_3_1 }; }
                        finally {
                            try {
                                if (suppliedBookmarks_1_1 && !suppliedBookmarks_1_1.done && (_a = suppliedBookmarks_1.return)) _a.call(suppliedBookmarks_1);
                            }
                            finally { if (e_3) throw e_3.error; }
                        }
                        _c.label = 2;
                    case 2: return [2 /*return*/, __spreadArray$k([], __read$q(bookmarks), false)];
                }
            });
        });
    };
    return Neo4jBookmarkManager;
}());

var resultTransformers$1 = {};

/**
 * 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 __awaiter$d = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$f = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$W = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(resultTransformers$1, "__esModule", { value: true });
var result_eager_1 = __importDefault$W(resultEager);
var error_1$2 = error;
/**
 * Protocol for transforming {@link Result}.
 *
 * @typedef {function<T>(result:Result):Promise<T>} ResultTransformer
 * @interface
 *
 * @see {@link resultTransformers} for provided implementations.
 * @see {@link Driver#executeQuery} for usage.
 */
/**
 * Defines the object which holds the common {@link ResultTransformer} used with {@link Driver#executeQuery}.
 */
var ResultTransformers = /** @class */ (function () {
    function ResultTransformers() {
    }
    /**
     * Creates a {@link ResultTransformer} which transforms {@link Result} to {@link EagerResult}
     * by consuming the whole stream.
     *
     * This is the default implementation used in {@link Driver#executeQuery}
     *
     * @example
     * // This:
     * const { keys, records, summary } = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, {
     *   resultTransformer: neo4j.resultTransformers.eagerResultTransformer()
     * })
     * // is equivalent to:
     * const { keys, records, summary } = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'})
     *
     * @returns {ResultTransformer<EagerResult<Entries>>} The result transformer
     * @alias {@link ResultTransformers#eager}
     */
    ResultTransformers.prototype.eagerResultTransformer = function () {
        return createEagerResultFromResult;
    };
    /**
     * Creates a {@link ResultTransformer} which transforms {@link Result} to {@link EagerResult}
     * by consuming the whole stream.
     *
     * This is the default implementation used in {@link Driver#executeQuery} and a alias to
     * {@link resultTransformers.eagerResultTransformer}
     *
     * @example
     * // This:
     * const { keys, records, summary } = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, {
     *   resultTransformer: neo4j.resultTransformers.eager()
     * })
     * // is equivalent to:
     * const { keys, records, summary } = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'})
     *
     * @returns {ResultTransformer<EagerResult<Entries>>} The result transformer
     * @experimental this is a preview
     * @since 5.22.0
     * @alias {@link ResultTransformers#eagerResultTransformer}
     */
    ResultTransformers.prototype.eager = function () {
        return createEagerResultFromResult;
    };
    /**
     * Creates a {@link ResultTransformer} which maps the {@link Record} in the result and collects it
     * along with the {@link ResultSummary} and {@link Result#keys}.
     *
     * NOTE: The config object requires map or/and collect to be valid.
     *
     * @example
     * // Mapping the records
     * const { keys, records, summary } = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: neo4j.resultTransformers.mappedResultTransformer({
     *     map(record) {
     *        return record.get('name')
     *     }
     *   })
     * })
     *
     * records.forEach(name => console.log(`${name} has 25`))
     *
     * @example
     * // Mapping records and collect result
     * const names = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: neo4j.resultTransformers.mappedResultTransformer({
     *     map(record) {
     *        return record.get('name')
     *     },
     *     collect(records, summary, keys) {
     *        return records
     *     }
     *   })
     * })
     *
     * names.forEach(name => console.log(`${name} has 25`))
     *
     * @example
     * // The transformer can be defined one and used everywhere
     * const getRecordsAsObjects = neo4j.resultTransformers.mappedResultTransformer({
     *   map(record) {
     *      return record.toObject()
     *   },
     *   collect(objects) {
     *      return objects
     *   }
     * })
     *
     * // The usage in a driver.executeQuery
     * const objects = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: getRecordsAsObjects
     * })
     * objects.forEach(object => console.log(`${object.name} has 25`))
     *
     *
     * // The usage in session.executeRead
     * const objects = await session.executeRead(tx => getRecordsAsObjects(tx.run('MATCH (p:Person{ age: $age }) RETURN p.name as name')))
     * objects.forEach(object => console.log(`${object.name} has 25`))
     *
     * @param {object} config The result transformer configuration
     * @param {function(record:Record):R} [config.map=function(record) {  return record }] Method called for mapping each record
     * @param {function(records:R[], summary:ResultSummary, keys:string[]):T} [config.collect=function(records, summary, keys) { return { records, summary, keys }}] Method called for mapping
     * the result data to the transformer output.
     * @returns {ResultTransformer<T>} The result transformer
     * @see {@link Driver#executeQuery}
     */
    ResultTransformers.prototype.mappedResultTransformer = function (config) {
        return createMappedResultTransformer(config);
    };
    /**
     * Creates a {@link ResultTransformer} which maps the {@link Record} in the result and collects it
     * along with the {@link ResultSummary} and {@link Result#keys}.
     *
     * NOTE: The config object requires map or/and collect to be valid.
     *
     * This method is a alias to {@link ResultTransformers#mappedResultTransformer}
     *
     *
     * @example
     * // Mapping the records
     * const { keys, records, summary } = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: neo4j.resultTransformers.mapped({
     *     map(record) {
     *        return record.get('name')
     *     }
     *   })
     * })
     *
     * records.forEach(name => console.log(`${name} has 25`))
     *
     * @example
     * // Mapping records and collect result
     * const names = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: neo4j.resultTransformers.mapped({
     *     map(record) {
     *        return record.get('name')
     *     },
     *     collect(records, summary, keys) {
     *        return records
     *     }
     *   })
     * })
     *
     * names.forEach(name => console.log(`${name} has 25`))
     *
     * @example
     * // The transformer can be defined one and used everywhere
     * const getRecordsAsObjects = neo4j.resultTransformers.mapped({
     *   map(record) {
     *      return record.toObject()
     *   },
     *   collect(objects) {
     *      return objects
     *   }
     * })
     *
     * // The usage in a driver.executeQuery
     * const objects = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: getRecordsAsObjects
     * })
     * objects.forEach(object => console.log(`${object.name} has 25`))
     *
     *
     * // The usage in session.executeRead
     * const objects = await session.executeRead(tx => getRecordsAsObjects(tx.run('MATCH (p:Person{ age: $age }) RETURN p.name as name')))
     * objects.forEach(object => console.log(`${object.name} has 25`))
     *
     * @param {object} config The result transformer configuration
     * @param {function(record:Record):R} [config.map=function(record) {  return record }] Method called for mapping each record
     * @param {function(records:R[], summary:ResultSummary, keys:string[]):T} [config.collect=function(records, summary, keys) { return { records, summary, keys }}] Method called for mapping
     * the result data to the transformer output.
     * @returns {ResultTransformer<T>} The result transformer
     * @experimental This is a preview feature
     * @alias {@link ResultTransformers#mappedResultTransformer}
     * @since 5.22.0
     * @see {@link Driver#executeQuery}
     */
    ResultTransformers.prototype.mapped = function (config) {
        return createMappedResultTransformer(config);
    };
    /**
     * Creates a {@link ResultTransformer} which collects the first record {@link Record} of {@link Result}
     * and discard the rest of the records, if existent.
     *
     * @example
     * // Using in executeQuery
     * const maybeFirstRecord = await driver.executeQuery('MATCH (p:Person{ age: $age }) RETURN p.name as name', { age: 25 }, {
     *   resultTransformer: neo4j.resultTransformers.first()
     * })
     *
     * @example
     * // Using in other results
     * const record = await neo4j.resultTransformers.first()(result)
     *
     *
     * @template Entries The shape of the record.
     * @returns {ResultTransformer<Record<Entries>|undefined>} The result transformer
     * @see {@link Driver#executeQuery}
     * @experimental This is a preview feature.
     * @since 5.22.0
     */
    ResultTransformers.prototype.first = function () {
        return first$2;
    };
    /**
     * Creates a {@link ResultTransformer} which consumes the result and returns the {@link ResultSummary}.
     *
     * This result transformer is a shortcut to `(result) => result.summary()`.
     *
     * @example
     * const summary = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'}, {
     *   resultTransformer: neo4j.resultTransformers.summary()
     * })
     *
     * @returns {ResultTransformer<ResultSummary<T>>} The result transformer
     * @see {@link Driver#executeQuery}
     * @experimental This is a preview feature
     */
    ResultTransformers.prototype.summary = function () {
        return summary;
    };
    return ResultTransformers;
}());
/**
 * Holds the common {@link ResultTransformer} used with {@link Driver#executeQuery}.
 */
var resultTransformers = new ResultTransformers();
Object.freeze(resultTransformers);
resultTransformers$1.default = resultTransformers;
function createEagerResultFromResult(result) {
    return __awaiter$d(this, void 0, void 0, function () {
        var _a, summary, records, keys;
        return __generator$f(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, result];
                case 1:
                    _a = _b.sent(), summary = _a.summary, records = _a.records;
                    return [4 /*yield*/, result.keys()];
                case 2:
                    keys = _b.sent();
                    return [2 /*return*/, new result_eager_1.default(keys, records, summary)];
            }
        });
    });
}
function createMappedResultTransformer(config) {
    var _this = this;
    if (config == null || (config.collect == null && config.map == null)) {
        throw (0, error_1$2.newError)('Requires a map or/and a collect functions.');
    }
    return function (result) { return __awaiter$d(_this, void 0, void 0, function () {
        return __generator$f(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
                        var state = { records: [], keys: [] };
                        result.subscribe({
                            onKeys: function (keys) {
                                state.keys = keys;
                            },
                            onNext: function (record) {
                                if (config.map != null) {
                                    var mappedRecord = config.map(record);
                                    if (mappedRecord !== undefined) {
                                        state.records.push(mappedRecord);
                                    }
                                }
                                else {
                                    state.records.push(record);
                                }
                            },
                            onCompleted: function (summary) {
                                if (config.collect != null) {
                                    resolve(config.collect(state.records, summary, state.keys));
                                }
                                else {
                                    var obj = { records: state.records, summary: summary, keys: state.keys };
                                    resolve(obj);
                                }
                            },
                            onError: function (error) {
                                reject(error);
                            }
                        });
                    })];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); };
}
function first$2(result) {
    return __awaiter$d(this, void 0, void 0, function () {
        var it, _a, value, done;
        return __generator$f(this, function (_b) {
            switch (_b.label) {
                case 0:
                    it = result[Symbol.asyncIterator]();
                    return [4 /*yield*/, it.next()];
                case 1:
                    _a = _b.sent(), value = _a.value, done = _a.done;
                    _b.label = 2;
                case 2:
                    _b.trys.push([2, , 3, 6]);
                    if (done === true) {
                        return [2 /*return*/, undefined];
                    }
                    return [2 /*return*/, value];
                case 3:
                    if (!(it.return != null)) return [3 /*break*/, 5];
                    return [4 /*yield*/, it.return()];
                case 4:
                    _b.sent();
                    _b.label = 5;
                case 5: return [7 /*endfinally*/];
                case 6: return [2 /*return*/];
            }
        });
    });
}
function summary(result) {
    return __awaiter$d(this, void 0, void 0, function () {
        return __generator$f(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, result.summary()];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    });
}

var queryExecutor = {};

/**
 * 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 __awaiter$c = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$e = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(queryExecutor, "__esModule", { value: true });
var constants_1$1 = constants$1;
var QueryExecutor = /** @class */ (function () {
    function QueryExecutor(_createSession) {
        this._createSession = _createSession;
    }
    QueryExecutor.prototype.execute = function (config, query, parameters) {
        return __awaiter$c(this, void 0, void 0, function () {
            var session, listenerHandle, executeInTransaction;
            var _this = this;
            return __generator$e(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        session = this._createSession({
                            database: config.database,
                            bookmarkManager: config.bookmarkManager,
                            impersonatedUser: config.impersonatedUser,
                            auth: config.auth
                        });
                        listenerHandle = installEventListenerWhenPossible(
                        // Solving linter and types definitions issue
                        config.signal, 'abort', function () { return __awaiter$c(_this, void 0, void 0, function () { return __generator$e(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, session.close()];
                                case 1: return [2 /*return*/, _a.sent()];
                            }
                        }); }); });
                        // @ts-expect-error The method is private for external users
                        session._configureTransactionExecutor(true, constants_1$1.TELEMETRY_APIS.EXECUTE_QUERY);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 5]);
                        executeInTransaction = config.routing === 'READ'
                            ? session.executeRead.bind(session)
                            : session.executeWrite.bind(session);
                        return [4 /*yield*/, executeInTransaction(function (tx) { return __awaiter$c(_this, void 0, void 0, function () {
                                var result;
                                return __generator$e(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            result = tx.run(query, parameters);
                                            return [4 /*yield*/, config.resultTransformer(result)];
                                        case 1: return [2 /*return*/, _a.sent()];
                                    }
                                });
                            }); }, config.transactionConfig)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        listenerHandle.uninstall();
                        return [4 /*yield*/, session.close()];
                    case 4:
                        _a.sent();
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    return QueryExecutor;
}());
queryExecutor.default = QueryExecutor;
function installEventListenerWhenPossible(target, event, listener) {
    if (typeof (target === null || target === void 0 ? void 0 : target.addEventListener) === 'function') {
        target.addEventListener(event, listener);
    }
    return {
        uninstall: function () {
            if (typeof (target === null || target === void 0 ? void 0 : target.removeEventListener) === 'function') {
                target.removeEventListener(event, listener);
            }
        }
    };
}

var homedbCache = {};

/**
 * 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(homedbCache, "__esModule", { value: true });
/**
 * Cache which maps users to their last known home database, along with the last time the entry was accessed.
 *
 * @private
 */
var HomeDatabaseCache = /** @class */ (function () {
    function HomeDatabaseCache(maxSize) {
        this.maxSize = maxSize;
        this.pruneCount = Math.max(Math.round(0.01 * maxSize * Math.log(maxSize)), 1);
        this.map = new Map();
    }
    /**
     * Updates or adds an entry to the cache, and prunes the cache if above the maximum allowed size
     *
     * @param {string} user cache key for the user to set
     * @param {string} database new home database to set for the user
     */
    HomeDatabaseCache.prototype.set = function (user, database) {
        this.map.set(user, { database: database, lastUsed: Date.now() });
        this._pruneCache();
    };
    /**
     * retrieves the last known home database for a user
     *
     * @param {string} user cache key for the user to get
     */
    HomeDatabaseCache.prototype.get = function (user) {
        var value = this.map.get(user);
        if (value !== undefined) {
            value.lastUsed = Date.now();
            return value.database;
        }
        return undefined;
    };
    /**
     * removes the entry for a given user in the cache
     *
     * @param {string} user cache key for the user to remove
     */
    HomeDatabaseCache.prototype.delete = function (user) {
        this.map.delete(user);
    };
    /**
     * Removes a number of the oldest entries in the cache if the number of entries has exceeded the maximum size.
     */
    HomeDatabaseCache.prototype._pruneCache = function () {
        if (this.map.size > this.maxSize) {
            var sortedArray = Array.from(this.map.entries()).sort(function (a, b) { return a[1].lastUsed - b[1].lastUsed; });
            for (var i = 0; i < this.pruneCount; i++) {
                this.map.delete(sortedArray[i][0]);
            }
        }
    };
    return HomeDatabaseCache;
}());
homedbCache.default = HomeDatabaseCache;

var __assign$t = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$t = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$t.apply(this, arguments);
};
var __awaiter$b = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$d = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$V = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(driver, "__esModule", { value: true });
driver.QueryConfig = driver.SessionConfig = driver.routing = driver.WRITE = driver.READ = driver.Driver = void 0;
var bookmarks_1 = bookmarks$1;
var configured_custom_resolver_1 = __importDefault$V(configuredCustomResolver);
var constants_1 = constants$1;
var logger_1 = logger$1;
var session_1 = __importDefault$V(session);
var util_1 = util$4;
var bookmark_manager_1 = bookmarkManager$1;
var result_transformers_1 = __importDefault$V(resultTransformers$1);
var query_executor_1 = __importDefault$V(queryExecutor);
var error_1$1 = error;
var homedb_cache_1 = __importDefault$V(homedbCache);
var auth_util_1 = authUtil;
var DEFAULT_MAX_CONNECTION_LIFETIME = 60 * 60 * 1000; // 1 hour
/**
 * The default record fetch size. This is used in Bolt V4 protocol to pull query execution result in batches.
 * @type {number}
 */
var DEFAULT_FETCH_SIZE = 1000;
/**
 * The maximum number of entries allowed in the home database cache before pruning.
 */
var HOMEDB_CACHE_MAX_SIZE = 10000;
/**
 * Constant that represents read session access mode.
 * Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.READ })`.
 * @type {string}
 */
var READ$3 = constants_1.ACCESS_MODE_READ;
driver.READ = READ$3;
/**
 * Constant that represents write session access mode.
 * Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.WRITE })`.
 * @type {string}
 */
var WRITE$3 = constants_1.ACCESS_MODE_WRITE;
driver.WRITE = WRITE$3;
var idGenerator$1 = 0;
/**
 * The session configuration
 *
 * @interface
 */
var SessionConfig = /** @class */ (function () {
    /**
     * @constructor
     * @private
     */
    function SessionConfig() {
        /**
         * The access mode of this session, allowed values are {@link READ} and {@link WRITE}.
         * **Default**: {@link WRITE}
         * @type {string}
         */
        this.defaultAccessMode = WRITE$3;
        /**
         * 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.
         * @type {string|string[]|undefined}
         */
        this.bookmarks = [];
        /**
         * The database this session will operate on.
         *
         * This option has no explicit value by default, but it is recommended to set
         * one if the target database is known in advance. This has the benefit of
         * ensuring a consistent target database name throughout the session in a
         * straightforward way and potentially simplifies driver logic as well as
         * reduces network communication resulting in better performance.
         *
         * Usage of Cypher clauses like USE is not a replacement for this option.
         * The driver does not parse any Cypher.
         *
         * When no explicit name is set, the driver behavior depends on the connection
         * URI scheme supplied to the driver on instantiation and Bolt protocol
         * version.
         *
         * Specifically, the following applies:
         *
         * - **bolt schemes** - queries are dispatched to the server for execution
         *   without explicit database name supplied, meaning that the target database
         *   name for query execution is determined by the server. It is important to
         *   note that the target database may change (even within the same session),
         *   for instance if the user's home database is changed on the server.
         *
         * - **neo4j schemes** - providing that Bolt protocol version 4.4, which was
         *   introduced with Neo4j server 4.4, or above is available, the driver
         *   fetches the user's home database name from the server on first query
         *   execution within the session and uses the fetched database name
         *   explicitly for all queries executed within the session. This ensures that
         *   the database name remains consistent within the given session. For
         *   instance, if the user's home database name is 'movies' and the server
         *   supplies it to the driver upon database name fetching for the session,
         *   all queries within that session are executed with the explicit database
         *   name 'movies' supplied. Any change to the user’s home database is
         *   reflected only in sessions created after such change takes effect. This
         *   behavior requires additional network communication. In clustered
         *   environments, it is strongly recommended to avoid a single point of
         *   failure. For instance, by ensuring that the connection URI resolves to
         *   multiple endpoints. For older Bolt protocol versions the behavior is the
         *   same as described for the **bolt schemes** above.
         *
         * @type {string|undefined}
         */
        this.database = '';
        /**
         * The username which the user wants to impersonate for the duration of the session.
         *
         * @type {string|undefined}
         */
        this.impersonatedUser = undefined;
        /**
         * The {@link AuthToken} which will be used for the duration of the session.
         *
         * By default, the session will use connections authenticated with the {@link AuthToken} configured on
         * driver creation. This configuration allows switching user and/or authorization information for the
         * session lifetime.
         *
         * **Warning**: This option is only available when the driver is connected to Neo4j Database servers
         * which supports Bolt 5.1 or newer.
         *
         * @type {AuthToken|undefined}
         * @see {@link driver}
         */
        this.auth = undefined;
        /**
         * The record fetch size of each batch of this session.
         *
         * Use {@link FETCH_ALL} to always pull all records in one batch. This will override the config value set on driver config.
         *
         * @type {number|undefined}
         */
        this.fetchSize = undefined;
        /**
         * Configure a BookmarkManager for the session to use
         *
         * A BookmarkManager is a piece of software responsible for keeping casual consistency between different sessions by sharing bookmarks
         * between the them.
         * Enabling it is done by supplying an BookmarkManager implementation instance to this param.
         * A default implementation could be acquired by calling the factory function {@link bookmarkManager}.
         *
         * **Warning**: Sharing the same BookmarkManager instance across multiple sessions can have a negative impact
         * on performance since all the queries will wait for the latest changes being propagated across the cluster.
         * For keeping consistency between a group of queries, use {@link Session} for grouping them.
         * For keeping consistency between a group of sessions, use {@link BookmarkManager} instance for grouping them.
         *
         * @example
         * const bookmarkManager = neo4j.bookmarkManager()
         * const linkedSession1 = driver.session({ database:'neo4j', bookmarkManager })
         * const linkedSession2 = driver.session({ database:'neo4j', bookmarkManager })
         * const unlinkedSession = driver.session({ database:'neo4j' })
         *
         * // Creating Driver User
         * const createUserQueryResult = await linkedSession1.run('CREATE (p:Person {name: $name})', { name: 'Driver User'})
         *
         * // Reading Driver User will *NOT* wait of the changes being propagated to the server before RUN the query
         * // So the 'Driver User' person might not exist in the Result
         * const unlinkedReadResult = await unlinkedSession.run('CREATE (p:Person {name: $name}) RETURN p', { name: 'Driver User'})
         *
         * // Reading Driver User will wait of the changes being propagated to the server before RUN the query
         * // So the 'Driver User' person should exist in the Result, unless deleted.
         * const linkedResult = await linkedSession2.run('CREATE (p:Person {name: $name}) RETURN p', { name: 'Driver User'})
         *
         * await linkedSession1.close()
         * await linkedSession2.close()
         * await unlinkedSession.close()
         *
         * @type {BookmarkManager|undefined}
         * @since 5.0
         */
        this.bookmarkManager = undefined;
        /**
         * Configure filter for {@link Notification} objects returned in {@link ResultSummary#notifications}.
         *
         * This configuration enables filter notifications by:
         *
         * * the minimum severity level ({@link NotificationFilterMinimumSeverityLevel})
         * * disabling notification categories ({@link NotificationFilterDisabledCategory})
         *
         *
         * Disabling notifications can be done by defining the minimum severity level to 'OFF'.
         * At driver level, when omitted, uses the server's default.
         * At session level, when omitted, defaults to what filters have been configured at driver level.
         *
         * Disabling categories or severities allows the server to skip analysis for those, which can speed up query
         * execution.
         *
         * @example
         * // enabling warning notification, but disabling `HINT` and `DEPRECATION` notifications.
         * const session = driver.session({
         *     database: 'neo4j',
         *     notificationFilter: {
         *         minimumSeverityLevel: neo4j.notificationFilterMinimumSeverityLevel.WARNING, // or 'WARNING
         *         disabledCategories: [
         *             neo4j.notificationFilterDisabledCategory.HINT, // or 'HINT'
         *             neo4j.notificationFilterDisabledCategory.DEPRECATION // or 'DEPRECATION'
         *        ]
         *     }
         * })
         *
         * @example
         * // disabling notifications for a session
         * const session = driver.session({
         *     database: 'neo4j',
         *     notificationFilter: {
         *         minimumSeverityLevel: neo4j.notificationFilterMinimumSeverityLevel.OFF // or 'OFF'
         *     }
         * })
         *
         * @example
         * // using default values configured in the driver
         * const sessionWithDefaultValues = driver.session({ database: 'neo4j' })
         * // or driver.session({ database: 'neo4j', notificationFilter: undefined })
         *
         * // using default minimum severity level, but disabling 'HINT' and 'UNRECOGNIZED'
         * // notification categories
         * const sessionWithDefaultSeverityLevel = driver.session({
         *     database: 'neo4j',
         *     notificationFilter: {
         *         disabledCategories: [
         *             neo4j.notificationFilterDisabledCategory.HINT, // or 'HINT'
         *             neo4j.notificationFilterDisabledCategory.UNRECOGNIZED // or 'UNRECOGNIZED'
         *        ]
         *     }
         * })
         *
         * // using default disabled categories, but configuring minimum severity level to 'WARNING'
         * const sessionWithDefaultSeverityLevel = driver.session({
         *     database: 'neo4j',
         *     notificationFilter: {
         *         minimumSeverityLevel: neo4j.notificationFilterMinimumSeverityLevel.WARNING // or 'WARNING'
         *     }
         * })
         *
         * @type {NotificationFilter|undefined}
         * @since 5.7
         */
        this.notificationFilter = undefined;
    }
    return SessionConfig;
}());
driver.SessionConfig = SessionConfig;
var ROUTING_WRITE = 'WRITE';
var ROUTING_READ = 'READ';
/**
 * @typedef {'WRITE'|'READ'} RoutingControl
 */
/**
 * Constants that represents routing modes.
 *
 * @example
 * driver.executeQuery("<QUERY>", <PARAMETERS>, { routing: neo4j.routing.WRITE })
 */
var routing = {
    WRITE: ROUTING_WRITE,
    READ: ROUTING_READ
};
driver.routing = routing;
Object.freeze(routing);
/**
 * The query configuration
 * @interface
 */
var QueryConfig = /** @class */ (function () {
    /**
     * @constructor
     * @private
     */
    function QueryConfig() {
        /**
         * Define the type of cluster member the query will be routed to.
         *
         * @type {RoutingControl}
         */
        this.routing = routing.WRITE;
        /**
         * Define the transformation will be applied to the Result before return from the
         * query method.
         *
         * @type {ResultTransformer}
         * @see {@link resultTransformers} for provided implementations.
         */
        this.resultTransformer = undefined;
        /**
         * The database this session will operate on.
         *
         * @type {string|undefined}
         */
        this.database = '';
        /**
         * The username which the user wants to impersonate for the duration of the query.
         *
         * @type {string|undefined}
         */
        this.impersonatedUser = undefined;
        /**
         * Configure a BookmarkManager for the session to use
         *
         * A BookmarkManager is a piece of software responsible for keeping casual consistency between different pieces of work by sharing bookmarks
         * between the them.
         *
         * By default, it uses the driver's non mutable driver level bookmark manager. See, {@link Driver.executeQueryBookmarkManager}
         *
         * Can be set to null to disable causal chaining.
         * @type {BookmarkManager|undefined|null}
         */
        this.bookmarkManager = undefined;
        /**
         * Configuration for all transactions started to execute the query.
         *
         * @type {TransactionConfig|undefined}
         *
         */
        this.transactionConfig = undefined;
        /**
         * The {@link AuthToken} which will be used for executing the query.
         *
         * By default, the query executor will use connections authenticated with the {@link AuthToken} configured on
         * driver creation. This configuration allows switching user and/or authorization information for the
         * underlying transaction's lifetime.
         *
         * **Warning**: This option is only available when the driver is connected to Neo4j Database servers
         * which support Bolt 5.1 or newer.
         *
         * @type {AuthToken|undefined}
         * @see {@link driver}
         */
        this.auth = undefined;
        /**
         * The {@link AbortSignal} for aborting query execution.
         *
         * When aborted, the signal triggers the result consumption cancelation and
         * transactions are reset. However, due to race conditions,
         * there is no guarantee the transaction will be rolled back.
         * Equivalent to {@link Session.close}
         *
         * **Warning**: This option is only available in runtime which supports AbortSignal.addEventListener.
         *
         * @since 5.22.0
         * @type {AbortSignal|undefined}
         * @experimental
         * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
         */
        this.signal = undefined;
    }
    return QueryConfig;
}());
driver.QueryConfig = QueryConfig;
/**
 * A driver maintains one or more {@link Session}s with a remote
 * Neo4j instance. Through the {@link Session}s you can send queries
 * 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$1 = /** @class */ (function () {
    /**
     * You should not be calling this directly, instead use {@link driver}.
     * @constructor
     * @protected
     * @param {Object} meta Metainformation about the driver
     * @param {Object} config
     * @param {function(id: number, config:Object, log:Logger, hostNameResolver: ConfiguredCustomResolver): ConnectionProvider } createConnectionProvider Creates the connection provider
     * @param {function(args): Session } createSession Creates the a session
    */
    function Driver(meta, config, createConnectionProvider, createSession, createQueryExecutor) {
        if (config === void 0) { config = {}; }
        if (createSession === void 0) { createSession = function (args) { return new session_1.default(args); }; }
        if (createQueryExecutor === void 0) { createQueryExecutor = function (createSession) { return new query_executor_1.default(createSession); }; }
        sanitizeConfig(config);
        var log = logger_1.Logger.create(config);
        validateConfig(config, log);
        this._id = idGenerator$1++;
        this._meta = meta;
        this._config = config;
        this._log = log;
        this._createConnectionProvider = createConnectionProvider;
        this._createSession = createSession;
        this._defaultExecuteQueryBookmarkManager = (0, bookmark_manager_1.bookmarkManager)();
        this._queryExecutor = createQueryExecutor(this.session.bind(this));
        /**
         * Reference to the connection provider. Initialized lazily by {@link _getOrCreateConnectionProvider}.
         * @type {ConnectionProvider}
         * @protected
         */
        this._connectionProvider = null;
        /**
         * @private
         */
        this.homeDatabaseCache = new homedb_cache_1.default(HOMEDB_CACHE_MAX_SIZE);
        this._afterConstruction();
    }
    Object.defineProperty(Driver.prototype, "executeQueryBookmarkManager", {
        /**
         * The bookmark managed used by {@link Driver.executeQuery}
         *
         * @type {BookmarkManager}
         */
        get: function () {
            return this._defaultExecuteQueryBookmarkManager;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Executes a query in a retriable context and returns a {@link EagerResult}.
     *
     * This method is a shortcut for a {@link Session#executeRead} and {@link Session#executeWrite}.
     *
     * NOTE: Because it is an explicit transaction from the server point of view, Cypher queries using
     * "CALL {} IN TRANSACTIONS" or the older "USING PERIODIC COMMIT" construct will not work (call
     * {@link Session#run} for these).
     *
     * @example
     * // Run a simple write query
     * const { keys, records, summary } = await driver.executeQuery('CREATE (p:Person{ name: $name }) RETURN p', { name: 'Person1'})
     *
     * @example
     * // Run a read query
     * const { keys, records, summary } = await driver.executeQuery(
     *    'MATCH (p:Person{ name: $name }) RETURN p',
     *    { name: 'Person1'},
     *    { routing: neo4j.routing.READ})
     *
     * @example
     * // Run a read query returning a Person Nodes per elementId
     * const peopleMappedById = await driver.executeQuery(
     *    'MATCH (p:Person{ name: $name }) RETURN p',
     *    { name: 'Person1'},
     *    {
     *      resultTransformer: neo4j.resultTransformers.mappedResultTransformer({
     *        map(record) {
     *          const p = record.get('p')
     *          return [p.elementId, p]
     *        },
     *        collect(elementIdPersonPairArray) {
     *          return new Map(elementIdPersonPairArray)
     *        }
     *      })
     *    }
     * )
     *
     * const person = peopleMappedById.get("<ELEMENT_ID>")
     *
     * @example
     * // these lines
     * const transformedResult = await driver.executeQuery(
     *    "<QUERY>",
     *    <PARAMETERS>,
     *    {
     *       routing: neo4j.routing.WRITE,
     *       resultTransformer: transformer,
     *       database: "<DATABASE>",
     *       impersonatedUser: "<USER>",
     *       bookmarkManager: bookmarkManager
     *    })
     * // are equivalent to those
     * const session = driver.session({
     *    database: "<DATABASE>",
     *    impersonatedUser: "<USER>",
     *    bookmarkManager: bookmarkManager
     * })
     *
     * try {
     *    const transformedResult = await session.executeWrite(tx => {
     *        const result = tx.run("<QUERY>", <PARAMETERS>)
     *        return transformer(result)
     *    })
     * } finally {
     *    await session.close()
     * }
     *
     * @public
     * @param {string | {text: string, parameters?: object}} query - Cypher query to execute
     * @param {Object} parameters - Map with parameters to use in the query
     * @param {QueryConfig<T>} config - The query configuration
     * @returns {Promise<T>}
     *
     * @see {@link resultTransformers} for provided result transformers.
     */
    Driver.prototype.executeQuery = function (query_1, parameters_1) {
        return __awaiter$b(this, arguments, void 0, function (query, parameters, config) {
            var bookmarkManager, resultTransformer, routingConfig;
            var _a, _b, _c;
            if (config === void 0) { config = {}; }
            return __generator$d(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        bookmarkManager = config.bookmarkManager === null ? undefined : ((_a = config.bookmarkManager) !== null && _a !== void 0 ? _a : this.executeQueryBookmarkManager);
                        resultTransformer = ((_b = config.resultTransformer) !== null && _b !== void 0 ? _b : result_transformers_1.default.eagerResultTransformer());
                        routingConfig = (_c = config.routing) !== null && _c !== void 0 ? _c : routing.WRITE;
                        if (routingConfig !== routing.READ && routingConfig !== routing.WRITE) {
                            throw (0, error_1$1.newError)("Illegal query routing config: \"".concat(routingConfig, "\""));
                        }
                        return [4 /*yield*/, this._queryExecutor.execute({
                                resultTransformer: resultTransformer,
                                bookmarkManager: bookmarkManager,
                                routing: routingConfig,
                                database: config.database,
                                impersonatedUser: config.impersonatedUser,
                                transactionConfig: config.transactionConfig,
                                auth: config.auth,
                                signal: config.signal
                            }, query, parameters)];
                    case 1: return [2 /*return*/, _d.sent()];
                }
            });
        });
    };
    /**
     * Verifies connectivity of this driver by trying to open a connection with the provided driver options.
     *
     * @deprecated This return of this method will change in 6.0.0 to not async return the {@link ServerInfo} and
     * async return {@link void} instead. If you need to use the server info, use {@link getServerInfo} instead.
     *
     * @public
     * @param {Object} param - The object parameter
     * @param {string} param.database - The target database to verify connectivity for.
     * @returns {Promise<ServerInfo>} promise resolved with server info or rejected with error.
     */
    Driver.prototype.verifyConnectivity = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.database, database = _c === void 0 ? '' : _c;
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.verifyConnectivityAndGetServerInfo({ database: database, accessMode: READ$3 });
    };
    /**
     * This method verifies the authorization credentials work by trying to acquire a connection
     * to one of the servers with the given credentials.
     *
     * @param {object} param - object parameter
     * @property {AuthToken} param.auth - the target auth for the to-be-acquired connection
     * @property {string} param.database - the target database for the to-be-acquired connection
     *
     * @returns {Promise<boolean>} promise resolved with true if succeed, false if failed with
     *  authentication issue and rejected with error if non-authentication error happens.
     */
    Driver.prototype.verifyAuthentication = function () {
        return __awaiter$b(this, arguments, void 0, function (_a) {
            var connectionProvider;
            var _b = _a === void 0 ? {} : _a, database = _b.database, auth = _b.auth;
            return __generator$d(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        connectionProvider = this._getOrCreateConnectionProvider();
                        return [4 /*yield*/, connectionProvider.verifyAuthentication({
                                database: database !== null && database !== void 0 ? database : 'system',
                                auth: auth,
                                accessMode: READ$3
                            })];
                    case 1: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    /**
     * Get ServerInfo for the giver database.
     *
     * @param {Object} param - The object parameter
     * @param {string} param.database - The target database to verify connectivity for.
     * @returns {Promise<ServerInfo>} promise resolved with the ServerInfo or rejected with error.
     */
    Driver.prototype.getServerInfo = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.database, database = _c === void 0 ? '' : _c;
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.verifyConnectivityAndGetServerInfo({ database: database, accessMode: READ$3 });
    };
    /**
     * Returns whether the server supports multi database capabilities based on the protocol
     * version negotiated via handshake.
     *
     * Note that this function call _always_ causes a round-trip to the server.
     *
     * @returns {Promise<boolean>} promise resolved with a boolean or rejected with error.
     */
    Driver.prototype.supportsMultiDb = function () {
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.supportsMultiDb();
    };
    /**
     * Returns whether the server supports transaction config capabilities based on the protocol
     * version negotiated via handshake.
     *
     * Note that this function call _always_ causes a round-trip to the server.
     *
     * @returns {Promise<boolean>} promise resolved with a boolean or rejected with error.
     */
    Driver.prototype.supportsTransactionConfig = function () {
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.supportsTransactionConfig();
    };
    /**
     * Returns whether the server supports user impersonation capabilities based on the protocol
     * version negotiated via handshake.
     *
     * Note that this function call _always_ causes a round-trip to the server.
     *
     * @returns {Promise<boolean>} promise resolved with a boolean or rejected with error.
     */
    Driver.prototype.supportsUserImpersonation = function () {
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.supportsUserImpersonation();
    };
    /**
     * Returns whether the driver session re-auth functionality capabilities based on the protocol
     * version negotiated via handshake.
     *
     * Note that this function call _always_ causes a round-trip to the server.
     *
     * @returns {Promise<boolean>} promise resolved with a boolean or rejected with error.
     */
    Driver.prototype.supportsSessionAuth = function () {
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.supportsSessionAuth();
    };
    /**
     * Returns the protocol version negotiated via handshake.
     *
     * Note that this function call _always_ causes a round-trip to the server.
     *
     * @returns {Promise<number>} the protocol version negotiated via handshake.
     * @throws {Error} When protocol negotiation fails
     */
    Driver.prototype.getNegotiatedProtocolVersion = function () {
        var connectionProvider = this._getOrCreateConnectionProvider();
        return connectionProvider.getNegotiatedProtocolVersion();
    };
    /**
     * Returns boolean to indicate if driver has been configured with encryption enabled.
     *
     * @returns {boolean}
     */
    Driver.prototype.isEncrypted = function () {
        return this._isEncrypted();
    };
    /**
     * @protected
     * @returns {boolean}
     */
    Driver.prototype._supportsRouting = function () {
        return this._meta.routing;
    };
    /**
     * Returns boolean to indicate if driver has been configured with encryption enabled.
     *
     * @protected
     * @returns {boolean}
     */
    Driver.prototype._isEncrypted = function () {
        return this._config.encrypted === util_1.ENCRYPTION_ON || this._config.encrypted === true;
    };
    /**
     * Returns the configured trust strategy that the driver has been configured with.
     *
     * @protected
     * @returns {TrustStrategy}
     */
    Driver.prototype._getTrust = function () {
        return this._config.trust;
    };
    /**
     * Acquire a session to communicate with the database. The session will
     * borrow connections from the underlying connection pool as required and
     * should be considered lightweight and disposable.
     *
     * 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 closed, the underlying connection will be released to the connection
     * pool and made available for others to use.
     *
     * @public
     * @param {SessionConfig} param - The session configuration
     * @return {Session} new session.
     */
    Driver.prototype.session = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.defaultAccessMode, defaultAccessMode = _c === void 0 ? WRITE$3 : _c, bookmarkOrBookmarks = _b.bookmarks, _d = _b.database, database = _d === void 0 ? '' : _d, impersonatedUser = _b.impersonatedUser, fetchSize = _b.fetchSize, bookmarkManager = _b.bookmarkManager, notificationFilter = _b.notificationFilter, auth = _b.auth;
        return this._newSession({
            defaultAccessMode: defaultAccessMode,
            bookmarkOrBookmarks: bookmarkOrBookmarks,
            database: database,
            reactive: false,
            impersonatedUser: impersonatedUser,
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            fetchSize: validateFetchSizeValue$1(fetchSize, this._config.fetchSize),
            bookmarkManager: bookmarkManager,
            notificationFilter: notificationFilter,
            auth: auth
        });
    };
    /**
     * Close all open sessions and other associated resources. You should
     * make sure to use this when you are done with this driver instance.
     *
     * This will interrupt any running connections.
     * Make sure you are done using the driver object and any resources
     * spawned from it (such as sessions or transactions) while calling
     * this method. Failing to do so will result in unspecified behavior.
     *
     * @public
     * @return {Promise<void>} promise resolved when the driver is closed.
     */
    Driver.prototype.close = function () {
        this._log.info("Driver ".concat(this._id, " closing"));
        if (this._connectionProvider != null) {
            return this._connectionProvider.close();
        }
        return Promise.resolve();
    };
    // eslint-disable-next-line
    // @ts-ignore
    Driver.prototype[Symbol.asyncDispose] = function () {
        return this.close();
    };
    /**
     * @protected
     * @returns {void}
     */
    Driver.prototype._afterConstruction = function () {
        this._log.info("".concat(this._meta.typename, " driver ").concat(this._id, " created for server address ").concat(this._meta.address.toString()));
    };
    Driver.prototype._homeDatabaseCallback = function (cacheKey, database) {
        this.homeDatabaseCache.set(cacheKey, database);
    };
    /**
     * @private
     */
    Driver.prototype._newSession = function (_a) {
        var defaultAccessMode = _a.defaultAccessMode, bookmarkOrBookmarks = _a.bookmarkOrBookmarks, database = _a.database, reactive = _a.reactive, impersonatedUser = _a.impersonatedUser, fetchSize = _a.fetchSize, bookmarkManager = _a.bookmarkManager, notificationFilter = _a.notificationFilter, auth = _a.auth;
        var sessionMode = session_1.default._validateSessionMode(defaultAccessMode);
        var connectionProvider = this._getOrCreateConnectionProvider();
        // eslint-disable-next-line
        var cachedHomeDatabase = this.homeDatabaseCache.get((0, auth_util_1.cacheKey)(auth, impersonatedUser));
        var homeDatabaseCallback = this._homeDatabaseCallback.bind(this);
        var bookmarks = bookmarkOrBookmarks != null
            ? new bookmarks_1.Bookmarks(bookmarkOrBookmarks)
            : bookmarks_1.Bookmarks.empty();
        return this._createSession({
            mode: sessionMode,
            database: database !== null && database !== void 0 ? database : '',
            connectionProvider: connectionProvider,
            bookmarks: bookmarks,
            config: __assign$t({ cachedHomeDatabase: cachedHomeDatabase, routingDriver: this._supportsRouting() }, this._config),
            reactive: reactive,
            impersonatedUser: impersonatedUser,
            fetchSize: fetchSize,
            bookmarkManager: bookmarkManager,
            notificationFilter: notificationFilter,
            auth: auth,
            log: this._log,
            homeDatabaseCallback: homeDatabaseCallback
        });
    };
    /**
     * @private
     */
    Driver.prototype._getOrCreateConnectionProvider = function () {
        if (this._connectionProvider == null) {
            this._connectionProvider = this._createConnectionProvider(this._id, this._config, this._log, createHostNameResolver(this._config));
        }
        return this._connectionProvider;
    };
    return Driver;
}());
driver.Driver = Driver$1;
/**
 * @private
 * @returns {Object} the given config.
 */
function validateConfig(config, log) {
    var _a, _b;
    var resolver = config.resolver;
    if (resolver !== null && resolver !== undefined && typeof resolver !== 'function') {
        throw new TypeError("Configured resolver should be a function. Got: ".concat(typeof resolver));
    }
    if (config.connectionAcquisitionTimeout < config.connectionTimeout) {
        log.warn('Configuration for "connectionAcquisitionTimeout" should be greater than ' +
            'or equal to "connectionTimeout". Otherwise, the connection acquisition ' +
            'timeout will take precedence for over the connection timeout in scenarios ' +
            'where a new connection is created while it is acquired');
    }
    if (((_a = config.notificationFilter) === null || _a === void 0 ? void 0 : _a.disabledCategories) != null && ((_b = config.notificationFilter) === null || _b === void 0 ? void 0 : _b.disabledClassifications) != null) {
        throw new Error('The notificationFilter can\'t have both "disabledCategories" and  "disabledClassifications" configured at the same time.');
    }
    return config;
}
/**
 * @private
 * @returns {void}
 */
function sanitizeConfig(config) {
    config.maxConnectionLifetime = sanitizeIntValue(config.maxConnectionLifetime, DEFAULT_MAX_CONNECTION_LIFETIME);
    config.maxConnectionPoolSize = sanitizeIntValue(config.maxConnectionPoolSize, constants_1.DEFAULT_POOL_MAX_SIZE);
    config.connectionAcquisitionTimeout = sanitizeIntValue(config.connectionAcquisitionTimeout, constants_1.DEFAULT_POOL_ACQUISITION_TIMEOUT);
    config.fetchSize = validateFetchSizeValue$1(config.fetchSize, DEFAULT_FETCH_SIZE);
    config.connectionTimeout = extractConnectionTimeout(config);
    config.connectionLivenessCheckTimeout =
        validateConnectionLivenessCheckTimeoutSizeValue(config.connectionLivenessCheckTimeout);
}
/**
 * @private
 * @returns {number}
 */
function sanitizeIntValue(rawValue, defaultWhenAbsent) {
    var sanitizedValue = parseInt(rawValue, 10);
    if (sanitizedValue > 0 || sanitizedValue === 0) {
        return sanitizedValue;
    }
    else if (sanitizedValue < 0) {
        return Number.MAX_SAFE_INTEGER;
    }
    else {
        return defaultWhenAbsent;
    }
}
/**
 * @private
 */
function validateFetchSizeValue$1(rawValue, defaultWhenAbsent) {
    var fetchSize = parseInt(rawValue, 10);
    if (fetchSize > 0 || fetchSize === constants_1.FETCH_ALL) {
        return fetchSize;
    }
    else if (fetchSize === 0 || fetchSize < 0) {
        throw new Error("The fetch size can only be a positive value or ".concat(constants_1.FETCH_ALL, " for ALL. However fetchSize = ").concat(fetchSize));
    }
    else {
        return defaultWhenAbsent;
    }
}
/**
 * @private
 */
function extractConnectionTimeout(config) {
    var configuredTimeout = parseInt(config.connectionTimeout, 10);
    if (configuredTimeout === 0) {
        // timeout explicitly configured to 0
        return null;
    }
    else if (!isNaN(configuredTimeout) && configuredTimeout < 0) {
        // timeout explicitly configured to a negative value
        return null;
    }
    else if (isNaN(configuredTimeout)) {
        // timeout not configured, use default value
        return constants_1.DEFAULT_CONNECTION_TIMEOUT_MILLIS;
    }
    else {
        // timeout configured, use the provided value
        return configuredTimeout;
    }
}
/**
 * @private
 */
function validateConnectionLivenessCheckTimeoutSizeValue(rawValue) {
    if (rawValue == null) {
        return undefined;
    }
    var connectionLivenessCheckTimeout = parseInt(rawValue, 10);
    if (connectionLivenessCheckTimeout < 0 || Number.isNaN(connectionLivenessCheckTimeout)) {
        throw new Error("The connectionLivenessCheckTimeout can only be a positive value or 0 for always. However connectionLivenessCheckTimeout = ".concat(connectionLivenessCheckTimeout));
    }
    return connectionLivenessCheckTimeout;
}
/**
 * @private
 * @returns {ConfiguredCustomResolver} new custom resolver that wraps the passed-in resolver function.
 *              If resolved function is not specified, it defaults to an identity resolver.
 */
function createHostNameResolver(config) {
    return new configured_custom_resolver_1.default(config.resolver);
}
driver.default = Driver$1;

var auth$1 = {};

/**
 * 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(auth$1, "__esModule", { value: true });
var error_1 = error;
var json_1 = json$3;
/**
 * @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(base64EncodedTicket: string)} bearer the function to create a Bearer authentication token.
 * Accepts a single string argument - base64 encoded Bearer ticket.
 * @property {function(principal: string, credentials: string, realm: string, scheme: string, parameters: ?object)} custom
 * the function to create a custom authentication token.
 */
var auth = {
    basic: function (username, password, realm) {
        if (realm != null) {
            return {
                scheme: 'basic',
                principal: username,
                credentials: password,
                realm: realm
            };
        }
        else {
            return { scheme: 'basic', principal: username, credentials: password };
        }
    },
    kerberos: function (base64EncodedTicket) {
        return {
            scheme: 'kerberos',
            principal: '', // This empty string is required for backwards compatibility.
            credentials: base64EncodedTicket
        };
    },
    bearer: function (base64EncodedToken) {
        return {
            scheme: 'bearer',
            credentials: base64EncodedToken
        };
    },
    none: function () {
        return {
            scheme: 'none'
        };
    },
    custom: function (principal, credentials, realm, scheme, parameters) {
        var output = {
            scheme: scheme,
            principal: principal
        };
        if (isNotEmpty(credentials)) {
            output.credentials = credentials;
        }
        if (isNotEmpty(realm)) {
            output.realm = realm;
        }
        if (isNotEmpty(parameters)) {
            try {
                (0, json_1.stringify)(parameters);
            }
            catch (e) {
                throw (0, error_1.newError)('Circular references in custom auth token parameters', undefined, e);
            }
            output.parameters = parameters;
        }
        return output;
    }
};
function isNotEmpty(value) {
    return !(value === null ||
        value === undefined ||
        value === '' ||
        (Object.getPrototypeOf(value) === Object.prototype && Object.keys(value).length === 0));
}
auth$1.default = auth;

var authTokenManager = {};

/**
 * 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 __awaiter$a = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$c = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$U = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(authTokenManager, "__esModule", { value: true });
authTokenManager.authTokenManagers = authTokenManager.AuthTokenAndExpiration = void 0;
authTokenManager.staticAuthTokenManager = staticAuthTokenManager;
var auth_1 = __importDefault$U(auth$1);
var internal_1 = internal;
/**
 * Interface for the piece of software responsible for keeping track of current active {@link AuthToken} across the driver.
 * @interface
 * @since 5.14
 */
var AuthTokenManager = /** @class */ (function () {
    function AuthTokenManager() {
    }
    /**
     * Returns a valid token.
     *
     * **Warning**: This method must only ever return auth information belonging to the same identity.
     * Switching identities using the `AuthTokenManager` is undefined behavior.
     *
     * @returns {Promise<AuthToken>|AuthToken} The valid auth token or a promise for a valid auth token
     */
    AuthTokenManager.prototype.getToken = function () {
        throw new Error('Not Implemented');
    };
    /**
     * Handles an error notification emitted by the server if a security error happened.
     *
     * @param {AuthToken} token The expired token.
     * @param {`Neo.ClientError.Security.${string}`} securityErrorCode the security error code returned by the server
     * @return {boolean} whether the exception was handled by the manager, so the driver knows if it can be retried..
     */
    AuthTokenManager.prototype.handleSecurityException = function (token, securityErrorCode) {
        throw new Error('Not implemented');
    };
    return AuthTokenManager;
}());
authTokenManager.default = AuthTokenManager;
/**
 * Interface which defines an {@link AuthToken} with an expiration data time associated
 * @interface
 * @since 5.14
 */
var AuthTokenAndExpiration = /** @class */ (function () {
    function AuthTokenAndExpiration() {
        /**
         * The {@link AuthToken} used for authenticate connections.
         *
         * @type {AuthToken}
         * @see {auth}
         */
        this.token = auth_1.default.none();
        /**
         * The expected expiration date of the auth token.
         *
         * This information will be used for triggering the auth token refresh
         * in managers created with {@link authTokenManagers#bearer}.
         *
         * If this value is not defined, the {@link AuthToken} will be considered valid
         * until a `Neo.ClientError.Security.TokenExpired` error happens.
         *
         * @type {Date|undefined}
         */
        this.expiration = undefined;
    }
    return AuthTokenAndExpiration;
}());
authTokenManager.AuthTokenAndExpiration = AuthTokenAndExpiration;
/**
 * Defines the object which holds the common {@link AuthTokenManager} used in the Driver
 */
var AuthTokenManagers = /** @class */ (function () {
    function AuthTokenManagers() {
    }
    /**
     * Creates a {@link AuthTokenManager} for handle {@link AuthToken} which is expires.
     *
     * **Warning**: `tokenProvider` must only ever return auth information belonging to the same identity.
     * Switching identities using the `AuthTokenManager` is undefined behavior.
     *
     * @param {object} param0 - The params
     * @param {function(): Promise<AuthTokenAndExpiration>} param0.tokenProvider - Retrieves a new valid auth token.
     * Must only ever return auth information belonging to the same identity.
     * @returns {AuthTokenManager} The temporal auth data manager.
     */
    AuthTokenManagers.prototype.bearer = function (_a) {
        var tokenProvider = _a.tokenProvider;
        if (typeof tokenProvider !== 'function') {
            throw new TypeError("tokenProvider should be function, but got: ".concat(typeof tokenProvider));
        }
        return new ExpirationBasedAuthTokenManager(tokenProvider, [
            'Neo.ClientError.Security.Unauthorized',
            'Neo.ClientError.Security.TokenExpired'
        ]);
    };
    /**
     * Creates a {@link AuthTokenManager} for handle {@link AuthToken} and password rotation.
     *
     * **Warning**: `tokenProvider` must only ever return auth information belonging to the same identity.
     * Switching identities using the `AuthTokenManager` is undefined behavior.
     *
     * @param {object} param0 - The params
     * @param {function(): Promise<AuthToken>} param0.tokenProvider - Retrieves a new valid auth token.
     * Must only ever return auth information belonging to the same identity.
     * @returns {AuthTokenManager} The basic auth data manager.
     */
    AuthTokenManagers.prototype.basic = function (_a) {
        var _this = this;
        var tokenProvider = _a.tokenProvider;
        if (typeof tokenProvider !== 'function') {
            throw new TypeError("tokenProvider should be function, but got: ".concat(typeof tokenProvider));
        }
        return new ExpirationBasedAuthTokenManager(function () { return __awaiter$a(_this, void 0, void 0, function () {
            var _a;
            return __generator$c(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = {};
                        return [4 /*yield*/, tokenProvider()];
                    case 1: return [2 /*return*/, (_a.token = _b.sent(), _a)];
                }
            });
        }); }, ['Neo.ClientError.Security.Unauthorized']);
    };
    return AuthTokenManagers;
}());
/**
 * Holds the common {@link AuthTokenManagers} used in the Driver.
 */
var authTokenManagers = new AuthTokenManagers();
authTokenManager.authTokenManagers = authTokenManagers;
Object.freeze(authTokenManagers);
/**
 * Create a {@link AuthTokenManager} for handle static {@link AuthToken}
 *
 * @private
 * @param {param} args - The args
 * @param {AuthToken} args.authToken - The static auth token which will always used in the driver.
 * @returns {AuthTokenManager} The temporal auth data manager.
 */
function staticAuthTokenManager(_a) {
    var authToken = _a.authToken;
    return new StaticAuthTokenManager(authToken);
}
var TokenRefreshObservable = /** @class */ (function () {
    function TokenRefreshObservable(_subscribers) {
        if (_subscribers === void 0) { _subscribers = []; }
        this._subscribers = _subscribers;
    }
    TokenRefreshObservable.prototype.subscribe = function (sub) {
        this._subscribers.push(sub);
    };
    TokenRefreshObservable.prototype.onCompleted = function (data) {
        this._subscribers.forEach(function (sub) { return sub.onCompleted(data); });
    };
    TokenRefreshObservable.prototype.onError = function (error) {
        this._subscribers.forEach(function (sub) { return sub.onError(error); });
    };
    return TokenRefreshObservable;
}());
var ExpirationBasedAuthTokenManager = /** @class */ (function () {
    function ExpirationBasedAuthTokenManager(_tokenProvider, _handledSecurityCodes, _currentAuthData, _refreshObservable) {
        this._tokenProvider = _tokenProvider;
        this._handledSecurityCodes = _handledSecurityCodes;
        this._currentAuthData = _currentAuthData;
        this._refreshObservable = _refreshObservable;
    }
    ExpirationBasedAuthTokenManager.prototype.getToken = function () {
        return __awaiter$a(this, void 0, void 0, function () {
            var _a;
            return __generator$c(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(this._currentAuthData === undefined ||
                            (this._currentAuthData.expiration !== undefined &&
                                this._currentAuthData.expiration < new Date()))) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._refreshAuthToken()];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2: return [2 /*return*/, (_a = this._currentAuthData) === null || _a === void 0 ? void 0 : _a.token];
                }
            });
        });
    };
    ExpirationBasedAuthTokenManager.prototype.handleSecurityException = function (token, securityErrorCode) {
        var _a;
        if (this._handledSecurityCodes.includes(securityErrorCode)) {
            if (internal_1.util.equals(token, (_a = this._currentAuthData) === null || _a === void 0 ? void 0 : _a.token)) {
                this._scheduleRefreshAuthToken();
            }
            return true;
        }
        return false;
    };
    ExpirationBasedAuthTokenManager.prototype._scheduleRefreshAuthToken = function (observer) {
        var _this = this;
        if (this._refreshObservable === undefined) {
            this._currentAuthData = undefined;
            this._refreshObservable = new TokenRefreshObservable();
            Promise.resolve(this._tokenProvider())
                .then(function (data) {
                var _a;
                _this._currentAuthData = data;
                (_a = _this._refreshObservable) === null || _a === void 0 ? void 0 : _a.onCompleted(data);
            })
                .catch(function (error) {
                var _a;
                (_a = _this._refreshObservable) === null || _a === void 0 ? void 0 : _a.onError(error);
            })
                .finally(function () {
                _this._refreshObservable = undefined;
            });
        }
        if (observer !== undefined) {
            this._refreshObservable.subscribe(observer);
        }
    };
    ExpirationBasedAuthTokenManager.prototype._refreshAuthToken = function () {
        return __awaiter$a(this, void 0, void 0, function () {
            var _this = this;
            return __generator$c(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
                            _this._scheduleRefreshAuthToken({
                                onCompleted: resolve,
                                onError: reject
                            });
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    return ExpirationBasedAuthTokenManager;
}());
var StaticAuthTokenManager = /** @class */ (function () {
    function StaticAuthTokenManager(_authToken) {
        this._authToken = _authToken;
    }
    StaticAuthTokenManager.prototype.getToken = function () {
        return this._authToken;
    };
    StaticAuthTokenManager.prototype.handleSecurityException = function (_, __) {
        return false;
    };
    return StaticAuthTokenManager;
}());

var types$1 = {};

/**
 * 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$O = (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 __());
    };
})();
Object.defineProperty(types$1, "__esModule", { value: true });
types$1.InternalConfig = types$1.Config = void 0;
/**
 * The Neo4j Driver configuration.
 *
 * @interface
 */
var Config = /** @class */ (function () {
    /**
     * @constructor
     * @private
     */
    function Config() {
        /**
         * Encryption level
         *
         * @type {'ENCRYPTION_ON'|'ENCRYPTION_OFF'|undefined}
         */
        this.encrypted = undefined;
        /**
         * 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_SYSTEM_CA_SIGNED_CERTIFICATES is the default choice. For NodeJS environments, this
         * means that you trust whatever certificates are in the default trusted certificate
         * store of the underlying system. For Browser environments, the trusted certificate
         * store is usually managed by the browser. Refer to your system or browser documentation
         * if you want to explicitly add a certificate as trusted.
         *
         * TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is another option for 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 given
         * as trusted through configuration. This option is only available for NodeJS environments.
         *
         * TRUST_ALL_CERTIFICATES means that you trust everything without any verifications
         * steps carried out.  This option is only available for NodeJS environments and should not
         * be used on production systems.
         *
         * @type {'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'|'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES'|'TRUST_ALL_CERTIFICATES'|undefined}
         */
        this.trust = undefined;
        /**
         * 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']
         *
         * @type {?string[]}
         * @see {@link Config#trust}
         */
        this.trustedCertificates = [];
        /**
         * The maximum total number of connections allowed to be managed by the connection pool, per host.
         *
         * This includes both in-use and idle connections.
         *
         * **Default**: ```100```
         *
         * @type {number|undefined}
         */
        this.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.
         *
         * **Default**: ```60 * 60 * 1000``` (1 hour)
         *
         * @type {number|undefined}
         */
        this.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).
         *
         * **Default**: ```60000``` (1 minute)
         *
         * @type {number|undefined}
         */
        this.connectionAcquisitionTimeout = 60000; // 1 minute
        /**
         * Specify the maximum time in milliseconds transactions are allowed to retry via
         * {@link Session#executeRead}, {@link Session#executeWrite}, and {@link Driver#executeQuery} functions.
         *
         * These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient
         * errors with exponential backoff using an initial delay of 1 second.
         *
         * **Default**: ```30000``` (30 seconds)
         *
         * @type {number|undefined}
         */
        this.maxTransactionRetryTime = 30000; // 30 seconds
        /**
         * Specify the maximum time in milliseconds the connection can be idle without needing
         * to perform a liveness check on acquire from the pool.
         *
         * Pooled connections that have been idle in the pool for longer than this
         * timeout will be tested before they are used again, to ensure they are still live.
         * If this option is set too low, an additional network call will be incurred
         * when acquiring a connection, which causes a performance hit.
         *
         * If this is set high, you may receive sessions that are backed by no longer
         * live connections, which will lead to exceptions in your application.
         * Assuming the database is running, these exceptions will go away if you retry
         * acquiring sessions.
         *
         * Hence, this parameter tunes a balance between the likelihood of your application
         * seeing connection problems, and performance.
         *
         * You normally should not need to tune this parameter. No connection liveliness
         * check is done by default. Value 0 means connections will always be tested for
         * validity and negative values mean connections will never be tested.
         *
         * **Default**: ```undefined``` (Disabled)
         *
         * @type {number|undefined}
         */
        this.connectionLivenessCheckTimeout = undefined; // Disabled
        /**
         * Specify socket connection timeout in milliseconds.
         *
         * 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**: ```30000``` (30 seconds)
         *
         * @type {number|undefined}
         */
        this.connectionTimeout = 30000; // 30 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 `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`.
         *
         * **Warning:** {@link ResultSummary} 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
         * `Number` type and thus the driver will return lossy values. This might also happen when data was
         * initially imported using neo4j import tool and contained numbers larger than
         * `Number.MAX_SAFE_INTEGER`. Driver will then return positive infinity, which is lossy.
         *
         * **Default**: ```false```
         *
         * Default value for this option is `false` because native JavaScript numbers might result
         * in loss of precision in the general case.
         *
         * @type {boolean|undefined}
         */
        this.disableLosslessIntegers = false;
        /**
         * Make this driver always return native Javascript `BigInt` for integer values,
         * instead of the dedicated {@link Integer} class or `Number`.
         *
         * **Warning:** `BigInt` doesn't implement the method `toJSON`. To serialize it as `json`,
         * it's needed to add a custom implementation of the `toJSON` on the
         * `BigInt.prototype`. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json.
         *
         * **Default**: ```false``` (for backwards compatibility)
         *
         * @type {boolean|undefined}
         */
        this.useBigInt = false;
        /**
         * Specify the logging configuration for the driver. Object should have two properties `level` and `logger`.
         *
         * Property `level` represents the logging level which should be one of: 'error', 'warn', 'info' or 'debug'. This property is optional and
         * its default value is 'info'. Levels have priorities: 'error': 0, 'warn': 1, 'info': 2, 'debug': 3. Enabling a certain level also enables all
         * levels with lower priority. For example: 'error', 'warn' and 'info' will be logged when 'info' level is configured.
         *
         * Property `logger` represents the logging function which will be invoked for every log call with an acceptable level. The function should
         * take two string arguments `level` and `message`. The function should not execute any blocking or long-running operations
         * because it is often executed on a hot path.
         *
         * No logging is done by default. See `neo4j.logging` object that contains predefined logging implementations.
         *
         * @type {LoggingConfig|undefined}
         * @see {@link logging}
         */
        this.logging = undefined;
        /**
         * Specify a custom server address resolver function used by the routing driver to resolve the initial address used to create the driver.
         *
         * Such resolution happens:
         *   * during the very first rediscovery when driver is created
         *   * when all the known routers from the current routing table have failed and driver needs to fallback to the initial address
         *
         *  In NodeJS environment driver defaults to performing a DNS resolution of the initial address using 'dns' module.
         *  In browser environment driver uses the initial address as-is.
         *  Value should be a function that takes a single string argument - the initial address. It should return an array of new addresses.
         *  Address is a string of shape '<host>:<port>'. Provided function can return either a Promise resolved with an array of addresses
         *  or array of addresses directly.
         *
         * @type {function(address: string) {} |undefined}
         */
        this.resolver = undefined;
        /**
         * Configure filter for Notification objects returned in {@link ResultSummary#notifications}.
         *
         * See {@link SessionConfig#notificationFilter} for usage instructions.
         *
         * @type {NotificationFilter|undefined}
         */
        this.notificationFilter = undefined;
        /**
         * Optionally override the default user agent name.
         *
         * **Default**: ```'neo4j-javascript/<version>'```
         *
         * @type {string|undefined}
         */
        this.userAgent = undefined;
        /**
         * Specify if telemetry collection is disabled.
         *
         * By default, the driver will send anonymous usage statistics to the server it connects to if the server requests those.
         * By setting ``telemetryDisabled=true``, the driver will not send any telemetry data.
         *
         * The driver transmits the following information:
         *
         * Every time one of the following APIs is used to execute a query (for the first time), the server is informed of this
         * (without any further information like arguments, client identifiers, etc.):
         *
         * * {@link Driver#executeQuery}
         * * {@link Session#run}
         * * {@link Session#beginTransaction}
         * * {@link Session#executeRead}
         * * {@link Session#executeWrite}
         * * {@link Session#writeTransaction}
         * * {@link Session#readTransaction}
         * * The reactive counterparts of methods above.
         *
         * Metrics are only collected when enabled both in server and driver instances.
         *
         * **Default**: ```false```
         *
         * @type {boolean}
         */
        this.telemetryDisabled = false;
        /**
         * Client Certificate used for mutual TLS.
         *
         * A {@link ClientCertificateProvider} can be configure for scenarios
         * where the {@link ClientCertificate} might change over time.
         *
         * @type {ClientCertificate|ClientCertificateProvider|undefined}
         * @since 5.27
         */
        this.clientCertificate = undefined;
    }
    return Config;
}());
types$1.Config = Config;
var InternalConfig = /** @class */ (function (_super) {
    __extends$O(InternalConfig, _super);
    function InternalConfig() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return InternalConfig;
}(Config));
types$1.InternalConfig = InternalConfig;

var clientCertificate = {};

/**
 * 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$N = (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 __assign$s = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$s = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$s.apply(this, arguments);
};
var __createBinding$5 = (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$5 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$5 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$5(result, mod, k[i]);
        __setModuleDefault$5(result, mod);
        return result;
    };
})();
Object.defineProperty(clientCertificate, "__esModule", { value: true });
clientCertificate.clientCertificateProviders = clientCertificate.RotatingClientCertificateProvider = clientCertificate.ClientCertificateProvider = void 0;
clientCertificate.resolveCertificateProvider = resolveCertificateProvider;
var json = __importStar$5(json$3);
/**
 * Represents KeyFile represented as file.
 *
 * @typedef {object} KeyFileObject
 * @property {string} path - The path of the file
 * @property {string|undefined} password - the password of the key. If none,
 * the password defined at {@link ClientCertificate} will be used.
 */
/**
 * Holds the Client TLS certificate information.
 *
 * Browser instances of the driver should configure the certificate
 * in the system.
 *
 * Files defined in the {@link ClientCertificate#certfile}
 * and {@link ClientCertificate#keyfile} will read and loaded to
 * memory to fill the fields `cert` and `key` in security context.
 *
 * @interface
 * @see https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions
 * @since 5.27
 */
var ClientCertificate = /** @class */ (function () {
    function ClientCertificate() {
        /**
         * The path to client certificate file.
         *
         * @type {string|string[]}
         */
        this.certfile = '';
        /**
         * The path to the key file.
         *
         * @type {string|string[]|KeyFileObject|KeyFileObject[]}
         */
        this.keyfile = '';
        /**
         * The key's password.
         *
         * @type {string|undefined}
         */
        this.password = undefined;
    }
    return ClientCertificate;
}());
clientCertificate.default = ClientCertificate;
/**
 * Provides a client certificate to the driver for mutual TLS.
 *
 * The driver will call {@link ClientCertificateProvider#hasUpdate} to check if the client wants to update the certificate.
 * If so, it will call {@link ClientCertificateProvider#getClientCertificate} to get the new certificate.
 *
 * The certificate is only used as a second factor for authentication authenticating the client.
 * The DMBS user still needs to authenticate with an authentication token.
 *
 * All implementations of this interface must be thread-safe and non-blocking for caller threads.
 * For instance, IO operations must not be done on the calling thread.
 *
 * Note that the work done in the methods of this interface count towards the connectionAcquisition.
 * Should fetching the certificate be particularly slow, it might be necessary to increase the timeout.
 *
 * @interface
 * @since 5.27
 */
var ClientCertificateProvider = /** @class */ (function () {
    function ClientCertificateProvider() {
    }
    /**
     * Indicates whether the client wants the driver to update the certificate.
     *
     * @returns {Promise<boolean>|boolean} true if the client wants the driver to update the certificate
     */
    ClientCertificateProvider.prototype.hasUpdate = function () {
        throw new Error('Not Implemented');
    };
    /**
     * Returns the certificate to use for new connections.
     *
     * Will be called by the driver after {@link ClientCertificateProvider#hasUpdate} returned true
     * or when the driver establishes the first connection.
     *
     * @returns {Promise<ClientCertificate>|ClientCertificate} the certificate to use for new connections
     */
    ClientCertificateProvider.prototype.getClientCertificate = function () {
        throw new Error('Not Implemented');
    };
    return ClientCertificateProvider;
}());
clientCertificate.ClientCertificateProvider = ClientCertificateProvider;
/**
 * Interface for  {@link ClientCertificateProvider} which provides update certificate function.
 * @interface
 * @since 5.27
 */
var RotatingClientCertificateProvider = /** @class */ (function (_super) {
    __extends$N(RotatingClientCertificateProvider, _super);
    function RotatingClientCertificateProvider() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Updates the certificate stored in the provider.
     *
     * To be called by user-code when a new client certificate is available.
     *
     * @param {ClientCertificate} certificate - the new certificate
     * @throws {TypeError} If initialCertificate is not a ClientCertificate.
     */
    RotatingClientCertificateProvider.prototype.updateCertificate = function (certificate) {
        throw new Error('Not implemented');
    };
    return RotatingClientCertificateProvider;
}(ClientCertificateProvider));
clientCertificate.RotatingClientCertificateProvider = RotatingClientCertificateProvider;
/**
 * Defines the object which holds the common {@link ClientCertificateProviders} used in the Driver
 *
 * @since 5.27
 */
var ClientCertificateProviders = /** @class */ (function () {
    function ClientCertificateProviders() {
    }
    /**
     *
     * @param {object} param0 - The params
     * @param {ClientCertificate} param0.initialCertificate - The certificated used by the driver until {@link RotatingClientCertificateProvider#updateCertificate} get called.
     *
     * @returns {RotatingClientCertificateProvider} The rotating client certificate provider
     * @throws {TypeError} If initialCertificate is not a ClientCertificate.
     */
    ClientCertificateProviders.prototype.rotating = function (_a) {
        var initialCertificate = _a.initialCertificate;
        if (initialCertificate == null || !isClientClientCertificate(initialCertificate)) {
            throw new TypeError("initialCertificate should be ClientCertificate, but got ".concat(json.stringify(initialCertificate)));
        }
        var certificate = __assign$s({}, initialCertificate);
        return new InternalRotatingClientCertificateProvider(certificate);
    };
    return ClientCertificateProviders;
}());
/**
 * Holds the common {@link ClientCertificateProviders} used in the Driver.
 *
 * @since 5.27
 */
var clientCertificateProviders = new ClientCertificateProviders();
clientCertificate.clientCertificateProviders = clientCertificateProviders;
Object.freeze(clientCertificateProviders);
/**
 * Resolves ClientCertificate or ClientCertificateProvider to a ClientCertificateProvider
 *
 * Method validates the input.
 *
 * @private
 * @param input
 * @returns {ClientCertificateProvider?} A client certificate provider if provided a ClientCertificate or a ClientCertificateProvider
 * @throws {TypeError} If input is not a ClientCertificate, ClientCertificateProvider, undefined or null.
 */
function resolveCertificateProvider(input) {
    if (input == null) {
        return undefined;
    }
    if (typeof input === 'object' && 'hasUpdate' in input && 'getClientCertificate' in input &&
        typeof input.getClientCertificate === 'function' && typeof input.hasUpdate === 'function') {
        return input;
    }
    if (isClientClientCertificate(input)) {
        var certificate_1 = __assign$s({}, input);
        return {
            getClientCertificate: function () { return certificate_1; },
            hasUpdate: function () { return false; }
        };
    }
    throw new TypeError("clientCertificate should be configured with ClientCertificate or ClientCertificateProvider, but got ".concat(json.stringify(input)));
}
/**
 * Verify if object is a client certificate
 * @private
 * @param maybeClientCertificate - Maybe the certificate
 * @returns {boolean} if maybeClientCertificate is a client certificate object
 */
function isClientClientCertificate(maybeClientCertificate) {
    return maybeClientCertificate != null &&
        typeof maybeClientCertificate === 'object' &&
        'certfile' in maybeClientCertificate && isCertFile(maybeClientCertificate.certfile) &&
        'keyfile' in maybeClientCertificate && isKeyFile(maybeClientCertificate.keyfile) &&
        isStringOrNotPresent('password', maybeClientCertificate);
}
/**
 * Check value is a cert file
 * @private
 * @param {any} value the value
 * @returns {boolean} is a cert file
 */
function isCertFile(value) {
    return isString(value) || isArrayOf(value, isString);
}
/**
 * Check if the value is a keyfile.
 *
 * @private
 * @param {any} maybeKeyFile might be a keyfile value
 * @returns {boolean} the value is a KeyFile
 */
function isKeyFile(maybeKeyFile) {
    function check(obj) {
        return typeof obj === 'string' ||
            (obj != null &&
                typeof obj === 'object' &&
                'path' in obj && typeof obj.path === 'string' &&
                isStringOrNotPresent('password', obj));
    }
    return check(maybeKeyFile) || isArrayOf(maybeKeyFile, check);
}
/**
 * Verify if value is string
 *
 * @private
 * @param {any} value the value
 * @returns {boolean} is string
 */
function isString(value) {
    return typeof value === 'string';
}
/**
 * Verifies if value is a array of type
 *
 * @private
 * @param {any} value the value
 * @param {function} isType the type checker
 * @returns {boolean} value is array of type
 */
function isArrayOf(value, isType, allowEmpty) {
    if (allowEmpty === void 0) { allowEmpty = false; }
    return Array.isArray(value) &&
        (allowEmpty || value.length > 0) &&
        value.filter(isType).length === value.length;
}
/**
 * Verify if valueName is present in the object and is a string, or not present at all.
 *
 * @private
 * @param {string} valueName The value in the object
 * @param {object} obj The object
 * @returns {boolean} if the value is present in object as string or not present
 */
function isStringOrNotPresent(valueName, obj) {
    return !(valueName in obj) || obj[valueName] == null || typeof obj[valueName] === 'string';
}
/**
 * Internal implementation
 *
 * @private
 */
var InternalRotatingClientCertificateProvider = /** @class */ (function () {
    function InternalRotatingClientCertificateProvider(_certificate, _updated) {
        if (_updated === void 0) { _updated = false; }
        this._certificate = _certificate;
        this._updated = _updated;
    }
    /**
     *
     * @returns {boolean|Promise<boolean>}
     */
    InternalRotatingClientCertificateProvider.prototype.hasUpdate = function () {
        try {
            return this._updated;
        }
        finally {
            this._updated = false;
        }
    };
    /**
     *
     * @returns {ClientCertificate|Promise<ClientCertificate>}
     */
    InternalRotatingClientCertificateProvider.prototype.getClientCertificate = function () {
        return this._certificate;
    };
    /**
     *
     * @param certificate
     * @returns {void}
     */
    InternalRotatingClientCertificateProvider.prototype.updateCertificate = function (certificate) {
        if (!isClientClientCertificate(certificate)) {
            throw new TypeError("certificate should be ClientCertificate, but got ".concat(json.stringify(certificate)));
        }
        this._certificate = __assign$s({}, certificate);
        this._updated = true;
    };
    return InternalRotatingClientCertificateProvider;
}());

(function (exports) {
/**
 * 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 __createBinding = (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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EagerResult = exports.Result = exports.Stats = exports.QueryStatistics = exports.ProfiledPlan = exports.Plan = exports.GqlStatusObject = exports.Notification = exports.ServerInfo = exports.queryType = exports.ResultSummary = exports.Record = exports.isPathSegment = exports.PathSegment = exports.isPath = exports.Path = exports.isUnboundRelationship = exports.UnboundRelationship = exports.isRelationship = exports.Relationship = exports.isNode = exports.Node = exports.Time = exports.LocalTime = exports.LocalDateTime = exports.isTime = exports.isLocalTime = exports.isLocalDateTime = exports.isDuration = exports.isDateTime = exports.isDate = exports.Duration = exports.DateTime = exports.Date = exports.Point = exports.isPoint = exports.internal = exports.toString = exports.toNumber = exports.inSafeRange = exports.isInt = exports.int = exports.Integer = exports.error = exports.isRetriableError = exports.GQLError = exports.newGQLError = exports.Neo4jError = exports.newError = exports.authTokenManagers = void 0;
exports.resolveCertificateProvider = exports.clientCertificateProviders = exports.notificationFilterMinimumSeverityLevel = exports.notificationFilterDisabledClassification = exports.notificationFilterDisabledCategory = exports.notificationSeverityLevel = exports.notificationClassification = exports.notificationCategory = exports.resultTransformers = exports.routing = exports.staticAuthTokenManager = exports.bookmarkManager = exports.auth = exports.json = exports.driver = exports.types = exports.Driver = exports.Session = exports.TransactionPromise = exports.ManagedTransaction = exports.Transaction = exports.Connection = exports.Releasable = exports.ConnectionProvider = void 0;
var error_1 = error;
Object.defineProperty(exports, "newError", { enumerable: true, get: function () { return error_1.newError; } });
Object.defineProperty(exports, "Neo4jError", { enumerable: true, get: function () { return error_1.Neo4jError; } });
Object.defineProperty(exports, "newGQLError", { enumerable: true, get: function () { return error_1.newGQLError; } });
Object.defineProperty(exports, "GQLError", { enumerable: true, get: function () { return error_1.GQLError; } });
Object.defineProperty(exports, "isRetriableError", { enumerable: true, get: function () { return error_1.isRetriableError; } });
var integer_1 = __importStar(integer);
exports.Integer = integer_1.default;
Object.defineProperty(exports, "int", { enumerable: true, get: function () { return integer_1.int; } });
Object.defineProperty(exports, "isInt", { enumerable: true, get: function () { return integer_1.isInt; } });
Object.defineProperty(exports, "inSafeRange", { enumerable: true, get: function () { return integer_1.inSafeRange; } });
Object.defineProperty(exports, "toNumber", { enumerable: true, get: function () { return integer_1.toNumber; } });
Object.defineProperty(exports, "toString", { enumerable: true, get: function () { return integer_1.toString; } });
var temporal_types_1 = temporalTypes;
Object.defineProperty(exports, "Date", { enumerable: true, get: function () { return temporal_types_1.Date; } });
Object.defineProperty(exports, "DateTime", { enumerable: true, get: function () { return temporal_types_1.DateTime; } });
Object.defineProperty(exports, "Duration", { enumerable: true, get: function () { return temporal_types_1.Duration; } });
Object.defineProperty(exports, "isDate", { enumerable: true, get: function () { return temporal_types_1.isDate; } });
Object.defineProperty(exports, "isDateTime", { enumerable: true, get: function () { return temporal_types_1.isDateTime; } });
Object.defineProperty(exports, "isDuration", { enumerable: true, get: function () { return temporal_types_1.isDuration; } });
Object.defineProperty(exports, "isLocalDateTime", { enumerable: true, get: function () { return temporal_types_1.isLocalDateTime; } });
Object.defineProperty(exports, "isLocalTime", { enumerable: true, get: function () { return temporal_types_1.isLocalTime; } });
Object.defineProperty(exports, "isTime", { enumerable: true, get: function () { return temporal_types_1.isTime; } });
Object.defineProperty(exports, "LocalDateTime", { enumerable: true, get: function () { return temporal_types_1.LocalDateTime; } });
Object.defineProperty(exports, "LocalTime", { enumerable: true, get: function () { return temporal_types_1.LocalTime; } });
Object.defineProperty(exports, "Time", { enumerable: true, get: function () { return temporal_types_1.Time; } });
var graph_types_1 = graphTypes;
Object.defineProperty(exports, "Node", { enumerable: true, get: function () { return graph_types_1.Node; } });
Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return graph_types_1.isNode; } });
Object.defineProperty(exports, "Relationship", { enumerable: true, get: function () { return graph_types_1.Relationship; } });
Object.defineProperty(exports, "isRelationship", { enumerable: true, get: function () { return graph_types_1.isRelationship; } });
Object.defineProperty(exports, "UnboundRelationship", { enumerable: true, get: function () { return graph_types_1.UnboundRelationship; } });
Object.defineProperty(exports, "isUnboundRelationship", { enumerable: true, get: function () { return graph_types_1.isUnboundRelationship; } });
Object.defineProperty(exports, "Path", { enumerable: true, get: function () { return graph_types_1.Path; } });
Object.defineProperty(exports, "isPath", { enumerable: true, get: function () { return graph_types_1.isPath; } });
Object.defineProperty(exports, "PathSegment", { enumerable: true, get: function () { return graph_types_1.PathSegment; } });
Object.defineProperty(exports, "isPathSegment", { enumerable: true, get: function () { return graph_types_1.isPathSegment; } });
var record_1 = __importDefault(record);
exports.Record = record_1.default;
var spatial_types_1 = spatialTypes;
Object.defineProperty(exports, "isPoint", { enumerable: true, get: function () { return spatial_types_1.isPoint; } });
Object.defineProperty(exports, "Point", { enumerable: true, get: function () { return spatial_types_1.Point; } });
var result_summary_1 = __importStar(resultSummary);
exports.ResultSummary = result_summary_1.default;
Object.defineProperty(exports, "queryType", { enumerable: true, get: function () { return result_summary_1.queryType; } });
Object.defineProperty(exports, "ServerInfo", { enumerable: true, get: function () { return result_summary_1.ServerInfo; } });
Object.defineProperty(exports, "Plan", { enumerable: true, get: function () { return result_summary_1.Plan; } });
Object.defineProperty(exports, "ProfiledPlan", { enumerable: true, get: function () { return result_summary_1.ProfiledPlan; } });
Object.defineProperty(exports, "QueryStatistics", { enumerable: true, get: function () { return result_summary_1.QueryStatistics; } });
Object.defineProperty(exports, "Stats", { enumerable: true, get: function () { return result_summary_1.Stats; } });
var notification_1 = __importStar(notification);
exports.Notification = notification_1.default;
Object.defineProperty(exports, "GqlStatusObject", { enumerable: true, get: function () { return notification_1.GqlStatusObject; } });
Object.defineProperty(exports, "notificationCategory", { enumerable: true, get: function () { return notification_1.notificationCategory; } });
Object.defineProperty(exports, "notificationClassification", { enumerable: true, get: function () { return notification_1.notificationClassification; } });
Object.defineProperty(exports, "notificationSeverityLevel", { enumerable: true, get: function () { return notification_1.notificationSeverityLevel; } });
var notification_filter_1 = notificationFilter;
Object.defineProperty(exports, "notificationFilterDisabledCategory", { enumerable: true, get: function () { return notification_filter_1.notificationFilterDisabledCategory; } });
Object.defineProperty(exports, "notificationFilterDisabledClassification", { enumerable: true, get: function () { return notification_filter_1.notificationFilterDisabledClassification; } });
Object.defineProperty(exports, "notificationFilterMinimumSeverityLevel", { enumerable: true, get: function () { return notification_filter_1.notificationFilterMinimumSeverityLevel; } });
var result_1 = __importDefault(result);
exports.Result = result_1.default;
var result_eager_1 = __importDefault(resultEager);
exports.EagerResult = result_eager_1.default;
var connection_provider_1 = __importStar(connectionProvider$1);
exports.ConnectionProvider = connection_provider_1.default;
Object.defineProperty(exports, "Releasable", { enumerable: true, get: function () { return connection_provider_1.Releasable; } });
var connection_1 = __importDefault(connection$2);
exports.Connection = connection_1.default;
var transaction_1 = __importDefault(transaction);
exports.Transaction = transaction_1.default;
var transaction_managed_1 = __importDefault(transactionManaged);
exports.ManagedTransaction = transaction_managed_1.default;
var transaction_promise_1 = __importDefault(transactionPromise);
exports.TransactionPromise = transaction_promise_1.default;
var session_1 = __importDefault(session);
exports.Session = session_1.default;
var driver_1 = __importStar(driver), driver$1 = driver_1;
exports.Driver = driver_1.default;
exports.driver = driver$1;
var auth_1 = __importDefault(auth$1);
exports.auth = auth_1.default;
var bookmark_manager_1 = bookmarkManager$1;
Object.defineProperty(exports, "bookmarkManager", { enumerable: true, get: function () { return bookmark_manager_1.bookmarkManager; } });
var auth_token_manager_1 = authTokenManager;
Object.defineProperty(exports, "authTokenManagers", { enumerable: true, get: function () { return auth_token_manager_1.authTokenManagers; } });
Object.defineProperty(exports, "staticAuthTokenManager", { enumerable: true, get: function () { return auth_token_manager_1.staticAuthTokenManager; } });
var driver_2 = driver;
Object.defineProperty(exports, "routing", { enumerable: true, get: function () { return driver_2.routing; } });
var types = __importStar(types$1);
exports.types = types;
var json = __importStar(json$3);
exports.json = json;
var result_transformers_1 = __importDefault(resultTransformers$1);
exports.resultTransformers = result_transformers_1.default;
var client_certificate_1 = clientCertificate;
Object.defineProperty(exports, "clientCertificateProviders", { enumerable: true, get: function () { return client_certificate_1.clientCertificateProviders; } });
Object.defineProperty(exports, "resolveCertificateProvider", { enumerable: true, get: function () { return client_certificate_1.resolveCertificateProvider; } });
var internal$1 = __importStar(internal); // todo: removed afterwards
exports.internal = internal$1;
/**
 * Object containing string constants representing predefined {@link Neo4jError} codes.
 */
var error$1 = {
    SERVICE_UNAVAILABLE: error_1.SERVICE_UNAVAILABLE,
    SESSION_EXPIRED: error_1.SESSION_EXPIRED,
    PROTOCOL_ERROR: error_1.PROTOCOL_ERROR
};
exports.error = error$1;
/**
 * @private
 */
var forExport = {
    authTokenManagers: auth_token_manager_1.authTokenManagers,
    newError: error_1.newError,
    Neo4jError: error_1.Neo4jError,
    newGQLError: error_1.newGQLError,
    GQLError: error_1.GQLError,
    isRetriableError: error_1.isRetriableError,
    error: error$1,
    Integer: integer_1.default,
    int: integer_1.int,
    isInt: integer_1.isInt,
    inSafeRange: integer_1.inSafeRange,
    toNumber: integer_1.toNumber,
    toString: integer_1.toString,
    internal: internal$1,
    isPoint: spatial_types_1.isPoint,
    Point: spatial_types_1.Point,
    Date: temporal_types_1.Date,
    DateTime: temporal_types_1.DateTime,
    Duration: temporal_types_1.Duration,
    isDate: temporal_types_1.isDate,
    isDateTime: temporal_types_1.isDateTime,
    isDuration: temporal_types_1.isDuration,
    isLocalDateTime: temporal_types_1.isLocalDateTime,
    isLocalTime: temporal_types_1.isLocalTime,
    isTime: temporal_types_1.isTime,
    LocalDateTime: temporal_types_1.LocalDateTime,
    LocalTime: temporal_types_1.LocalTime,
    Time: temporal_types_1.Time,
    Node: graph_types_1.Node,
    isNode: graph_types_1.isNode,
    Relationship: graph_types_1.Relationship,
    isRelationship: graph_types_1.isRelationship,
    UnboundRelationship: graph_types_1.UnboundRelationship,
    isUnboundRelationship: graph_types_1.isUnboundRelationship,
    Path: graph_types_1.Path,
    isPath: graph_types_1.isPath,
    PathSegment: graph_types_1.PathSegment,
    isPathSegment: graph_types_1.isPathSegment,
    Record: record_1.default,
    ResultSummary: result_summary_1.default,
    queryType: result_summary_1.queryType,
    ServerInfo: result_summary_1.ServerInfo,
    Notification: notification_1.default,
    GqlStatusObject: notification_1.GqlStatusObject,
    Plan: result_summary_1.Plan,
    ProfiledPlan: result_summary_1.ProfiledPlan,
    QueryStatistics: result_summary_1.QueryStatistics,
    Stats: result_summary_1.Stats,
    Result: result_1.default,
    EagerResult: result_eager_1.default,
    Transaction: transaction_1.default,
    ManagedTransaction: transaction_managed_1.default,
    TransactionPromise: transaction_promise_1.default,
    Session: session_1.default,
    Driver: driver_1.default,
    Connection: connection_1.default,
    Releasable: connection_provider_1.Releasable,
    types: types,
    driver: driver$1,
    json: json,
    auth: auth_1.default,
    bookmarkManager: bookmark_manager_1.bookmarkManager,
    routing: driver_2.routing,
    resultTransformers: result_transformers_1.default,
    notificationCategory: notification_1.notificationCategory,
    notificationClassification: notification_1.notificationClassification,
    notificationSeverityLevel: notification_1.notificationSeverityLevel,
    notificationFilterDisabledCategory: notification_filter_1.notificationFilterDisabledCategory,
    notificationFilterDisabledClassification: notification_filter_1.notificationFilterDisabledClassification,
    notificationFilterMinimumSeverityLevel: notification_filter_1.notificationFilterMinimumSeverityLevel,
    clientCertificateProviders: client_certificate_1.clientCertificateProviders,
    resolveCertificateProvider: client_certificate_1.resolveCertificateProvider
};
exports.default = forExport;
}(lib$1));

var sessionRx = {};

var cjs = {};

var Observable$1 = {};

var Subscriber = {};

var isFunction$1 = {};

Object.defineProperty(isFunction$1, "__esModule", { value: true });
isFunction$1.isFunction = void 0;
function isFunction(value) {
    return typeof value === 'function';
}
isFunction$1.isFunction = isFunction;

var Subscription$1 = {};

var UnsubscriptionError = {};

var createErrorClass$1 = {};

Object.defineProperty(createErrorClass$1, "__esModule", { value: true });
createErrorClass$1.createErrorClass = void 0;
function createErrorClass(createImpl) {
    var _super = function (instance) {
        Error.call(instance);
        instance.stack = new Error().stack;
    };
    var ctorFunc = createImpl(_super);
    ctorFunc.prototype = Object.create(Error.prototype);
    ctorFunc.prototype.constructor = ctorFunc;
    return ctorFunc;
}
createErrorClass$1.createErrorClass = createErrorClass;

Object.defineProperty(UnsubscriptionError, "__esModule", { value: true });
UnsubscriptionError.UnsubscriptionError = void 0;
var createErrorClass_1$5 = createErrorClass$1;
UnsubscriptionError.UnsubscriptionError = createErrorClass_1$5.createErrorClass(function (_super) {
    return function UnsubscriptionErrorImpl(errors) {
        _super(this);
        this.message = errors
            ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ')
            : '';
        this.name = 'UnsubscriptionError';
        this.errors = errors;
    };
});

var arrRemove$1 = {};

Object.defineProperty(arrRemove$1, "__esModule", { value: true });
arrRemove$1.arrRemove = void 0;
function arrRemove(arr, item) {
    if (arr) {
        var index = arr.indexOf(item);
        0 <= index && arr.splice(index, 1);
    }
}
arrRemove$1.arrRemove = arrRemove;

var __values$a = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read$p = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$j = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(Subscription$1, "__esModule", { value: true });
Subscription$1.isSubscription = Subscription$1.EMPTY_SUBSCRIPTION = Subscription$1.Subscription = void 0;
var isFunction_1$p = isFunction$1;
var UnsubscriptionError_1 = UnsubscriptionError;
var arrRemove_1$7 = arrRemove$1;
var Subscription = (function () {
    function Subscription(initialTeardown) {
        this.initialTeardown = initialTeardown;
        this.closed = false;
        this._parentage = null;
        this._finalizers = null;
    }
    Subscription.prototype.unsubscribe = function () {
        var e_1, _a, e_2, _b;
        var errors;
        if (!this.closed) {
            this.closed = true;
            var _parentage = this._parentage;
            if (_parentage) {
                this._parentage = null;
                if (Array.isArray(_parentage)) {
                    try {
                        for (var _parentage_1 = __values$a(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
                            var parent_1 = _parentage_1_1.value;
                            parent_1.remove(this);
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                }
                else {
                    _parentage.remove(this);
                }
            }
            var initialFinalizer = this.initialTeardown;
            if (isFunction_1$p.isFunction(initialFinalizer)) {
                try {
                    initialFinalizer();
                }
                catch (e) {
                    errors = e instanceof UnsubscriptionError_1.UnsubscriptionError ? e.errors : [e];
                }
            }
            var _finalizers = this._finalizers;
            if (_finalizers) {
                this._finalizers = null;
                try {
                    for (var _finalizers_1 = __values$a(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
                        var finalizer = _finalizers_1_1.value;
                        try {
                            execFinalizer(finalizer);
                        }
                        catch (err) {
                            errors = errors !== null && errors !== void 0 ? errors : [];
                            if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
                                errors = __spreadArray$j(__spreadArray$j([], __read$p(errors)), __read$p(err.errors));
                            }
                            else {
                                errors.push(err);
                            }
                        }
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
            if (errors) {
                throw new UnsubscriptionError_1.UnsubscriptionError(errors);
            }
        }
    };
    Subscription.prototype.add = function (teardown) {
        var _a;
        if (teardown && teardown !== this) {
            if (this.closed) {
                execFinalizer(teardown);
            }
            else {
                if (teardown instanceof Subscription) {
                    if (teardown.closed || teardown._hasParent(this)) {
                        return;
                    }
                    teardown._addParent(this);
                }
                (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
            }
        }
    };
    Subscription.prototype._hasParent = function (parent) {
        var _parentage = this._parentage;
        return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
    };
    Subscription.prototype._addParent = function (parent) {
        var _parentage = this._parentage;
        this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
    };
    Subscription.prototype._removeParent = function (parent) {
        var _parentage = this._parentage;
        if (_parentage === parent) {
            this._parentage = null;
        }
        else if (Array.isArray(_parentage)) {
            arrRemove_1$7.arrRemove(_parentage, parent);
        }
    };
    Subscription.prototype.remove = function (teardown) {
        var _finalizers = this._finalizers;
        _finalizers && arrRemove_1$7.arrRemove(_finalizers, teardown);
        if (teardown instanceof Subscription) {
            teardown._removeParent(this);
        }
    };
    Subscription.EMPTY = (function () {
        var empty = new Subscription();
        empty.closed = true;
        return empty;
    })();
    return Subscription;
}());
Subscription$1.Subscription = Subscription;
Subscription$1.EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
    return (value instanceof Subscription ||
        (value && 'closed' in value && isFunction_1$p.isFunction(value.remove) && isFunction_1$p.isFunction(value.add) && isFunction_1$p.isFunction(value.unsubscribe)));
}
Subscription$1.isSubscription = isSubscription;
function execFinalizer(finalizer) {
    if (isFunction_1$p.isFunction(finalizer)) {
        finalizer();
    }
    else {
        finalizer.unsubscribe();
    }
}

var config = {};

Object.defineProperty(config, "__esModule", { value: true });
config.config = void 0;
config.config = {
    onUnhandledError: null,
    onStoppedNotification: null,
    Promise: undefined,
    useDeprecatedSynchronousErrorHandling: false,
    useDeprecatedNextContext: false,
};

var reportUnhandledError$1 = {};

var timeoutProvider = {};

(function (exports) {
var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeoutProvider = void 0;
exports.timeoutProvider = {
    setTimeout: function (handler, timeout) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        var delegate = exports.timeoutProvider.delegate;
        if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
            return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
        }
        return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
    },
    clearTimeout: function (handle) {
        var delegate = exports.timeoutProvider.delegate;
        return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
    },
    delegate: undefined,
};

}(timeoutProvider));

Object.defineProperty(reportUnhandledError$1, "__esModule", { value: true });
reportUnhandledError$1.reportUnhandledError = void 0;
var config_1$2 = config;
var timeoutProvider_1 = timeoutProvider;
function reportUnhandledError(err) {
    timeoutProvider_1.timeoutProvider.setTimeout(function () {
        var onUnhandledError = config_1$2.config.onUnhandledError;
        if (onUnhandledError) {
            onUnhandledError(err);
        }
        else {
            throw err;
        }
    });
}
reportUnhandledError$1.reportUnhandledError = reportUnhandledError;

var noop$1 = {};

Object.defineProperty(noop$1, "__esModule", { value: true });
noop$1.noop = void 0;
function noop() { }
noop$1.noop = noop;

var NotificationFactories = {};

Object.defineProperty(NotificationFactories, "__esModule", { value: true });
NotificationFactories.createNotification = NotificationFactories.nextNotification = NotificationFactories.errorNotification = NotificationFactories.COMPLETE_NOTIFICATION = void 0;
NotificationFactories.COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();
function errorNotification(error) {
    return createNotification('E', undefined, error);
}
NotificationFactories.errorNotification = errorNotification;
function nextNotification(value) {
    return createNotification('N', value, undefined);
}
NotificationFactories.nextNotification = nextNotification;
function createNotification(kind, value, error) {
    return {
        kind: kind,
        value: value,
        error: error,
    };
}
NotificationFactories.createNotification = createNotification;

var errorContext$1 = {};

Object.defineProperty(errorContext$1, "__esModule", { value: true });
errorContext$1.captureError = errorContext$1.errorContext = void 0;
var config_1$1 = config;
var context = null;
function errorContext(cb) {
    if (config_1$1.config.useDeprecatedSynchronousErrorHandling) {
        var isRoot = !context;
        if (isRoot) {
            context = { errorThrown: false, error: null };
        }
        cb();
        if (isRoot) {
            var _a = context, errorThrown = _a.errorThrown, error = _a.error;
            context = null;
            if (errorThrown) {
                throw error;
            }
        }
    }
    else {
        cb();
    }
}
errorContext$1.errorContext = errorContext;
function captureError(err) {
    if (config_1$1.config.useDeprecatedSynchronousErrorHandling && context) {
        context.errorThrown = true;
        context.error = err;
    }
}
errorContext$1.captureError = captureError;

(function (exports) {
var __extends = (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 __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EMPTY_OBSERVER = exports.SafeSubscriber = exports.Subscriber = void 0;
var isFunction_1 = isFunction$1;
var Subscription_1 = Subscription$1;
var config_1 = config;
var reportUnhandledError_1 = reportUnhandledError$1;
var noop_1 = noop$1;
var NotificationFactories_1 = NotificationFactories;
var timeoutProvider_1 = timeoutProvider;
var errorContext_1 = errorContext$1;
var Subscriber = (function (_super) {
    __extends(Subscriber, _super);
    function Subscriber(destination) {
        var _this = _super.call(this) || this;
        _this.isStopped = false;
        if (destination) {
            _this.destination = destination;
            if (Subscription_1.isSubscription(destination)) {
                destination.add(_this);
            }
        }
        else {
            _this.destination = exports.EMPTY_OBSERVER;
        }
        return _this;
    }
    Subscriber.create = function (next, error, complete) {
        return new SafeSubscriber(next, error, complete);
    };
    Subscriber.prototype.next = function (value) {
        if (this.isStopped) {
            handleStoppedNotification(NotificationFactories_1.nextNotification(value), this);
        }
        else {
            this._next(value);
        }
    };
    Subscriber.prototype.error = function (err) {
        if (this.isStopped) {
            handleStoppedNotification(NotificationFactories_1.errorNotification(err), this);
        }
        else {
            this.isStopped = true;
            this._error(err);
        }
    };
    Subscriber.prototype.complete = function () {
        if (this.isStopped) {
            handleStoppedNotification(NotificationFactories_1.COMPLETE_NOTIFICATION, this);
        }
        else {
            this.isStopped = true;
            this._complete();
        }
    };
    Subscriber.prototype.unsubscribe = function () {
        if (!this.closed) {
            this.isStopped = true;
            _super.prototype.unsubscribe.call(this);
            this.destination = null;
        }
    };
    Subscriber.prototype._next = function (value) {
        this.destination.next(value);
    };
    Subscriber.prototype._error = function (err) {
        try {
            this.destination.error(err);
        }
        finally {
            this.unsubscribe();
        }
    };
    Subscriber.prototype._complete = function () {
        try {
            this.destination.complete();
        }
        finally {
            this.unsubscribe();
        }
    };
    return Subscriber;
}(Subscription_1.Subscription));
exports.Subscriber = Subscriber;
var _bind = Function.prototype.bind;
function bind(fn, thisArg) {
    return _bind.call(fn, thisArg);
}
var ConsumerObserver = (function () {
    function ConsumerObserver(partialObserver) {
        this.partialObserver = partialObserver;
    }
    ConsumerObserver.prototype.next = function (value) {
        var partialObserver = this.partialObserver;
        if (partialObserver.next) {
            try {
                partialObserver.next(value);
            }
            catch (error) {
                handleUnhandledError(error);
            }
        }
    };
    ConsumerObserver.prototype.error = function (err) {
        var partialObserver = this.partialObserver;
        if (partialObserver.error) {
            try {
                partialObserver.error(err);
            }
            catch (error) {
                handleUnhandledError(error);
            }
        }
        else {
            handleUnhandledError(err);
        }
    };
    ConsumerObserver.prototype.complete = function () {
        var partialObserver = this.partialObserver;
        if (partialObserver.complete) {
            try {
                partialObserver.complete();
            }
            catch (error) {
                handleUnhandledError(error);
            }
        }
    };
    return ConsumerObserver;
}());
var SafeSubscriber = (function (_super) {
    __extends(SafeSubscriber, _super);
    function SafeSubscriber(observerOrNext, error, complete) {
        var _this = _super.call(this) || this;
        var partialObserver;
        if (isFunction_1.isFunction(observerOrNext) || !observerOrNext) {
            partialObserver = {
                next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
                error: error !== null && error !== void 0 ? error : undefined,
                complete: complete !== null && complete !== void 0 ? complete : undefined,
            };
        }
        else {
            var context_1;
            if (_this && config_1.config.useDeprecatedNextContext) {
                context_1 = Object.create(observerOrNext);
                context_1.unsubscribe = function () { return _this.unsubscribe(); };
                partialObserver = {
                    next: observerOrNext.next && bind(observerOrNext.next, context_1),
                    error: observerOrNext.error && bind(observerOrNext.error, context_1),
                    complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
                };
            }
            else {
                partialObserver = observerOrNext;
            }
        }
        _this.destination = new ConsumerObserver(partialObserver);
        return _this;
    }
    return SafeSubscriber;
}(Subscriber));
exports.SafeSubscriber = SafeSubscriber;
function handleUnhandledError(error) {
    if (config_1.config.useDeprecatedSynchronousErrorHandling) {
        errorContext_1.captureError(error);
    }
    else {
        reportUnhandledError_1.reportUnhandledError(error);
    }
}
function defaultErrorHandler(err) {
    throw err;
}
function handleStoppedNotification(notification, subscriber) {
    var onStoppedNotification = config_1.config.onStoppedNotification;
    onStoppedNotification && timeoutProvider_1.timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });
}
exports.EMPTY_OBSERVER = {
    closed: true,
    next: noop_1.noop,
    error: defaultErrorHandler,
    complete: noop_1.noop,
};

}(Subscriber));

var observable = {};

Object.defineProperty(observable, "__esModule", { value: true });
observable.observable = void 0;
observable.observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();

var pipe$1 = {};

var identity$2 = {};

Object.defineProperty(identity$2, "__esModule", { value: true });
identity$2.identity = void 0;
function identity$1(x) {
    return x;
}
identity$2.identity = identity$1;

Object.defineProperty(pipe$1, "__esModule", { value: true });
pipe$1.pipeFromArray = pipe$1.pipe = void 0;
var identity_1$e = identity$2;
function pipe() {
    var fns = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        fns[_i] = arguments[_i];
    }
    return pipeFromArray(fns);
}
pipe$1.pipe = pipe;
function pipeFromArray(fns) {
    if (fns.length === 0) {
        return identity_1$e.identity;
    }
    if (fns.length === 1) {
        return fns[0];
    }
    return function piped(input) {
        return fns.reduce(function (prev, fn) { return fn(prev); }, input);
    };
}
pipe$1.pipeFromArray = pipeFromArray;

Object.defineProperty(Observable$1, "__esModule", { value: true });
Observable$1.Observable = void 0;
var Subscriber_1$3 = Subscriber;
var Subscription_1$8 = Subscription$1;
var observable_1$2 = observable;
var pipe_1$2 = pipe$1;
var config_1 = config;
var isFunction_1$o = isFunction$1;
var errorContext_1$1 = errorContext$1;
var Observable = (function () {
    function Observable(subscribe) {
        if (subscribe) {
            this._subscribe = subscribe;
        }
    }
    Observable.prototype.lift = function (operator) {
        var observable = new Observable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    };
    Observable.prototype.subscribe = function (observerOrNext, error, complete) {
        var _this = this;
        var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new Subscriber_1$3.SafeSubscriber(observerOrNext, error, complete);
        errorContext_1$1.errorContext(function () {
            var _a = _this, operator = _a.operator, source = _a.source;
            subscriber.add(operator
                ?
                    operator.call(subscriber, source)
                : source
                    ?
                        _this._subscribe(subscriber)
                    :
                        _this._trySubscribe(subscriber));
        });
        return subscriber;
    };
    Observable.prototype._trySubscribe = function (sink) {
        try {
            return this._subscribe(sink);
        }
        catch (err) {
            sink.error(err);
        }
    };
    Observable.prototype.forEach = function (next, promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var subscriber = new Subscriber_1$3.SafeSubscriber({
                next: function (value) {
                    try {
                        next(value);
                    }
                    catch (err) {
                        reject(err);
                        subscriber.unsubscribe();
                    }
                },
                error: reject,
                complete: resolve,
            });
            _this.subscribe(subscriber);
        });
    };
    Observable.prototype._subscribe = function (subscriber) {
        var _a;
        return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
    };
    Observable.prototype[observable_1$2.observable] = function () {
        return this;
    };
    Observable.prototype.pipe = function () {
        var operations = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            operations[_i] = arguments[_i];
        }
        return pipe_1$2.pipeFromArray(operations)(this);
    };
    Observable.prototype.toPromise = function (promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var value;
            _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
        });
    };
    Observable.create = function (subscribe) {
        return new Observable(subscribe);
    };
    return Observable;
}());
Observable$1.Observable = Observable;
function getPromiseCtor(promiseCtor) {
    var _a;
    return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config_1.config.Promise) !== null && _a !== void 0 ? _a : Promise;
}
function isObserver(value) {
    return value && isFunction_1$o.isFunction(value.next) && isFunction_1$o.isFunction(value.error) && isFunction_1$o.isFunction(value.complete);
}
function isSubscriber(value) {
    return (value && value instanceof Subscriber_1$3.Subscriber) || (isObserver(value) && Subscription_1$8.isSubscription(value));
}

var ConnectableObservable$1 = {};

var refCount$1 = {};

var lift = {};

Object.defineProperty(lift, "__esModule", { value: true });
lift.operate = lift.hasLift = void 0;
var isFunction_1$n = isFunction$1;
function hasLift(source) {
    return isFunction_1$n.isFunction(source === null || source === void 0 ? void 0 : source.lift);
}
lift.hasLift = hasLift;
function operate(init) {
    return function (source) {
        if (hasLift(source)) {
            return source.lift(function (liftedSource) {
                try {
                    return init(liftedSource, this);
                }
                catch (err) {
                    this.error(err);
                }
            });
        }
        throw new TypeError('Unable to lift unknown Observable type');
    };
}
lift.operate = operate;

var OperatorSubscriber$1 = {};

var __extends$M = (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 __());
    };
})();
Object.defineProperty(OperatorSubscriber$1, "__esModule", { value: true });
OperatorSubscriber$1.OperatorSubscriber = OperatorSubscriber$1.createOperatorSubscriber = void 0;
var Subscriber_1$2 = Subscriber;
function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
    return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
OperatorSubscriber$1.createOperatorSubscriber = createOperatorSubscriber;
var OperatorSubscriber = (function (_super) {
    __extends$M(OperatorSubscriber, _super);
    function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
        var _this = _super.call(this, destination) || this;
        _this.onFinalize = onFinalize;
        _this.shouldUnsubscribe = shouldUnsubscribe;
        _this._next = onNext
            ? function (value) {
                try {
                    onNext(value);
                }
                catch (err) {
                    destination.error(err);
                }
            }
            : _super.prototype._next;
        _this._error = onError
            ? function (err) {
                try {
                    onError(err);
                }
                catch (err) {
                    destination.error(err);
                }
                finally {
                    this.unsubscribe();
                }
            }
            : _super.prototype._error;
        _this._complete = onComplete
            ? function () {
                try {
                    onComplete();
                }
                catch (err) {
                    destination.error(err);
                }
                finally {
                    this.unsubscribe();
                }
            }
            : _super.prototype._complete;
        return _this;
    }
    OperatorSubscriber.prototype.unsubscribe = function () {
        var _a;
        if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
            var closed_1 = this.closed;
            _super.prototype.unsubscribe.call(this);
            !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
        }
    };
    return OperatorSubscriber;
}(Subscriber_1$2.Subscriber));
OperatorSubscriber$1.OperatorSubscriber = OperatorSubscriber;

Object.defineProperty(refCount$1, "__esModule", { value: true });
refCount$1.refCount = void 0;
var lift_1$14 = lift;
var OperatorSubscriber_1$V = OperatorSubscriber$1;
function refCount() {
    return lift_1$14.operate(function (source, subscriber) {
        var connection = null;
        source._refCount++;
        var refCounter = OperatorSubscriber_1$V.createOperatorSubscriber(subscriber, undefined, undefined, undefined, function () {
            if (!source || source._refCount <= 0 || 0 < --source._refCount) {
                connection = null;
                return;
            }
            var sharedConnection = source._connection;
            var conn = connection;
            connection = null;
            if (sharedConnection && (!conn || sharedConnection === conn)) {
                sharedConnection.unsubscribe();
            }
            subscriber.unsubscribe();
        });
        source.subscribe(refCounter);
        if (!refCounter.closed) {
            connection = source.connect();
        }
    });
}
refCount$1.refCount = refCount;

var __extends$L = (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 __());
    };
})();
Object.defineProperty(ConnectableObservable$1, "__esModule", { value: true });
ConnectableObservable$1.ConnectableObservable = void 0;
var Observable_1$n = Observable$1;
var Subscription_1$7 = Subscription$1;
var refCount_1 = refCount$1;
var OperatorSubscriber_1$U = OperatorSubscriber$1;
var lift_1$13 = lift;
var ConnectableObservable = (function (_super) {
    __extends$L(ConnectableObservable, _super);
    function ConnectableObservable(source, subjectFactory) {
        var _this = _super.call(this) || this;
        _this.source = source;
        _this.subjectFactory = subjectFactory;
        _this._subject = null;
        _this._refCount = 0;
        _this._connection = null;
        if (lift_1$13.hasLift(source)) {
            _this.lift = source.lift;
        }
        return _this;
    }
    ConnectableObservable.prototype._subscribe = function (subscriber) {
        return this.getSubject().subscribe(subscriber);
    };
    ConnectableObservable.prototype.getSubject = function () {
        var subject = this._subject;
        if (!subject || subject.isStopped) {
            this._subject = this.subjectFactory();
        }
        return this._subject;
    };
    ConnectableObservable.prototype._teardown = function () {
        this._refCount = 0;
        var _connection = this._connection;
        this._subject = this._connection = null;
        _connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe();
    };
    ConnectableObservable.prototype.connect = function () {
        var _this = this;
        var connection = this._connection;
        if (!connection) {
            connection = this._connection = new Subscription_1$7.Subscription();
            var subject_1 = this.getSubject();
            connection.add(this.source.subscribe(OperatorSubscriber_1$U.createOperatorSubscriber(subject_1, undefined, function () {
                _this._teardown();
                subject_1.complete();
            }, function (err) {
                _this._teardown();
                subject_1.error(err);
            }, function () { return _this._teardown(); })));
            if (connection.closed) {
                this._connection = null;
                connection = Subscription_1$7.Subscription.EMPTY;
            }
        }
        return connection;
    };
    ConnectableObservable.prototype.refCount = function () {
        return refCount_1.refCount()(this);
    };
    return ConnectableObservable;
}(Observable_1$n.Observable));
ConnectableObservable$1.ConnectableObservable = ConnectableObservable;

var animationFrames$1 = {};

var performanceTimestampProvider = {};

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.performanceTimestampProvider = void 0;
exports.performanceTimestampProvider = {
    now: function () {
        return (exports.performanceTimestampProvider.delegate || performance).now();
    },
    delegate: undefined,
};

}(performanceTimestampProvider));

var animationFrameProvider = {};

(function (exports) {
var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.animationFrameProvider = void 0;
var Subscription_1 = Subscription$1;
exports.animationFrameProvider = {
    schedule: function (callback) {
        var request = requestAnimationFrame;
        var cancel = cancelAnimationFrame;
        var delegate = exports.animationFrameProvider.delegate;
        if (delegate) {
            request = delegate.requestAnimationFrame;
            cancel = delegate.cancelAnimationFrame;
        }
        var handle = request(function (timestamp) {
            cancel = undefined;
            callback(timestamp);
        });
        return new Subscription_1.Subscription(function () { return cancel === null || cancel === void 0 ? void 0 : cancel(handle); });
    },
    requestAnimationFrame: function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var delegate = exports.animationFrameProvider.delegate;
        return ((delegate === null || delegate === void 0 ? void 0 : delegate.requestAnimationFrame) || requestAnimationFrame).apply(void 0, __spreadArray([], __read(args)));
    },
    cancelAnimationFrame: function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var delegate = exports.animationFrameProvider.delegate;
        return ((delegate === null || delegate === void 0 ? void 0 : delegate.cancelAnimationFrame) || cancelAnimationFrame).apply(void 0, __spreadArray([], __read(args)));
    },
    delegate: undefined,
};

}(animationFrameProvider));

Object.defineProperty(animationFrames$1, "__esModule", { value: true });
animationFrames$1.animationFrames = void 0;
var Observable_1$m = Observable$1;
var performanceTimestampProvider_1 = performanceTimestampProvider;
var animationFrameProvider_1$1 = animationFrameProvider;
function animationFrames(timestampProvider) {
    return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;
}
animationFrames$1.animationFrames = animationFrames;
function animationFramesFactory(timestampProvider) {
    return new Observable_1$m.Observable(function (subscriber) {
        var provider = timestampProvider || performanceTimestampProvider_1.performanceTimestampProvider;
        var start = provider.now();
        var id = 0;
        var run = function () {
            if (!subscriber.closed) {
                id = animationFrameProvider_1$1.animationFrameProvider.requestAnimationFrame(function (timestamp) {
                    id = 0;
                    var now = provider.now();
                    subscriber.next({
                        timestamp: timestampProvider ? now : timestamp,
                        elapsed: now - start,
                    });
                    run();
                });
            }
        };
        run();
        return function () {
            if (id) {
                animationFrameProvider_1$1.animationFrameProvider.cancelAnimationFrame(id);
            }
        };
    });
}
var DEFAULT_ANIMATION_FRAMES = animationFramesFactory();

var Subject$1 = {};

var ObjectUnsubscribedError = {};

Object.defineProperty(ObjectUnsubscribedError, "__esModule", { value: true });
ObjectUnsubscribedError.ObjectUnsubscribedError = void 0;
var createErrorClass_1$4 = createErrorClass$1;
ObjectUnsubscribedError.ObjectUnsubscribedError = createErrorClass_1$4.createErrorClass(function (_super) {
    return function ObjectUnsubscribedErrorImpl() {
        _super(this);
        this.name = 'ObjectUnsubscribedError';
        this.message = 'object unsubscribed';
    };
});

var __extends$K = (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 __values$9 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(Subject$1, "__esModule", { value: true });
Subject$1.AnonymousSubject = Subject$1.Subject = void 0;
var Observable_1$l = Observable$1;
var Subscription_1$6 = Subscription$1;
var ObjectUnsubscribedError_1 = ObjectUnsubscribedError;
var arrRemove_1$6 = arrRemove$1;
var errorContext_1 = errorContext$1;
var Subject = (function (_super) {
    __extends$K(Subject, _super);
    function Subject() {
        var _this = _super.call(this) || this;
        _this.closed = false;
        _this.currentObservers = null;
        _this.observers = [];
        _this.isStopped = false;
        _this.hasError = false;
        _this.thrownError = null;
        return _this;
    }
    Subject.prototype.lift = function (operator) {
        var subject = new AnonymousSubject(this, this);
        subject.operator = operator;
        return subject;
    };
    Subject.prototype._throwIfClosed = function () {
        if (this.closed) {
            throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
        }
    };
    Subject.prototype.next = function (value) {
        var _this = this;
        errorContext_1.errorContext(function () {
            var e_1, _a;
            _this._throwIfClosed();
            if (!_this.isStopped) {
                if (!_this.currentObservers) {
                    _this.currentObservers = Array.from(_this.observers);
                }
                try {
                    for (var _b = __values$9(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var observer = _c.value;
                        observer.next(value);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
        });
    };
    Subject.prototype.error = function (err) {
        var _this = this;
        errorContext_1.errorContext(function () {
            _this._throwIfClosed();
            if (!_this.isStopped) {
                _this.hasError = _this.isStopped = true;
                _this.thrownError = err;
                var observers = _this.observers;
                while (observers.length) {
                    observers.shift().error(err);
                }
            }
        });
    };
    Subject.prototype.complete = function () {
        var _this = this;
        errorContext_1.errorContext(function () {
            _this._throwIfClosed();
            if (!_this.isStopped) {
                _this.isStopped = true;
                var observers = _this.observers;
                while (observers.length) {
                    observers.shift().complete();
                }
            }
        });
    };
    Subject.prototype.unsubscribe = function () {
        this.isStopped = this.closed = true;
        this.observers = this.currentObservers = null;
    };
    Object.defineProperty(Subject.prototype, "observed", {
        get: function () {
            var _a;
            return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
        },
        enumerable: false,
        configurable: true
    });
    Subject.prototype._trySubscribe = function (subscriber) {
        this._throwIfClosed();
        return _super.prototype._trySubscribe.call(this, subscriber);
    };
    Subject.prototype._subscribe = function (subscriber) {
        this._throwIfClosed();
        this._checkFinalizedStatuses(subscriber);
        return this._innerSubscribe(subscriber);
    };
    Subject.prototype._innerSubscribe = function (subscriber) {
        var _this = this;
        var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
        if (hasError || isStopped) {
            return Subscription_1$6.EMPTY_SUBSCRIPTION;
        }
        this.currentObservers = null;
        observers.push(subscriber);
        return new Subscription_1$6.Subscription(function () {
            _this.currentObservers = null;
            arrRemove_1$6.arrRemove(observers, subscriber);
        });
    };
    Subject.prototype._checkFinalizedStatuses = function (subscriber) {
        var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
        if (hasError) {
            subscriber.error(thrownError);
        }
        else if (isStopped) {
            subscriber.complete();
        }
    };
    Subject.prototype.asObservable = function () {
        var observable = new Observable_1$l.Observable();
        observable.source = this;
        return observable;
    };
    Subject.create = function (destination, source) {
        return new AnonymousSubject(destination, source);
    };
    return Subject;
}(Observable_1$l.Observable));
Subject$1.Subject = Subject;
var AnonymousSubject = (function (_super) {
    __extends$K(AnonymousSubject, _super);
    function AnonymousSubject(destination, source) {
        var _this = _super.call(this) || this;
        _this.destination = destination;
        _this.source = source;
        return _this;
    }
    AnonymousSubject.prototype.next = function (value) {
        var _a, _b;
        (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
    };
    AnonymousSubject.prototype.error = function (err) {
        var _a, _b;
        (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
    };
    AnonymousSubject.prototype.complete = function () {
        var _a, _b;
        (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
    };
    AnonymousSubject.prototype._subscribe = function (subscriber) {
        var _a, _b;
        return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : Subscription_1$6.EMPTY_SUBSCRIPTION;
    };
    return AnonymousSubject;
}(Subject));
Subject$1.AnonymousSubject = AnonymousSubject;

var BehaviorSubject$1 = {};

var __extends$J = (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 __());
    };
})();
Object.defineProperty(BehaviorSubject$1, "__esModule", { value: true });
BehaviorSubject$1.BehaviorSubject = void 0;
var Subject_1$e = Subject$1;
var BehaviorSubject = (function (_super) {
    __extends$J(BehaviorSubject, _super);
    function BehaviorSubject(_value) {
        var _this = _super.call(this) || this;
        _this._value = _value;
        return _this;
    }
    Object.defineProperty(BehaviorSubject.prototype, "value", {
        get: function () {
            return this.getValue();
        },
        enumerable: false,
        configurable: true
    });
    BehaviorSubject.prototype._subscribe = function (subscriber) {
        var subscription = _super.prototype._subscribe.call(this, subscriber);
        !subscription.closed && subscriber.next(this._value);
        return subscription;
    };
    BehaviorSubject.prototype.getValue = function () {
        var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
        if (hasError) {
            throw thrownError;
        }
        this._throwIfClosed();
        return _value;
    };
    BehaviorSubject.prototype.next = function (value) {
        _super.prototype.next.call(this, (this._value = value));
    };
    return BehaviorSubject;
}(Subject_1$e.Subject));
BehaviorSubject$1.BehaviorSubject = BehaviorSubject;

var ReplaySubject$1 = {};

var dateTimestampProvider = {};

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.dateTimestampProvider = void 0;
exports.dateTimestampProvider = {
    now: function () {
        return (exports.dateTimestampProvider.delegate || Date).now();
    },
    delegate: undefined,
};

}(dateTimestampProvider));

var __extends$I = (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 __());
    };
})();
Object.defineProperty(ReplaySubject$1, "__esModule", { value: true });
ReplaySubject$1.ReplaySubject = void 0;
var Subject_1$d = Subject$1;
var dateTimestampProvider_1$2 = dateTimestampProvider;
var ReplaySubject = (function (_super) {
    __extends$I(ReplaySubject, _super);
    function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
        if (_bufferSize === void 0) { _bufferSize = Infinity; }
        if (_windowTime === void 0) { _windowTime = Infinity; }
        if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider_1$2.dateTimestampProvider; }
        var _this = _super.call(this) || this;
        _this._bufferSize = _bufferSize;
        _this._windowTime = _windowTime;
        _this._timestampProvider = _timestampProvider;
        _this._buffer = [];
        _this._infiniteTimeWindow = true;
        _this._infiniteTimeWindow = _windowTime === Infinity;
        _this._bufferSize = Math.max(1, _bufferSize);
        _this._windowTime = Math.max(1, _windowTime);
        return _this;
    }
    ReplaySubject.prototype.next = function (value) {
        var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
        if (!isStopped) {
            _buffer.push(value);
            !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
        }
        this._trimBuffer();
        _super.prototype.next.call(this, value);
    };
    ReplaySubject.prototype._subscribe = function (subscriber) {
        this._throwIfClosed();
        this._trimBuffer();
        var subscription = this._innerSubscribe(subscriber);
        var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
        var copy = _buffer.slice();
        for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
            subscriber.next(copy[i]);
        }
        this._checkFinalizedStatuses(subscriber);
        return subscription;
    };
    ReplaySubject.prototype._trimBuffer = function () {
        var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
        var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
        _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
        if (!_infiniteTimeWindow) {
            var now = _timestampProvider.now();
            var last = 0;
            for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
                last = i;
            }
            last && _buffer.splice(0, last + 1);
        }
    };
    return ReplaySubject;
}(Subject_1$d.Subject));
ReplaySubject$1.ReplaySubject = ReplaySubject;

var AsyncSubject$1 = {};

var __extends$H = (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 __());
    };
})();
Object.defineProperty(AsyncSubject$1, "__esModule", { value: true });
AsyncSubject$1.AsyncSubject = void 0;
var Subject_1$c = Subject$1;
var AsyncSubject = (function (_super) {
    __extends$H(AsyncSubject, _super);
    function AsyncSubject() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._value = null;
        _this._hasValue = false;
        _this._isComplete = false;
        return _this;
    }
    AsyncSubject.prototype._checkFinalizedStatuses = function (subscriber) {
        var _a = this, hasError = _a.hasError, _hasValue = _a._hasValue, _value = _a._value, thrownError = _a.thrownError, isStopped = _a.isStopped, _isComplete = _a._isComplete;
        if (hasError) {
            subscriber.error(thrownError);
        }
        else if (isStopped || _isComplete) {
            _hasValue && subscriber.next(_value);
            subscriber.complete();
        }
    };
    AsyncSubject.prototype.next = function (value) {
        if (!this.isStopped) {
            this._value = value;
            this._hasValue = true;
        }
    };
    AsyncSubject.prototype.complete = function () {
        var _a = this, _hasValue = _a._hasValue, _value = _a._value, _isComplete = _a._isComplete;
        if (!_isComplete) {
            this._isComplete = true;
            _hasValue && _super.prototype.next.call(this, _value);
            _super.prototype.complete.call(this);
        }
    };
    return AsyncSubject;
}(Subject_1$c.Subject));
AsyncSubject$1.AsyncSubject = AsyncSubject;

var asap = {};

var AsapAction$1 = {};

var AsyncAction$1 = {};

var Action$1 = {};

var __extends$G = (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 __());
    };
})();
Object.defineProperty(Action$1, "__esModule", { value: true });
Action$1.Action = void 0;
var Subscription_1$5 = Subscription$1;
var Action = (function (_super) {
    __extends$G(Action, _super);
    function Action(scheduler, work) {
        return _super.call(this) || this;
    }
    Action.prototype.schedule = function (state, delay) {
        return this;
    };
    return Action;
}(Subscription_1$5.Subscription));
Action$1.Action = Action;

var intervalProvider = {};

(function (exports) {
var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.intervalProvider = void 0;
exports.intervalProvider = {
    setInterval: function (handler, timeout) {
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        var delegate = exports.intervalProvider.delegate;
        if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
            return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args)));
        }
        return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
    },
    clearInterval: function (handle) {
        var delegate = exports.intervalProvider.delegate;
        return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
    },
    delegate: undefined,
};

}(intervalProvider));

var __extends$F = (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 __());
    };
})();
Object.defineProperty(AsyncAction$1, "__esModule", { value: true });
AsyncAction$1.AsyncAction = void 0;
var Action_1 = Action$1;
var intervalProvider_1 = intervalProvider;
var arrRemove_1$5 = arrRemove$1;
var AsyncAction = (function (_super) {
    __extends$F(AsyncAction, _super);
    function AsyncAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        _this.pending = false;
        return _this;
    }
    AsyncAction.prototype.schedule = function (state, delay) {
        var _a;
        if (delay === void 0) { delay = 0; }
        if (this.closed) {
            return this;
        }
        this.state = state;
        var id = this.id;
        var scheduler = this.scheduler;
        if (id != null) {
            this.id = this.recycleAsyncId(scheduler, id, delay);
        }
        this.pending = true;
        this.delay = delay;
        this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay);
        return this;
    };
    AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
        if (delay === void 0) { delay = 0; }
        return intervalProvider_1.intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
    };
    AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
        if (delay === void 0) { delay = 0; }
        if (delay != null && this.delay === delay && this.pending === false) {
            return id;
        }
        if (id != null) {
            intervalProvider_1.intervalProvider.clearInterval(id);
        }
        return undefined;
    };
    AsyncAction.prototype.execute = function (state, delay) {
        if (this.closed) {
            return new Error('executing a cancelled action');
        }
        this.pending = false;
        var error = this._execute(state, delay);
        if (error) {
            return error;
        }
        else if (this.pending === false && this.id != null) {
            this.id = this.recycleAsyncId(this.scheduler, this.id, null);
        }
    };
    AsyncAction.prototype._execute = function (state, _delay) {
        var errored = false;
        var errorValue;
        try {
            this.work(state);
        }
        catch (e) {
            errored = true;
            errorValue = e ? e : new Error('Scheduled action threw falsy error');
        }
        if (errored) {
            this.unsubscribe();
            return errorValue;
        }
    };
    AsyncAction.prototype.unsubscribe = function () {
        if (!this.closed) {
            var _a = this, id = _a.id, scheduler = _a.scheduler;
            var actions = scheduler.actions;
            this.work = this.state = this.scheduler = null;
            this.pending = false;
            arrRemove_1$5.arrRemove(actions, this);
            if (id != null) {
                this.id = this.recycleAsyncId(scheduler, id, null);
            }
            this.delay = null;
            _super.prototype.unsubscribe.call(this);
        }
    };
    return AsyncAction;
}(Action_1.Action));
AsyncAction$1.AsyncAction = AsyncAction;

var immediateProvider = {};

var Immediate = {};

Object.defineProperty(Immediate, "__esModule", { value: true });
Immediate.TestTools = Immediate.Immediate = void 0;
var nextHandle = 1;
var resolved;
var activeHandles = {};
function findAndClearHandle(handle) {
    if (handle in activeHandles) {
        delete activeHandles[handle];
        return true;
    }
    return false;
}
Immediate.Immediate = {
    setImmediate: function (cb) {
        var handle = nextHandle++;
        activeHandles[handle] = true;
        if (!resolved) {
            resolved = Promise.resolve();
        }
        resolved.then(function () { return findAndClearHandle(handle) && cb(); });
        return handle;
    },
    clearImmediate: function (handle) {
        findAndClearHandle(handle);
    },
};
Immediate.TestTools = {
    pending: function () {
        return Object.keys(activeHandles).length;
    }
};

(function (exports) {
var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.immediateProvider = void 0;
var Immediate_1 = Immediate;
var setImmediate = Immediate_1.Immediate.setImmediate, clearImmediate = Immediate_1.Immediate.clearImmediate;
exports.immediateProvider = {
    setImmediate: function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var delegate = exports.immediateProvider.delegate;
        return ((delegate === null || delegate === void 0 ? void 0 : delegate.setImmediate) || setImmediate).apply(void 0, __spreadArray([], __read(args)));
    },
    clearImmediate: function (handle) {
        var delegate = exports.immediateProvider.delegate;
        return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearImmediate) || clearImmediate)(handle);
    },
    delegate: undefined,
};

}(immediateProvider));

var __extends$E = (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 __());
    };
})();
Object.defineProperty(AsapAction$1, "__esModule", { value: true });
AsapAction$1.AsapAction = void 0;
var AsyncAction_1$3 = AsyncAction$1;
var immediateProvider_1 = immediateProvider;
var AsapAction = (function (_super) {
    __extends$E(AsapAction, _super);
    function AsapAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        return _this;
    }
    AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) { delay = 0; }
        if (delay !== null && delay > 0) {
            return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
        }
        scheduler.actions.push(this);
        return scheduler._scheduled || (scheduler._scheduled = immediateProvider_1.immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));
    };
    AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        var _a;
        if (delay === void 0) { delay = 0; }
        if (delay != null ? delay > 0 : this.delay > 0) {
            return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
        }
        var actions = scheduler.actions;
        if (id != null && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id) {
            immediateProvider_1.immediateProvider.clearImmediate(id);
            if (scheduler._scheduled === id) {
                scheduler._scheduled = undefined;
            }
        }
        return undefined;
    };
    return AsapAction;
}(AsyncAction_1$3.AsyncAction));
AsapAction$1.AsapAction = AsapAction;

var AsapScheduler$1 = {};

var AsyncScheduler$1 = {};

var Scheduler$1 = {};

Object.defineProperty(Scheduler$1, "__esModule", { value: true });
Scheduler$1.Scheduler = void 0;
var dateTimestampProvider_1$1 = dateTimestampProvider;
var Scheduler = (function () {
    function Scheduler(schedulerActionCtor, now) {
        if (now === void 0) { now = Scheduler.now; }
        this.schedulerActionCtor = schedulerActionCtor;
        this.now = now;
    }
    Scheduler.prototype.schedule = function (work, delay, state) {
        if (delay === void 0) { delay = 0; }
        return new this.schedulerActionCtor(this, work).schedule(state, delay);
    };
    Scheduler.now = dateTimestampProvider_1$1.dateTimestampProvider.now;
    return Scheduler;
}());
Scheduler$1.Scheduler = Scheduler;

var __extends$D = (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 __());
    };
})();
Object.defineProperty(AsyncScheduler$1, "__esModule", { value: true });
AsyncScheduler$1.AsyncScheduler = void 0;
var Scheduler_1 = Scheduler$1;
var AsyncScheduler = (function (_super) {
    __extends$D(AsyncScheduler, _super);
    function AsyncScheduler(SchedulerAction, now) {
        if (now === void 0) { now = Scheduler_1.Scheduler.now; }
        var _this = _super.call(this, SchedulerAction, now) || this;
        _this.actions = [];
        _this._active = false;
        return _this;
    }
    AsyncScheduler.prototype.flush = function (action) {
        var actions = this.actions;
        if (this._active) {
            actions.push(action);
            return;
        }
        var error;
        this._active = true;
        do {
            if ((error = action.execute(action.state, action.delay))) {
                break;
            }
        } while ((action = actions.shift()));
        this._active = false;
        if (error) {
            while ((action = actions.shift())) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    return AsyncScheduler;
}(Scheduler_1.Scheduler));
AsyncScheduler$1.AsyncScheduler = AsyncScheduler;

var __extends$C = (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 __());
    };
})();
Object.defineProperty(AsapScheduler$1, "__esModule", { value: true });
AsapScheduler$1.AsapScheduler = void 0;
var AsyncScheduler_1$3 = AsyncScheduler$1;
var AsapScheduler = (function (_super) {
    __extends$C(AsapScheduler, _super);
    function AsapScheduler() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AsapScheduler.prototype.flush = function (action) {
        this._active = true;
        var flushId = this._scheduled;
        this._scheduled = undefined;
        var actions = this.actions;
        var error;
        action = action || actions.shift();
        do {
            if ((error = action.execute(action.state, action.delay))) {
                break;
            }
        } while ((action = actions[0]) && action.id === flushId && actions.shift());
        this._active = false;
        if (error) {
            while ((action = actions[0]) && action.id === flushId && actions.shift()) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    return AsapScheduler;
}(AsyncScheduler_1$3.AsyncScheduler));
AsapScheduler$1.AsapScheduler = AsapScheduler;

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.asap = exports.asapScheduler = void 0;
var AsapAction_1 = AsapAction$1;
var AsapScheduler_1 = AsapScheduler$1;
exports.asapScheduler = new AsapScheduler_1.AsapScheduler(AsapAction_1.AsapAction);
exports.asap = exports.asapScheduler;

}(asap));

var async = {};

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.async = exports.asyncScheduler = void 0;
var AsyncAction_1 = AsyncAction$1;
var AsyncScheduler_1 = AsyncScheduler$1;
exports.asyncScheduler = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
exports.async = exports.asyncScheduler;

}(async));

var queue = {};

var QueueAction$1 = {};

var __extends$B = (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 __());
    };
})();
Object.defineProperty(QueueAction$1, "__esModule", { value: true });
QueueAction$1.QueueAction = void 0;
var AsyncAction_1$2 = AsyncAction$1;
var QueueAction = (function (_super) {
    __extends$B(QueueAction, _super);
    function QueueAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        return _this;
    }
    QueueAction.prototype.schedule = function (state, delay) {
        if (delay === void 0) { delay = 0; }
        if (delay > 0) {
            return _super.prototype.schedule.call(this, state, delay);
        }
        this.delay = delay;
        this.state = state;
        this.scheduler.flush(this);
        return this;
    };
    QueueAction.prototype.execute = function (state, delay) {
        return delay > 0 || this.closed ? _super.prototype.execute.call(this, state, delay) : this._execute(state, delay);
    };
    QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) { delay = 0; }
        if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {
            return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
        }
        scheduler.flush(this);
        return 0;
    };
    return QueueAction;
}(AsyncAction_1$2.AsyncAction));
QueueAction$1.QueueAction = QueueAction;

var QueueScheduler$1 = {};

var __extends$A = (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 __());
    };
})();
Object.defineProperty(QueueScheduler$1, "__esModule", { value: true });
QueueScheduler$1.QueueScheduler = void 0;
var AsyncScheduler_1$2 = AsyncScheduler$1;
var QueueScheduler = (function (_super) {
    __extends$A(QueueScheduler, _super);
    function QueueScheduler() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return QueueScheduler;
}(AsyncScheduler_1$2.AsyncScheduler));
QueueScheduler$1.QueueScheduler = QueueScheduler;

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.queue = exports.queueScheduler = void 0;
var QueueAction_1 = QueueAction$1;
var QueueScheduler_1 = QueueScheduler$1;
exports.queueScheduler = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
exports.queue = exports.queueScheduler;

}(queue));

var animationFrame = {};

var AnimationFrameAction$1 = {};

var __extends$z = (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 __());
    };
})();
Object.defineProperty(AnimationFrameAction$1, "__esModule", { value: true });
AnimationFrameAction$1.AnimationFrameAction = void 0;
var AsyncAction_1$1 = AsyncAction$1;
var animationFrameProvider_1 = animationFrameProvider;
var AnimationFrameAction = (function (_super) {
    __extends$z(AnimationFrameAction, _super);
    function AnimationFrameAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        return _this;
    }
    AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) { delay = 0; }
        if (delay !== null && delay > 0) {
            return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
        }
        scheduler.actions.push(this);
        return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider_1.animationFrameProvider.requestAnimationFrame(function () { return scheduler.flush(undefined); }));
    };
    AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        var _a;
        if (delay === void 0) { delay = 0; }
        if (delay != null ? delay > 0 : this.delay > 0) {
            return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
        }
        var actions = scheduler.actions;
        if (id != null && id === scheduler._scheduled && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id) {
            animationFrameProvider_1.animationFrameProvider.cancelAnimationFrame(id);
            scheduler._scheduled = undefined;
        }
        return undefined;
    };
    return AnimationFrameAction;
}(AsyncAction_1$1.AsyncAction));
AnimationFrameAction$1.AnimationFrameAction = AnimationFrameAction;

var AnimationFrameScheduler$1 = {};

var __extends$y = (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 __());
    };
})();
Object.defineProperty(AnimationFrameScheduler$1, "__esModule", { value: true });
AnimationFrameScheduler$1.AnimationFrameScheduler = void 0;
var AsyncScheduler_1$1 = AsyncScheduler$1;
var AnimationFrameScheduler = (function (_super) {
    __extends$y(AnimationFrameScheduler, _super);
    function AnimationFrameScheduler() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AnimationFrameScheduler.prototype.flush = function (action) {
        this._active = true;
        var flushId;
        if (action) {
            flushId = action.id;
        }
        else {
            flushId = this._scheduled;
            this._scheduled = undefined;
        }
        var actions = this.actions;
        var error;
        action = action || actions.shift();
        do {
            if ((error = action.execute(action.state, action.delay))) {
                break;
            }
        } while ((action = actions[0]) && action.id === flushId && actions.shift());
        this._active = false;
        if (error) {
            while ((action = actions[0]) && action.id === flushId && actions.shift()) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    return AnimationFrameScheduler;
}(AsyncScheduler_1$1.AsyncScheduler));
AnimationFrameScheduler$1.AnimationFrameScheduler = AnimationFrameScheduler;

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.animationFrame = exports.animationFrameScheduler = void 0;
var AnimationFrameAction_1 = AnimationFrameAction$1;
var AnimationFrameScheduler_1 = AnimationFrameScheduler$1;
exports.animationFrameScheduler = new AnimationFrameScheduler_1.AnimationFrameScheduler(AnimationFrameAction_1.AnimationFrameAction);
exports.animationFrame = exports.animationFrameScheduler;

}(animationFrame));

var VirtualTimeScheduler$1 = {};

var __extends$x = (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 __());
    };
})();
Object.defineProperty(VirtualTimeScheduler$1, "__esModule", { value: true });
VirtualTimeScheduler$1.VirtualAction = VirtualTimeScheduler$1.VirtualTimeScheduler = void 0;
var AsyncAction_1 = AsyncAction$1;
var Subscription_1$4 = Subscription$1;
var AsyncScheduler_1 = AsyncScheduler$1;
var VirtualTimeScheduler = (function (_super) {
    __extends$x(VirtualTimeScheduler, _super);
    function VirtualTimeScheduler(schedulerActionCtor, maxFrames) {
        if (schedulerActionCtor === void 0) { schedulerActionCtor = VirtualAction; }
        if (maxFrames === void 0) { maxFrames = Infinity; }
        var _this = _super.call(this, schedulerActionCtor, function () { return _this.frame; }) || this;
        _this.maxFrames = maxFrames;
        _this.frame = 0;
        _this.index = -1;
        return _this;
    }
    VirtualTimeScheduler.prototype.flush = function () {
        var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
        var error;
        var action;
        while ((action = actions[0]) && action.delay <= maxFrames) {
            actions.shift();
            this.frame = action.delay;
            if ((error = action.execute(action.state, action.delay))) {
                break;
            }
        }
        if (error) {
            while ((action = actions.shift())) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    VirtualTimeScheduler.frameTimeFactor = 10;
    return VirtualTimeScheduler;
}(AsyncScheduler_1.AsyncScheduler));
VirtualTimeScheduler$1.VirtualTimeScheduler = VirtualTimeScheduler;
var VirtualAction = (function (_super) {
    __extends$x(VirtualAction, _super);
    function VirtualAction(scheduler, work, index) {
        if (index === void 0) { index = (scheduler.index += 1); }
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        _this.index = index;
        _this.active = true;
        _this.index = scheduler.index = index;
        return _this;
    }
    VirtualAction.prototype.schedule = function (state, delay) {
        if (delay === void 0) { delay = 0; }
        if (Number.isFinite(delay)) {
            if (!this.id) {
                return _super.prototype.schedule.call(this, state, delay);
            }
            this.active = false;
            var action = new VirtualAction(this.scheduler, this.work);
            this.add(action);
            return action.schedule(state, delay);
        }
        else {
            return Subscription_1$4.Subscription.EMPTY;
        }
    };
    VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) { delay = 0; }
        this.delay = scheduler.frame + delay;
        var actions = scheduler.actions;
        actions.push(this);
        actions.sort(VirtualAction.sortActions);
        return 1;
    };
    VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        return undefined;
    };
    VirtualAction.prototype._execute = function (state, delay) {
        if (this.active === true) {
            return _super.prototype._execute.call(this, state, delay);
        }
    };
    VirtualAction.sortActions = function (a, b) {
        if (a.delay === b.delay) {
            if (a.index === b.index) {
                return 0;
            }
            else if (a.index > b.index) {
                return 1;
            }
            else {
                return -1;
            }
        }
        else if (a.delay > b.delay) {
            return 1;
        }
        else {
            return -1;
        }
    };
    return VirtualAction;
}(AsyncAction_1.AsyncAction));
VirtualTimeScheduler$1.VirtualAction = VirtualAction;

var Notification = {};

var empty = {};

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.empty = exports.EMPTY = void 0;
var Observable_1 = Observable$1;
exports.EMPTY = new Observable_1.Observable(function (subscriber) { return subscriber.complete(); });
function empty(scheduler) {
    return scheduler ? emptyScheduled(scheduler) : exports.EMPTY;
}
exports.empty = empty;
function emptyScheduled(scheduler) {
    return new Observable_1.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
}

}(empty));

var of$1 = {};

var args = {};

var isScheduler$1 = {};

Object.defineProperty(isScheduler$1, "__esModule", { value: true });
isScheduler$1.isScheduler = void 0;
var isFunction_1$m = isFunction$1;
function isScheduler(value) {
    return value && isFunction_1$m.isFunction(value.schedule);
}
isScheduler$1.isScheduler = isScheduler;

Object.defineProperty(args, "__esModule", { value: true });
args.popNumber = args.popScheduler = args.popResultSelector = void 0;
var isFunction_1$l = isFunction$1;
var isScheduler_1$3 = isScheduler$1;
function last$2(arr) {
    return arr[arr.length - 1];
}
function popResultSelector(args) {
    return isFunction_1$l.isFunction(last$2(args)) ? args.pop() : undefined;
}
args.popResultSelector = popResultSelector;
function popScheduler(args) {
    return isScheduler_1$3.isScheduler(last$2(args)) ? args.pop() : undefined;
}
args.popScheduler = popScheduler;
function popNumber(args, defaultValue) {
    return typeof last$2(args) === 'number' ? args.pop() : defaultValue;
}
args.popNumber = popNumber;

var from$1 = {};

var scheduled$1 = {};

var scheduleObservable$1 = {};

var innerFrom$1 = {};

var isArrayLike = {};

Object.defineProperty(isArrayLike, "__esModule", { value: true });
isArrayLike.isArrayLike = void 0;
isArrayLike.isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });

var isPromise$1 = {};

Object.defineProperty(isPromise$1, "__esModule", { value: true });
isPromise$1.isPromise = void 0;
var isFunction_1$k = isFunction$1;
function isPromise(value) {
    return isFunction_1$k.isFunction(value === null || value === void 0 ? void 0 : value.then);
}
isPromise$1.isPromise = isPromise;

var isInteropObservable$1 = {};

Object.defineProperty(isInteropObservable$1, "__esModule", { value: true });
isInteropObservable$1.isInteropObservable = void 0;
var observable_1$1 = observable;
var isFunction_1$j = isFunction$1;
function isInteropObservable(input) {
    return isFunction_1$j.isFunction(input[observable_1$1.observable]);
}
isInteropObservable$1.isInteropObservable = isInteropObservable;

var isAsyncIterable$1 = {};

Object.defineProperty(isAsyncIterable$1, "__esModule", { value: true });
isAsyncIterable$1.isAsyncIterable = void 0;
var isFunction_1$i = isFunction$1;
function isAsyncIterable(obj) {
    return Symbol.asyncIterator && isFunction_1$i.isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
}
isAsyncIterable$1.isAsyncIterable = isAsyncIterable;

var throwUnobservableError = {};

Object.defineProperty(throwUnobservableError, "__esModule", { value: true });
throwUnobservableError.createInvalidObservableTypeError = void 0;
function createInvalidObservableTypeError(input) {
    return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
}
throwUnobservableError.createInvalidObservableTypeError = createInvalidObservableTypeError;

var isIterable$2 = {};

var iterator = {};

Object.defineProperty(iterator, "__esModule", { value: true });
iterator.iterator = iterator.getSymbolIterator = void 0;
function getSymbolIterator() {
    if (typeof Symbol !== 'function' || !Symbol.iterator) {
        return '@@iterator';
    }
    return Symbol.iterator;
}
iterator.getSymbolIterator = getSymbolIterator;
iterator.iterator = getSymbolIterator();

Object.defineProperty(isIterable$2, "__esModule", { value: true });
isIterable$2.isIterable = void 0;
var iterator_1$1 = iterator;
var isFunction_1$h = isFunction$1;
function isIterable$1(input) {
    return isFunction_1$h.isFunction(input === null || input === void 0 ? void 0 : input[iterator_1$1.iterator]);
}
isIterable$2.isIterable = isIterable$1;

var isReadableStreamLike$1 = {};

var __generator$b = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __await = (commonjsGlobal && commonjsGlobal.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); };
var __asyncGenerator = (commonjsGlobal && commonjsGlobal.__asyncGenerator) || function (thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
Object.defineProperty(isReadableStreamLike$1, "__esModule", { value: true });
isReadableStreamLike$1.isReadableStreamLike = isReadableStreamLike$1.readableStreamLikeToAsyncGenerator = void 0;
var isFunction_1$g = isFunction$1;
function readableStreamLikeToAsyncGenerator(readableStream) {
    return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
        var reader, _a, value, done;
        return __generator$b(this, function (_b) {
            switch (_b.label) {
                case 0:
                    reader = readableStream.getReader();
                    _b.label = 1;
                case 1:
                    _b.trys.push([1, , 9, 10]);
                    _b.label = 2;
                case 2:
                    return [4, __await(reader.read())];
                case 3:
                    _a = _b.sent(), value = _a.value, done = _a.done;
                    if (!done) return [3, 5];
                    return [4, __await(void 0)];
                case 4: return [2, _b.sent()];
                case 5: return [4, __await(value)];
                case 6: return [4, _b.sent()];
                case 7:
                    _b.sent();
                    return [3, 2];
                case 8: return [3, 10];
                case 9:
                    reader.releaseLock();
                    return [7];
                case 10: return [2];
            }
        });
    });
}
isReadableStreamLike$1.readableStreamLikeToAsyncGenerator = readableStreamLikeToAsyncGenerator;
function isReadableStreamLike(obj) {
    return isFunction_1$g.isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
}
isReadableStreamLike$1.isReadableStreamLike = isReadableStreamLike;

var __awaiter$9 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$a = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __asyncValues = (commonjsGlobal && commonjsGlobal.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values$8 === "function" ? __values$8(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __values$8 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(innerFrom$1, "__esModule", { value: true });
innerFrom$1.fromReadableStreamLike = innerFrom$1.fromAsyncIterable = innerFrom$1.fromIterable = innerFrom$1.fromPromise = innerFrom$1.fromArrayLike = innerFrom$1.fromInteropObservable = innerFrom$1.innerFrom = void 0;
var isArrayLike_1$2 = isArrayLike;
var isPromise_1$1 = isPromise$1;
var Observable_1$k = Observable$1;
var isInteropObservable_1$1 = isInteropObservable$1;
var isAsyncIterable_1$1 = isAsyncIterable$1;
var throwUnobservableError_1$1 = throwUnobservableError;
var isIterable_1$1 = isIterable$2;
var isReadableStreamLike_1$2 = isReadableStreamLike$1;
var isFunction_1$f = isFunction$1;
var reportUnhandledError_1 = reportUnhandledError$1;
var observable_1 = observable;
function innerFrom(input) {
    if (input instanceof Observable_1$k.Observable) {
        return input;
    }
    if (input != null) {
        if (isInteropObservable_1$1.isInteropObservable(input)) {
            return fromInteropObservable(input);
        }
        if (isArrayLike_1$2.isArrayLike(input)) {
            return fromArrayLike(input);
        }
        if (isPromise_1$1.isPromise(input)) {
            return fromPromise(input);
        }
        if (isAsyncIterable_1$1.isAsyncIterable(input)) {
            return fromAsyncIterable(input);
        }
        if (isIterable_1$1.isIterable(input)) {
            return fromIterable(input);
        }
        if (isReadableStreamLike_1$2.isReadableStreamLike(input)) {
            return fromReadableStreamLike(input);
        }
    }
    throw throwUnobservableError_1$1.createInvalidObservableTypeError(input);
}
innerFrom$1.innerFrom = innerFrom;
function fromInteropObservable(obj) {
    return new Observable_1$k.Observable(function (subscriber) {
        var obs = obj[observable_1.observable]();
        if (isFunction_1$f.isFunction(obs.subscribe)) {
            return obs.subscribe(subscriber);
        }
        throw new TypeError('Provided object does not correctly implement Symbol.observable');
    });
}
innerFrom$1.fromInteropObservable = fromInteropObservable;
function fromArrayLike(array) {
    return new Observable_1$k.Observable(function (subscriber) {
        for (var i = 0; i < array.length && !subscriber.closed; i++) {
            subscriber.next(array[i]);
        }
        subscriber.complete();
    });
}
innerFrom$1.fromArrayLike = fromArrayLike;
function fromPromise(promise) {
    return new Observable_1$k.Observable(function (subscriber) {
        promise
            .then(function (value) {
            if (!subscriber.closed) {
                subscriber.next(value);
                subscriber.complete();
            }
        }, function (err) { return subscriber.error(err); })
            .then(null, reportUnhandledError_1.reportUnhandledError);
    });
}
innerFrom$1.fromPromise = fromPromise;
function fromIterable(iterable) {
    return new Observable_1$k.Observable(function (subscriber) {
        var e_1, _a;
        try {
            for (var iterable_1 = __values$8(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
                var value = iterable_1_1.value;
                subscriber.next(value);
                if (subscriber.closed) {
                    return;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        subscriber.complete();
    });
}
innerFrom$1.fromIterable = fromIterable;
function fromAsyncIterable(asyncIterable) {
    return new Observable_1$k.Observable(function (subscriber) {
        process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
    });
}
innerFrom$1.fromAsyncIterable = fromAsyncIterable;
function fromReadableStreamLike(readableStream) {
    return fromAsyncIterable(isReadableStreamLike_1$2.readableStreamLikeToAsyncGenerator(readableStream));
}
innerFrom$1.fromReadableStreamLike = fromReadableStreamLike;
function process(asyncIterable, subscriber) {
    var asyncIterable_1, asyncIterable_1_1;
    var e_2, _a;
    return __awaiter$9(this, void 0, void 0, function () {
        var value, e_2_1;
        return __generator$a(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 5, 6, 11]);
                    asyncIterable_1 = __asyncValues(asyncIterable);
                    _b.label = 1;
                case 1: return [4, asyncIterable_1.next()];
                case 2:
                    if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
                    value = asyncIterable_1_1.value;
                    subscriber.next(value);
                    if (subscriber.closed) {
                        return [2];
                    }
                    _b.label = 3;
                case 3: return [3, 1];
                case 4: return [3, 11];
                case 5:
                    e_2_1 = _b.sent();
                    e_2 = { error: e_2_1 };
                    return [3, 11];
                case 6:
                    _b.trys.push([6, , 9, 10]);
                    if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
                    return [4, _a.call(asyncIterable_1)];
                case 7:
                    _b.sent();
                    _b.label = 8;
                case 8: return [3, 10];
                case 9:
                    if (e_2) throw e_2.error;
                    return [7];
                case 10: return [7];
                case 11:
                    subscriber.complete();
                    return [2];
            }
        });
    });
}

var observeOn$1 = {};

var executeSchedule$1 = {};

Object.defineProperty(executeSchedule$1, "__esModule", { value: true });
executeSchedule$1.executeSchedule = void 0;
function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
    if (delay === void 0) { delay = 0; }
    if (repeat === void 0) { repeat = false; }
    var scheduleSubscription = scheduler.schedule(function () {
        work();
        if (repeat) {
            parentSubscription.add(this.schedule(null, delay));
        }
        else {
            this.unsubscribe();
        }
    }, delay);
    parentSubscription.add(scheduleSubscription);
    if (!repeat) {
        return scheduleSubscription;
    }
}
executeSchedule$1.executeSchedule = executeSchedule;

Object.defineProperty(observeOn$1, "__esModule", { value: true });
observeOn$1.observeOn = void 0;
var executeSchedule_1$6 = executeSchedule$1;
var lift_1$12 = lift;
var OperatorSubscriber_1$T = OperatorSubscriber$1;
function observeOn(scheduler, delay) {
    if (delay === void 0) { delay = 0; }
    return lift_1$12.operate(function (source, subscriber) {
        source.subscribe(OperatorSubscriber_1$T.createOperatorSubscriber(subscriber, function (value) { return executeSchedule_1$6.executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule_1$6.executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule_1$6.executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
    });
}
observeOn$1.observeOn = observeOn;

var subscribeOn$1 = {};

Object.defineProperty(subscribeOn$1, "__esModule", { value: true });
subscribeOn$1.subscribeOn = void 0;
var lift_1$11 = lift;
function subscribeOn(scheduler, delay) {
    if (delay === void 0) { delay = 0; }
    return lift_1$11.operate(function (source, subscriber) {
        subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
    });
}
subscribeOn$1.subscribeOn = subscribeOn;

Object.defineProperty(scheduleObservable$1, "__esModule", { value: true });
scheduleObservable$1.scheduleObservable = void 0;
var innerFrom_1$D = innerFrom$1;
var observeOn_1$2 = observeOn$1;
var subscribeOn_1$2 = subscribeOn$1;
function scheduleObservable(input, scheduler) {
    return innerFrom_1$D.innerFrom(input).pipe(subscribeOn_1$2.subscribeOn(scheduler), observeOn_1$2.observeOn(scheduler));
}
scheduleObservable$1.scheduleObservable = scheduleObservable;

var schedulePromise$1 = {};

Object.defineProperty(schedulePromise$1, "__esModule", { value: true });
schedulePromise$1.schedulePromise = void 0;
var innerFrom_1$C = innerFrom$1;
var observeOn_1$1 = observeOn$1;
var subscribeOn_1$1 = subscribeOn$1;
function schedulePromise(input, scheduler) {
    return innerFrom_1$C.innerFrom(input).pipe(subscribeOn_1$1.subscribeOn(scheduler), observeOn_1$1.observeOn(scheduler));
}
schedulePromise$1.schedulePromise = schedulePromise;

var scheduleArray$1 = {};

Object.defineProperty(scheduleArray$1, "__esModule", { value: true });
scheduleArray$1.scheduleArray = void 0;
var Observable_1$j = Observable$1;
function scheduleArray(input, scheduler) {
    return new Observable_1$j.Observable(function (subscriber) {
        var i = 0;
        return scheduler.schedule(function () {
            if (i === input.length) {
                subscriber.complete();
            }
            else {
                subscriber.next(input[i++]);
                if (!subscriber.closed) {
                    this.schedule();
                }
            }
        });
    });
}
scheduleArray$1.scheduleArray = scheduleArray;

var scheduleIterable$1 = {};

Object.defineProperty(scheduleIterable$1, "__esModule", { value: true });
scheduleIterable$1.scheduleIterable = void 0;
var Observable_1$i = Observable$1;
var iterator_1 = iterator;
var isFunction_1$e = isFunction$1;
var executeSchedule_1$5 = executeSchedule$1;
function scheduleIterable(input, scheduler) {
    return new Observable_1$i.Observable(function (subscriber) {
        var iterator;
        executeSchedule_1$5.executeSchedule(subscriber, scheduler, function () {
            iterator = input[iterator_1.iterator]();
            executeSchedule_1$5.executeSchedule(subscriber, scheduler, function () {
                var _a;
                var value;
                var done;
                try {
                    (_a = iterator.next(), value = _a.value, done = _a.done);
                }
                catch (err) {
                    subscriber.error(err);
                    return;
                }
                if (done) {
                    subscriber.complete();
                }
                else {
                    subscriber.next(value);
                }
            }, 0, true);
        });
        return function () { return isFunction_1$e.isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return(); };
    });
}
scheduleIterable$1.scheduleIterable = scheduleIterable;

var scheduleAsyncIterable$1 = {};

Object.defineProperty(scheduleAsyncIterable$1, "__esModule", { value: true });
scheduleAsyncIterable$1.scheduleAsyncIterable = void 0;
var Observable_1$h = Observable$1;
var executeSchedule_1$4 = executeSchedule$1;
function scheduleAsyncIterable(input, scheduler) {
    if (!input) {
        throw new Error('Iterable cannot be null');
    }
    return new Observable_1$h.Observable(function (subscriber) {
        executeSchedule_1$4.executeSchedule(subscriber, scheduler, function () {
            var iterator = input[Symbol.asyncIterator]();
            executeSchedule_1$4.executeSchedule(subscriber, scheduler, function () {
                iterator.next().then(function (result) {
                    if (result.done) {
                        subscriber.complete();
                    }
                    else {
                        subscriber.next(result.value);
                    }
                });
            }, 0, true);
        });
    });
}
scheduleAsyncIterable$1.scheduleAsyncIterable = scheduleAsyncIterable;

var scheduleReadableStreamLike$1 = {};

Object.defineProperty(scheduleReadableStreamLike$1, "__esModule", { value: true });
scheduleReadableStreamLike$1.scheduleReadableStreamLike = void 0;
var scheduleAsyncIterable_1$1 = scheduleAsyncIterable$1;
var isReadableStreamLike_1$1 = isReadableStreamLike$1;
function scheduleReadableStreamLike(input, scheduler) {
    return scheduleAsyncIterable_1$1.scheduleAsyncIterable(isReadableStreamLike_1$1.readableStreamLikeToAsyncGenerator(input), scheduler);
}
scheduleReadableStreamLike$1.scheduleReadableStreamLike = scheduleReadableStreamLike;

Object.defineProperty(scheduled$1, "__esModule", { value: true });
scheduled$1.scheduled = void 0;
var scheduleObservable_1 = scheduleObservable$1;
var schedulePromise_1 = schedulePromise$1;
var scheduleArray_1 = scheduleArray$1;
var scheduleIterable_1$1 = scheduleIterable$1;
var scheduleAsyncIterable_1 = scheduleAsyncIterable$1;
var isInteropObservable_1 = isInteropObservable$1;
var isPromise_1 = isPromise$1;
var isArrayLike_1$1 = isArrayLike;
var isIterable_1 = isIterable$2;
var isAsyncIterable_1 = isAsyncIterable$1;
var throwUnobservableError_1 = throwUnobservableError;
var isReadableStreamLike_1 = isReadableStreamLike$1;
var scheduleReadableStreamLike_1 = scheduleReadableStreamLike$1;
function scheduled(input, scheduler) {
    if (input != null) {
        if (isInteropObservable_1.isInteropObservable(input)) {
            return scheduleObservable_1.scheduleObservable(input, scheduler);
        }
        if (isArrayLike_1$1.isArrayLike(input)) {
            return scheduleArray_1.scheduleArray(input, scheduler);
        }
        if (isPromise_1.isPromise(input)) {
            return schedulePromise_1.schedulePromise(input, scheduler);
        }
        if (isAsyncIterable_1.isAsyncIterable(input)) {
            return scheduleAsyncIterable_1.scheduleAsyncIterable(input, scheduler);
        }
        if (isIterable_1.isIterable(input)) {
            return scheduleIterable_1$1.scheduleIterable(input, scheduler);
        }
        if (isReadableStreamLike_1.isReadableStreamLike(input)) {
            return scheduleReadableStreamLike_1.scheduleReadableStreamLike(input, scheduler);
        }
    }
    throw throwUnobservableError_1.createInvalidObservableTypeError(input);
}
scheduled$1.scheduled = scheduled;

Object.defineProperty(from$1, "__esModule", { value: true });
from$1.from = void 0;
var scheduled_1 = scheduled$1;
var innerFrom_1$B = innerFrom$1;
function from(input, scheduler) {
    return scheduler ? scheduled_1.scheduled(input, scheduler) : innerFrom_1$B.innerFrom(input);
}
from$1.from = from;

Object.defineProperty(of$1, "__esModule", { value: true });
of$1.of = void 0;
var args_1$c = args;
var from_1$6 = from$1;
function of() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var scheduler = args_1$c.popScheduler(args);
    return from_1$6.from(args, scheduler);
}
of$1.of = of;

var throwError$1 = {};

Object.defineProperty(throwError$1, "__esModule", { value: true });
throwError$1.throwError = void 0;
var Observable_1$g = Observable$1;
var isFunction_1$d = isFunction$1;
function throwError(errorOrErrorFactory, scheduler) {
    var errorFactory = isFunction_1$d.isFunction(errorOrErrorFactory) ? errorOrErrorFactory : function () { return errorOrErrorFactory; };
    var init = function (subscriber) { return subscriber.error(errorFactory()); };
    return new Observable_1$g.Observable(scheduler ? function (subscriber) { return scheduler.schedule(init, 0, subscriber); } : init);
}
throwError$1.throwError = throwError;

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.observeNotification = exports.Notification = exports.NotificationKind = void 0;
var empty_1 = empty;
var of_1 = of$1;
var throwError_1 = throwError$1;
var isFunction_1 = isFunction$1;
(function (NotificationKind) {
    NotificationKind["NEXT"] = "N";
    NotificationKind["ERROR"] = "E";
    NotificationKind["COMPLETE"] = "C";
})(exports.NotificationKind || (exports.NotificationKind = {}));
var Notification = (function () {
    function Notification(kind, value, error) {
        this.kind = kind;
        this.value = value;
        this.error = error;
        this.hasValue = kind === 'N';
    }
    Notification.prototype.observe = function (observer) {
        return observeNotification(this, observer);
    };
    Notification.prototype.do = function (nextHandler, errorHandler, completeHandler) {
        var _a = this, kind = _a.kind, value = _a.value, error = _a.error;
        return kind === 'N' ? nextHandler === null || nextHandler === void 0 ? void 0 : nextHandler(value) : kind === 'E' ? errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(error) : completeHandler === null || completeHandler === void 0 ? void 0 : completeHandler();
    };
    Notification.prototype.accept = function (nextOrObserver, error, complete) {
        var _a;
        return isFunction_1.isFunction((_a = nextOrObserver) === null || _a === void 0 ? void 0 : _a.next)
            ? this.observe(nextOrObserver)
            : this.do(nextOrObserver, error, complete);
    };
    Notification.prototype.toObservable = function () {
        var _a = this, kind = _a.kind, value = _a.value, error = _a.error;
        var result = kind === 'N'
            ?
                of_1.of(value)
            :
                kind === 'E'
                    ?
                        throwError_1.throwError(function () { return error; })
                    :
                        kind === 'C'
                            ?
                                empty_1.EMPTY
                            :
                                0;
        if (!result) {
            throw new TypeError("Unexpected notification kind " + kind);
        }
        return result;
    };
    Notification.createNext = function (value) {
        return new Notification('N', value);
    };
    Notification.createError = function (err) {
        return new Notification('E', undefined, err);
    };
    Notification.createComplete = function () {
        return Notification.completeNotification;
    };
    Notification.completeNotification = new Notification('C');
    return Notification;
}());
exports.Notification = Notification;
function observeNotification(notification, observer) {
    var _a, _b, _c;
    var _d = notification, kind = _d.kind, value = _d.value, error = _d.error;
    if (typeof kind !== 'string') {
        throw new TypeError('Invalid notification, missing "kind"');
    }
    kind === 'N' ? (_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, value) : kind === 'E' ? (_b = observer.error) === null || _b === void 0 ? void 0 : _b.call(observer, error) : (_c = observer.complete) === null || _c === void 0 ? void 0 : _c.call(observer);
}
exports.observeNotification = observeNotification;

}(Notification));

var isObservable$1 = {};

Object.defineProperty(isObservable$1, "__esModule", { value: true });
isObservable$1.isObservable = void 0;
var Observable_1$f = Observable$1;
var isFunction_1$c = isFunction$1;
function isObservable(obj) {
    return !!obj && (obj instanceof Observable_1$f.Observable || (isFunction_1$c.isFunction(obj.lift) && isFunction_1$c.isFunction(obj.subscribe)));
}
isObservable$1.isObservable = isObservable;

var lastValueFrom$1 = {};

var EmptyError = {};

Object.defineProperty(EmptyError, "__esModule", { value: true });
EmptyError.EmptyError = void 0;
var createErrorClass_1$3 = createErrorClass$1;
EmptyError.EmptyError = createErrorClass_1$3.createErrorClass(function (_super) {
    return function EmptyErrorImpl() {
        _super(this);
        this.name = 'EmptyError';
        this.message = 'no elements in sequence';
    };
});

Object.defineProperty(lastValueFrom$1, "__esModule", { value: true });
lastValueFrom$1.lastValueFrom = void 0;
var EmptyError_1$5 = EmptyError;
function lastValueFrom(source, config) {
    var hasConfig = typeof config === 'object';
    return new Promise(function (resolve, reject) {
        var _hasValue = false;
        var _value;
        source.subscribe({
            next: function (value) {
                _value = value;
                _hasValue = true;
            },
            error: reject,
            complete: function () {
                if (_hasValue) {
                    resolve(_value);
                }
                else if (hasConfig) {
                    resolve(config.defaultValue);
                }
                else {
                    reject(new EmptyError_1$5.EmptyError());
                }
            },
        });
    });
}
lastValueFrom$1.lastValueFrom = lastValueFrom;

var firstValueFrom$1 = {};

Object.defineProperty(firstValueFrom$1, "__esModule", { value: true });
firstValueFrom$1.firstValueFrom = void 0;
var EmptyError_1$4 = EmptyError;
var Subscriber_1$1 = Subscriber;
function firstValueFrom(source, config) {
    var hasConfig = typeof config === 'object';
    return new Promise(function (resolve, reject) {
        var subscriber = new Subscriber_1$1.SafeSubscriber({
            next: function (value) {
                resolve(value);
                subscriber.unsubscribe();
            },
            error: reject,
            complete: function () {
                if (hasConfig) {
                    resolve(config.defaultValue);
                }
                else {
                    reject(new EmptyError_1$4.EmptyError());
                }
            },
        });
        source.subscribe(subscriber);
    });
}
firstValueFrom$1.firstValueFrom = firstValueFrom;

var ArgumentOutOfRangeError = {};

Object.defineProperty(ArgumentOutOfRangeError, "__esModule", { value: true });
ArgumentOutOfRangeError.ArgumentOutOfRangeError = void 0;
var createErrorClass_1$2 = createErrorClass$1;
ArgumentOutOfRangeError.ArgumentOutOfRangeError = createErrorClass_1$2.createErrorClass(function (_super) {
    return function ArgumentOutOfRangeErrorImpl() {
        _super(this);
        this.name = 'ArgumentOutOfRangeError';
        this.message = 'argument out of range';
    };
});

var NotFoundError = {};

Object.defineProperty(NotFoundError, "__esModule", { value: true });
NotFoundError.NotFoundError = void 0;
var createErrorClass_1$1 = createErrorClass$1;
NotFoundError.NotFoundError = createErrorClass_1$1.createErrorClass(function (_super) {
    return function NotFoundErrorImpl(message) {
        _super(this);
        this.name = 'NotFoundError';
        this.message = message;
    };
});

var SequenceError = {};

Object.defineProperty(SequenceError, "__esModule", { value: true });
SequenceError.SequenceError = void 0;
var createErrorClass_1 = createErrorClass$1;
SequenceError.SequenceError = createErrorClass_1.createErrorClass(function (_super) {
    return function SequenceErrorImpl(message) {
        _super(this);
        this.name = 'SequenceError';
        this.message = message;
    };
});

var timeout = {};

var isDate = {};

Object.defineProperty(isDate, "__esModule", { value: true });
isDate.isValidDate = void 0;
function isValidDate(value) {
    return value instanceof Date && !isNaN(value);
}
isDate.isValidDate = isValidDate;

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeout = exports.TimeoutError = void 0;
var async_1 = async;
var isDate_1 = isDate;
var lift_1 = lift;
var innerFrom_1 = innerFrom$1;
var createErrorClass_1 = createErrorClass$1;
var OperatorSubscriber_1 = OperatorSubscriber$1;
var executeSchedule_1 = executeSchedule$1;
exports.TimeoutError = createErrorClass_1.createErrorClass(function (_super) {
    return function TimeoutErrorImpl(info) {
        if (info === void 0) { info = null; }
        _super(this);
        this.message = 'Timeout has occurred';
        this.name = 'TimeoutError';
        this.info = info;
    };
});
function timeout(config, schedulerArg) {
    var _a = (isDate_1.isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config), first = _a.first, each = _a.each, _b = _a.with, _with = _b === void 0 ? timeoutErrorFactory : _b, _c = _a.scheduler, scheduler = _c === void 0 ? schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : async_1.asyncScheduler : _c, _d = _a.meta, meta = _d === void 0 ? null : _d;
    if (first == null && each == null) {
        throw new TypeError('No timeout provided.');
    }
    return lift_1.operate(function (source, subscriber) {
        var originalSourceSubscription;
        var timerSubscription;
        var lastValue = null;
        var seen = 0;
        var startTimer = function (delay) {
            timerSubscription = executeSchedule_1.executeSchedule(subscriber, scheduler, function () {
                try {
                    originalSourceSubscription.unsubscribe();
                    innerFrom_1.innerFrom(_with({
                        meta: meta,
                        lastValue: lastValue,
                        seen: seen,
                    })).subscribe(subscriber);
                }
                catch (err) {
                    subscriber.error(err);
                }
            }, delay);
        };
        originalSourceSubscription = source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
            timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
            seen++;
            subscriber.next((lastValue = value));
            each > 0 && startTimer(each);
        }, undefined, undefined, function () {
            if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {
                timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
            }
            lastValue = null;
        }));
        !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler.now()) : each);
    });
}
exports.timeout = timeout;
function timeoutErrorFactory(info) {
    throw new exports.TimeoutError(info);
}

}(timeout));

var bindCallback$1 = {};

var bindCallbackInternals$1 = {};

var mapOneOrManyArgs$1 = {};

var map$1 = {};

Object.defineProperty(map$1, "__esModule", { value: true });
map$1.map = void 0;
var lift_1$10 = lift;
var OperatorSubscriber_1$S = OperatorSubscriber$1;
function map(project, thisArg) {
    return lift_1$10.operate(function (source, subscriber) {
        var index = 0;
        source.subscribe(OperatorSubscriber_1$S.createOperatorSubscriber(subscriber, function (value) {
            subscriber.next(project.call(thisArg, value, index++));
        }));
    });
}
map$1.map = map;

var __read$o = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$i = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(mapOneOrManyArgs$1, "__esModule", { value: true });
mapOneOrManyArgs$1.mapOneOrManyArgs = void 0;
var map_1$5 = map$1;
var isArray$2 = Array.isArray;
function callOrApply(fn, args) {
    return isArray$2(args) ? fn.apply(void 0, __spreadArray$i([], __read$o(args))) : fn(args);
}
function mapOneOrManyArgs(fn) {
    return map_1$5.map(function (args) { return callOrApply(fn, args); });
}
mapOneOrManyArgs$1.mapOneOrManyArgs = mapOneOrManyArgs;

var __read$n = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$h = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(bindCallbackInternals$1, "__esModule", { value: true });
bindCallbackInternals$1.bindCallbackInternals = void 0;
var isScheduler_1$2 = isScheduler$1;
var Observable_1$e = Observable$1;
var subscribeOn_1 = subscribeOn$1;
var mapOneOrManyArgs_1$6 = mapOneOrManyArgs$1;
var observeOn_1 = observeOn$1;
var AsyncSubject_1$1 = AsyncSubject$1;
function bindCallbackInternals(isNodeStyle, callbackFunc, resultSelector, scheduler) {
    if (resultSelector) {
        if (isScheduler_1$2.isScheduler(resultSelector)) {
            scheduler = resultSelector;
        }
        else {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return bindCallbackInternals(isNodeStyle, callbackFunc, scheduler)
                    .apply(this, args)
                    .pipe(mapOneOrManyArgs_1$6.mapOneOrManyArgs(resultSelector));
            };
        }
    }
    if (scheduler) {
        return function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return bindCallbackInternals(isNodeStyle, callbackFunc)
                .apply(this, args)
                .pipe(subscribeOn_1.subscribeOn(scheduler), observeOn_1.observeOn(scheduler));
        };
    }
    return function () {
        var _this = this;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var subject = new AsyncSubject_1$1.AsyncSubject();
        var uninitialized = true;
        return new Observable_1$e.Observable(function (subscriber) {
            var subs = subject.subscribe(subscriber);
            if (uninitialized) {
                uninitialized = false;
                var isAsync_1 = false;
                var isComplete_1 = false;
                callbackFunc.apply(_this, __spreadArray$h(__spreadArray$h([], __read$n(args)), [
                    function () {
                        var results = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            results[_i] = arguments[_i];
                        }
                        if (isNodeStyle) {
                            var err = results.shift();
                            if (err != null) {
                                subject.error(err);
                                return;
                            }
                        }
                        subject.next(1 < results.length ? results : results[0]);
                        isComplete_1 = true;
                        if (isAsync_1) {
                            subject.complete();
                        }
                    },
                ]));
                if (isComplete_1) {
                    subject.complete();
                }
                isAsync_1 = true;
            }
            return subs;
        });
    };
}
bindCallbackInternals$1.bindCallbackInternals = bindCallbackInternals;

Object.defineProperty(bindCallback$1, "__esModule", { value: true });
bindCallback$1.bindCallback = void 0;
var bindCallbackInternals_1$1 = bindCallbackInternals$1;
function bindCallback(callbackFunc, resultSelector, scheduler) {
    return bindCallbackInternals_1$1.bindCallbackInternals(false, callbackFunc, resultSelector, scheduler);
}
bindCallback$1.bindCallback = bindCallback;

var bindNodeCallback$1 = {};

Object.defineProperty(bindNodeCallback$1, "__esModule", { value: true });
bindNodeCallback$1.bindNodeCallback = void 0;
var bindCallbackInternals_1 = bindCallbackInternals$1;
function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
    return bindCallbackInternals_1.bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);
}
bindNodeCallback$1.bindNodeCallback = bindNodeCallback;

var combineLatest$3 = {};

var argsArgArrayOrObject$1 = {};

Object.defineProperty(argsArgArrayOrObject$1, "__esModule", { value: true });
argsArgArrayOrObject$1.argsArgArrayOrObject = void 0;
var isArray$1 = Array.isArray;
var getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys;
function argsArgArrayOrObject(args) {
    if (args.length === 1) {
        var first_1 = args[0];
        if (isArray$1(first_1)) {
            return { args: first_1, keys: null };
        }
        if (isPOJO(first_1)) {
            var keys = getKeys(first_1);
            return {
                args: keys.map(function (key) { return first_1[key]; }),
                keys: keys,
            };
        }
    }
    return { args: args, keys: null };
}
argsArgArrayOrObject$1.argsArgArrayOrObject = argsArgArrayOrObject;
function isPOJO(obj) {
    return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;
}

var createObject$1 = {};

Object.defineProperty(createObject$1, "__esModule", { value: true });
createObject$1.createObject = void 0;
function createObject(keys, values) {
    return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {});
}
createObject$1.createObject = createObject;

Object.defineProperty(combineLatest$3, "__esModule", { value: true });
combineLatest$3.combineLatestInit = combineLatest$3.combineLatest = void 0;
var Observable_1$d = Observable$1;
var argsArgArrayOrObject_1$1 = argsArgArrayOrObject$1;
var from_1$5 = from$1;
var identity_1$d = identity$2;
var mapOneOrManyArgs_1$5 = mapOneOrManyArgs$1;
var args_1$b = args;
var createObject_1$1 = createObject$1;
var OperatorSubscriber_1$R = OperatorSubscriber$1;
var executeSchedule_1$3 = executeSchedule$1;
function combineLatest$2() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var scheduler = args_1$b.popScheduler(args);
    var resultSelector = args_1$b.popResultSelector(args);
    var _a = argsArgArrayOrObject_1$1.argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;
    if (observables.length === 0) {
        return from_1$5.from([], scheduler);
    }
    var result = new Observable_1$d.Observable(combineLatestInit(observables, scheduler, keys
        ?
            function (values) { return createObject_1$1.createObject(keys, values); }
        :
            identity_1$d.identity));
    return resultSelector ? result.pipe(mapOneOrManyArgs_1$5.mapOneOrManyArgs(resultSelector)) : result;
}
combineLatest$3.combineLatest = combineLatest$2;
function combineLatestInit(observables, scheduler, valueTransform) {
    if (valueTransform === void 0) { valueTransform = identity_1$d.identity; }
    return function (subscriber) {
        maybeSchedule(scheduler, function () {
            var length = observables.length;
            var values = new Array(length);
            var active = length;
            var remainingFirstValues = length;
            var _loop_1 = function (i) {
                maybeSchedule(scheduler, function () {
                    var source = from_1$5.from(observables[i], scheduler);
                    var hasFirstValue = false;
                    source.subscribe(OperatorSubscriber_1$R.createOperatorSubscriber(subscriber, function (value) {
                        values[i] = value;
                        if (!hasFirstValue) {
                            hasFirstValue = true;
                            remainingFirstValues--;
                        }
                        if (!remainingFirstValues) {
                            subscriber.next(valueTransform(values.slice()));
                        }
                    }, function () {
                        if (!--active) {
                            subscriber.complete();
                        }
                    }));
                }, subscriber);
            };
            for (var i = 0; i < length; i++) {
                _loop_1(i);
            }
        }, subscriber);
    };
}
combineLatest$3.combineLatestInit = combineLatestInit;
function maybeSchedule(scheduler, execute, subscription) {
    if (scheduler) {
        executeSchedule_1$3.executeSchedule(subscription, scheduler, execute);
    }
    else {
        execute();
    }
}

var concat$3 = {};

var concatAll$1 = {};

var mergeAll$1 = {};

var mergeMap$1 = {};

var mergeInternals$1 = {};

Object.defineProperty(mergeInternals$1, "__esModule", { value: true });
mergeInternals$1.mergeInternals = void 0;
var innerFrom_1$A = innerFrom$1;
var executeSchedule_1$2 = executeSchedule$1;
var OperatorSubscriber_1$Q = OperatorSubscriber$1;
function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
    var buffer = [];
    var active = 0;
    var index = 0;
    var isComplete = false;
    var checkComplete = function () {
        if (isComplete && !buffer.length && !active) {
            subscriber.complete();
        }
    };
    var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
    var doInnerSub = function (value) {
        expand && subscriber.next(value);
        active++;
        var innerComplete = false;
        innerFrom_1$A.innerFrom(project(value, index++)).subscribe(OperatorSubscriber_1$Q.createOperatorSubscriber(subscriber, function (innerValue) {
            onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
            if (expand) {
                outerNext(innerValue);
            }
            else {
                subscriber.next(innerValue);
            }
        }, function () {
            innerComplete = true;
        }, undefined, function () {
            if (innerComplete) {
                try {
                    active--;
                    var _loop_1 = function () {
                        var bufferedValue = buffer.shift();
                        if (innerSubScheduler) {
                            executeSchedule_1$2.executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
                        }
                        else {
                            doInnerSub(bufferedValue);
                        }
                    };
                    while (buffer.length && active < concurrent) {
                        _loop_1();
                    }
                    checkComplete();
                }
                catch (err) {
                    subscriber.error(err);
                }
            }
        }));
    };
    source.subscribe(OperatorSubscriber_1$Q.createOperatorSubscriber(subscriber, outerNext, function () {
        isComplete = true;
        checkComplete();
    }));
    return function () {
        additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
    };
}
mergeInternals$1.mergeInternals = mergeInternals;

Object.defineProperty(mergeMap$1, "__esModule", { value: true });
mergeMap$1.mergeMap = void 0;
var map_1$4 = map$1;
var innerFrom_1$z = innerFrom$1;
var lift_1$$ = lift;
var mergeInternals_1$2 = mergeInternals$1;
var isFunction_1$b = isFunction$1;
function mergeMap(project, resultSelector, concurrent) {
    if (concurrent === void 0) { concurrent = Infinity; }
    if (isFunction_1$b.isFunction(resultSelector)) {
        return mergeMap(function (a, i) { return map_1$4.map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom_1$z.innerFrom(project(a, i))); }, concurrent);
    }
    else if (typeof resultSelector === 'number') {
        concurrent = resultSelector;
    }
    return lift_1$$.operate(function (source, subscriber) { return mergeInternals_1$2.mergeInternals(source, subscriber, project, concurrent); });
}
mergeMap$1.mergeMap = mergeMap;

Object.defineProperty(mergeAll$1, "__esModule", { value: true });
mergeAll$1.mergeAll = void 0;
var mergeMap_1$6 = mergeMap$1;
var identity_1$c = identity$2;
function mergeAll(concurrent) {
    if (concurrent === void 0) { concurrent = Infinity; }
    return mergeMap_1$6.mergeMap(identity_1$c.identity, concurrent);
}
mergeAll$1.mergeAll = mergeAll;

Object.defineProperty(concatAll$1, "__esModule", { value: true });
concatAll$1.concatAll = void 0;
var mergeAll_1$2 = mergeAll$1;
function concatAll() {
    return mergeAll_1$2.mergeAll(1);
}
concatAll$1.concatAll = concatAll;

Object.defineProperty(concat$3, "__esModule", { value: true });
concat$3.concat = void 0;
var concatAll_1$1 = concatAll$1;
var args_1$a = args;
var from_1$4 = from$1;
function concat$2() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    return concatAll_1$1.concatAll()(from_1$4.from(args, args_1$a.popScheduler(args)));
}
concat$3.concat = concat$2;

var connectable$1 = {};

var defer$1 = {};

Object.defineProperty(defer$1, "__esModule", { value: true });
defer$1.defer = void 0;
var Observable_1$c = Observable$1;
var innerFrom_1$y = innerFrom$1;
function defer(observableFactory) {
    return new Observable_1$c.Observable(function (subscriber) {
        innerFrom_1$y.innerFrom(observableFactory()).subscribe(subscriber);
    });
}
defer$1.defer = defer;

Object.defineProperty(connectable$1, "__esModule", { value: true });
connectable$1.connectable = void 0;
var Subject_1$b = Subject$1;
var Observable_1$b = Observable$1;
var defer_1$2 = defer$1;
var DEFAULT_CONFIG$1 = {
    connector: function () { return new Subject_1$b.Subject(); },
    resetOnDisconnect: true,
};
function connectable(source, config) {
    if (config === void 0) { config = DEFAULT_CONFIG$1; }
    var connection = null;
    var connector = config.connector, _a = config.resetOnDisconnect, resetOnDisconnect = _a === void 0 ? true : _a;
    var subject = connector();
    var result = new Observable_1$b.Observable(function (subscriber) {
        return subject.subscribe(subscriber);
    });
    result.connect = function () {
        if (!connection || connection.closed) {
            connection = defer_1$2.defer(function () { return source; }).subscribe(subject);
            if (resetOnDisconnect) {
                connection.add(function () { return (subject = connector()); });
            }
        }
        return connection;
    };
    return result;
}
connectable$1.connectable = connectable;

var forkJoin$1 = {};

Object.defineProperty(forkJoin$1, "__esModule", { value: true });
forkJoin$1.forkJoin = void 0;
var Observable_1$a = Observable$1;
var argsArgArrayOrObject_1 = argsArgArrayOrObject$1;
var innerFrom_1$x = innerFrom$1;
var args_1$9 = args;
var OperatorSubscriber_1$P = OperatorSubscriber$1;
var mapOneOrManyArgs_1$4 = mapOneOrManyArgs$1;
var createObject_1 = createObject$1;
function forkJoin() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var resultSelector = args_1$9.popResultSelector(args);
    var _a = argsArgArrayOrObject_1.argsArgArrayOrObject(args), sources = _a.args, keys = _a.keys;
    var result = new Observable_1$a.Observable(function (subscriber) {
        var length = sources.length;
        if (!length) {
            subscriber.complete();
            return;
        }
        var values = new Array(length);
        var remainingCompletions = length;
        var remainingEmissions = length;
        var _loop_1 = function (sourceIndex) {
            var hasValue = false;
            innerFrom_1$x.innerFrom(sources[sourceIndex]).subscribe(OperatorSubscriber_1$P.createOperatorSubscriber(subscriber, function (value) {
                if (!hasValue) {
                    hasValue = true;
                    remainingEmissions--;
                }
                values[sourceIndex] = value;
            }, function () { return remainingCompletions--; }, undefined, function () {
                if (!remainingCompletions || !hasValue) {
                    if (!remainingEmissions) {
                        subscriber.next(keys ? createObject_1.createObject(keys, values) : values);
                    }
                    subscriber.complete();
                }
            }));
        };
        for (var sourceIndex = 0; sourceIndex < length; sourceIndex++) {
            _loop_1(sourceIndex);
        }
    });
    return resultSelector ? result.pipe(mapOneOrManyArgs_1$4.mapOneOrManyArgs(resultSelector)) : result;
}
forkJoin$1.forkJoin = forkJoin;

var fromEvent$1 = {};

var __read$m = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(fromEvent$1, "__esModule", { value: true });
fromEvent$1.fromEvent = void 0;
var innerFrom_1$w = innerFrom$1;
var Observable_1$9 = Observable$1;
var mergeMap_1$5 = mergeMap$1;
var isArrayLike_1 = isArrayLike;
var isFunction_1$a = isFunction$1;
var mapOneOrManyArgs_1$3 = mapOneOrManyArgs$1;
var nodeEventEmitterMethods = ['addListener', 'removeListener'];
var eventTargetMethods = ['addEventListener', 'removeEventListener'];
var jqueryMethods = ['on', 'off'];
function fromEvent(target, eventName, options, resultSelector) {
    if (isFunction_1$a.isFunction(options)) {
        resultSelector = options;
        options = undefined;
    }
    if (resultSelector) {
        return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs_1$3.mapOneOrManyArgs(resultSelector));
    }
    var _a = __read$m(isEventTarget(target)
        ? eventTargetMethods.map(function (methodName) { return function (handler) { return target[methodName](eventName, handler, options); }; })
        :
            isNodeStyleEventEmitter(target)
                ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))
                : isJQueryStyleEventEmitter(target)
                    ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))
                    : [], 2), add = _a[0], remove = _a[1];
    if (!add) {
        if (isArrayLike_1.isArrayLike(target)) {
            return mergeMap_1$5.mergeMap(function (subTarget) { return fromEvent(subTarget, eventName, options); })(innerFrom_1$w.innerFrom(target));
        }
    }
    if (!add) {
        throw new TypeError('Invalid event target');
    }
    return new Observable_1$9.Observable(function (subscriber) {
        var handler = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return subscriber.next(1 < args.length ? args : args[0]);
        };
        add(handler);
        return function () { return remove(handler); };
    });
}
fromEvent$1.fromEvent = fromEvent;
function toCommonHandlerRegistry(target, eventName) {
    return function (methodName) { return function (handler) { return target[methodName](eventName, handler); }; };
}
function isNodeStyleEventEmitter(target) {
    return isFunction_1$a.isFunction(target.addListener) && isFunction_1$a.isFunction(target.removeListener);
}
function isJQueryStyleEventEmitter(target) {
    return isFunction_1$a.isFunction(target.on) && isFunction_1$a.isFunction(target.off);
}
function isEventTarget(target) {
    return isFunction_1$a.isFunction(target.addEventListener) && isFunction_1$a.isFunction(target.removeEventListener);
}

var fromEventPattern$1 = {};

Object.defineProperty(fromEventPattern$1, "__esModule", { value: true });
fromEventPattern$1.fromEventPattern = void 0;
var Observable_1$8 = Observable$1;
var isFunction_1$9 = isFunction$1;
var mapOneOrManyArgs_1$2 = mapOneOrManyArgs$1;
function fromEventPattern(addHandler, removeHandler, resultSelector) {
    if (resultSelector) {
        return fromEventPattern(addHandler, removeHandler).pipe(mapOneOrManyArgs_1$2.mapOneOrManyArgs(resultSelector));
    }
    return new Observable_1$8.Observable(function (subscriber) {
        var handler = function () {
            var e = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                e[_i] = arguments[_i];
            }
            return subscriber.next(e.length === 1 ? e[0] : e);
        };
        var retValue = addHandler(handler);
        return isFunction_1$9.isFunction(removeHandler) ? function () { return removeHandler(handler, retValue); } : undefined;
    });
}
fromEventPattern$1.fromEventPattern = fromEventPattern;

var generate$1 = {};

var __generator$9 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(generate$1, "__esModule", { value: true });
generate$1.generate = void 0;
var identity_1$b = identity$2;
var isScheduler_1$1 = isScheduler$1;
var defer_1$1 = defer$1;
var scheduleIterable_1 = scheduleIterable$1;
function generate(initialStateOrOptions, condition, iterate, resultSelectorOrScheduler, scheduler) {
    var _a, _b;
    var resultSelector;
    var initialState;
    if (arguments.length === 1) {
        (_a = initialStateOrOptions, initialState = _a.initialState, condition = _a.condition, iterate = _a.iterate, _b = _a.resultSelector, resultSelector = _b === void 0 ? identity_1$b.identity : _b, scheduler = _a.scheduler);
    }
    else {
        initialState = initialStateOrOptions;
        if (!resultSelectorOrScheduler || isScheduler_1$1.isScheduler(resultSelectorOrScheduler)) {
            resultSelector = identity_1$b.identity;
            scheduler = resultSelectorOrScheduler;
        }
        else {
            resultSelector = resultSelectorOrScheduler;
        }
    }
    function gen() {
        var state;
        return __generator$9(this, function (_a) {
            switch (_a.label) {
                case 0:
                    state = initialState;
                    _a.label = 1;
                case 1:
                    if (!(!condition || condition(state))) return [3, 4];
                    return [4, resultSelector(state)];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    state = iterate(state);
                    return [3, 1];
                case 4: return [2];
            }
        });
    }
    return defer_1$1.defer((scheduler
        ?
            function () { return scheduleIterable_1.scheduleIterable(gen(), scheduler); }
        :
            gen));
}
generate$1.generate = generate;

var iif$1 = {};

Object.defineProperty(iif$1, "__esModule", { value: true });
iif$1.iif = void 0;
var defer_1 = defer$1;
function iif(condition, trueResult, falseResult) {
    return defer_1.defer(function () { return (condition() ? trueResult : falseResult); });
}
iif$1.iif = iif;

var interval$1 = {};

var timer$1 = {};

Object.defineProperty(timer$1, "__esModule", { value: true });
timer$1.timer = void 0;
var Observable_1$7 = Observable$1;
var async_1$a = async;
var isScheduler_1 = isScheduler$1;
var isDate_1$1 = isDate;
function timer(dueTime, intervalOrScheduler, scheduler) {
    if (dueTime === void 0) { dueTime = 0; }
    if (scheduler === void 0) { scheduler = async_1$a.async; }
    var intervalDuration = -1;
    if (intervalOrScheduler != null) {
        if (isScheduler_1.isScheduler(intervalOrScheduler)) {
            scheduler = intervalOrScheduler;
        }
        else {
            intervalDuration = intervalOrScheduler;
        }
    }
    return new Observable_1$7.Observable(function (subscriber) {
        var due = isDate_1$1.isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
        if (due < 0) {
            due = 0;
        }
        var n = 0;
        return scheduler.schedule(function () {
            if (!subscriber.closed) {
                subscriber.next(n++);
                if (0 <= intervalDuration) {
                    this.schedule(undefined, intervalDuration);
                }
                else {
                    subscriber.complete();
                }
            }
        }, due);
    });
}
timer$1.timer = timer;

Object.defineProperty(interval$1, "__esModule", { value: true });
interval$1.interval = void 0;
var async_1$9 = async;
var timer_1$5 = timer$1;
function interval(period, scheduler) {
    if (period === void 0) { period = 0; }
    if (scheduler === void 0) { scheduler = async_1$9.asyncScheduler; }
    if (period < 0) {
        period = 0;
    }
    return timer_1$5.timer(period, period, scheduler);
}
interval$1.interval = interval;

var merge$3 = {};

Object.defineProperty(merge$3, "__esModule", { value: true });
merge$3.merge = void 0;
var mergeAll_1$1 = mergeAll$1;
var innerFrom_1$v = innerFrom$1;
var empty_1$6 = empty;
var args_1$8 = args;
var from_1$3 = from$1;
function merge$2() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var scheduler = args_1$8.popScheduler(args);
    var concurrent = args_1$8.popNumber(args, Infinity);
    var sources = args;
    return !sources.length
        ?
            empty_1$6.EMPTY
        : sources.length === 1
            ?
                innerFrom_1$v.innerFrom(sources[0])
            :
                mergeAll_1$1.mergeAll(concurrent)(from_1$3.from(sources, scheduler));
}
merge$3.merge = merge$2;

var never = {};

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.never = exports.NEVER = void 0;
var Observable_1 = Observable$1;
var noop_1 = noop$1;
exports.NEVER = new Observable_1.Observable(noop_1.noop);
function never() {
    return exports.NEVER;
}
exports.never = never;

}(never));

var onErrorResumeNext$1 = {};

var argsOrArgArray$1 = {};

Object.defineProperty(argsOrArgArray$1, "__esModule", { value: true });
argsOrArgArray$1.argsOrArgArray = void 0;
var isArray = Array.isArray;
function argsOrArgArray(args) {
    return args.length === 1 && isArray(args[0]) ? args[0] : args;
}
argsOrArgArray$1.argsOrArgArray = argsOrArgArray;

Object.defineProperty(onErrorResumeNext$1, "__esModule", { value: true });
onErrorResumeNext$1.onErrorResumeNext = void 0;
var Observable_1$6 = Observable$1;
var argsOrArgArray_1$5 = argsOrArgArray$1;
var OperatorSubscriber_1$O = OperatorSubscriber$1;
var noop_1$c = noop$1;
var innerFrom_1$u = innerFrom$1;
function onErrorResumeNext() {
    var sources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        sources[_i] = arguments[_i];
    }
    var nextSources = argsOrArgArray_1$5.argsOrArgArray(sources);
    return new Observable_1$6.Observable(function (subscriber) {
        var sourceIndex = 0;
        var subscribeNext = function () {
            if (sourceIndex < nextSources.length) {
                var nextSource = void 0;
                try {
                    nextSource = innerFrom_1$u.innerFrom(nextSources[sourceIndex++]);
                }
                catch (err) {
                    subscribeNext();
                    return;
                }
                var innerSubscriber = new OperatorSubscriber_1$O.OperatorSubscriber(subscriber, undefined, noop_1$c.noop, noop_1$c.noop);
                nextSource.subscribe(innerSubscriber);
                innerSubscriber.add(subscribeNext);
            }
            else {
                subscriber.complete();
            }
        };
        subscribeNext();
    });
}
onErrorResumeNext$1.onErrorResumeNext = onErrorResumeNext;

var pairs$1 = {};

Object.defineProperty(pairs$1, "__esModule", { value: true });
pairs$1.pairs = void 0;
var from_1$2 = from$1;
function pairs(obj, scheduler) {
    return from_1$2.from(Object.entries(obj), scheduler);
}
pairs$1.pairs = pairs;

var partition$3 = {};

var not$1 = {};

Object.defineProperty(not$1, "__esModule", { value: true });
not$1.not = void 0;
function not(pred, thisArg) {
    return function (value, index) { return !pred.call(thisArg, value, index); };
}
not$1.not = not;

var filter$1 = {};

Object.defineProperty(filter$1, "__esModule", { value: true });
filter$1.filter = void 0;
var lift_1$_ = lift;
var OperatorSubscriber_1$N = OperatorSubscriber$1;
function filter(predicate, thisArg) {
    return lift_1$_.operate(function (source, subscriber) {
        var index = 0;
        source.subscribe(OperatorSubscriber_1$N.createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
    });
}
filter$1.filter = filter;

Object.defineProperty(partition$3, "__esModule", { value: true });
partition$3.partition = void 0;
var not_1$1 = not$1;
var filter_1$5 = filter$1;
var innerFrom_1$t = innerFrom$1;
function partition$2(source, predicate, thisArg) {
    return [filter_1$5.filter(predicate, thisArg)(innerFrom_1$t.innerFrom(source)), filter_1$5.filter(not_1$1.not(predicate, thisArg))(innerFrom_1$t.innerFrom(source))];
}
partition$3.partition = partition$2;

var race$3 = {};

Object.defineProperty(race$3, "__esModule", { value: true });
race$3.raceInit = race$3.race = void 0;
var Observable_1$5 = Observable$1;
var innerFrom_1$s = innerFrom$1;
var argsOrArgArray_1$4 = argsOrArgArray$1;
var OperatorSubscriber_1$M = OperatorSubscriber$1;
function race$2() {
    var sources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        sources[_i] = arguments[_i];
    }
    sources = argsOrArgArray_1$4.argsOrArgArray(sources);
    return sources.length === 1 ? innerFrom_1$s.innerFrom(sources[0]) : new Observable_1$5.Observable(raceInit(sources));
}
race$3.race = race$2;
function raceInit(sources) {
    return function (subscriber) {
        var subscriptions = [];
        var _loop_1 = function (i) {
            subscriptions.push(innerFrom_1$s.innerFrom(sources[i]).subscribe(OperatorSubscriber_1$M.createOperatorSubscriber(subscriber, function (value) {
                if (subscriptions) {
                    for (var s = 0; s < subscriptions.length; s++) {
                        s !== i && subscriptions[s].unsubscribe();
                    }
                    subscriptions = null;
                }
                subscriber.next(value);
            })));
        };
        for (var i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {
            _loop_1(i);
        }
    };
}
race$3.raceInit = raceInit;

var range$1 = {};

Object.defineProperty(range$1, "__esModule", { value: true });
range$1.range = void 0;
var Observable_1$4 = Observable$1;
var empty_1$5 = empty;
function range(start, count, scheduler) {
    if (count == null) {
        count = start;
        start = 0;
    }
    if (count <= 0) {
        return empty_1$5.EMPTY;
    }
    var end = count + start;
    return new Observable_1$4.Observable(scheduler
        ?
            function (subscriber) {
                var n = start;
                return scheduler.schedule(function () {
                    if (n < end) {
                        subscriber.next(n++);
                        this.schedule();
                    }
                    else {
                        subscriber.complete();
                    }
                });
            }
        :
            function (subscriber) {
                var n = start;
                while (n < end && !subscriber.closed) {
                    subscriber.next(n++);
                }
                subscriber.complete();
            });
}
range$1.range = range;

var using$1 = {};

Object.defineProperty(using$1, "__esModule", { value: true });
using$1.using = void 0;
var Observable_1$3 = Observable$1;
var innerFrom_1$r = innerFrom$1;
var empty_1$4 = empty;
function using(resourceFactory, observableFactory) {
    return new Observable_1$3.Observable(function (subscriber) {
        var resource = resourceFactory();
        var result = observableFactory(resource);
        var source = result ? innerFrom_1$r.innerFrom(result) : empty_1$4.EMPTY;
        source.subscribe(subscriber);
        return function () {
            if (resource) {
                resource.unsubscribe();
            }
        };
    });
}
using$1.using = using;

var zip$3 = {};

var __read$l = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$g = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(zip$3, "__esModule", { value: true });
zip$3.zip = void 0;
var Observable_1$2 = Observable$1;
var innerFrom_1$q = innerFrom$1;
var argsOrArgArray_1$3 = argsOrArgArray$1;
var empty_1$3 = empty;
var OperatorSubscriber_1$L = OperatorSubscriber$1;
var args_1$7 = args;
function zip$2() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var resultSelector = args_1$7.popResultSelector(args);
    var sources = argsOrArgArray_1$3.argsOrArgArray(args);
    return sources.length
        ? new Observable_1$2.Observable(function (subscriber) {
            var buffers = sources.map(function () { return []; });
            var completed = sources.map(function () { return false; });
            subscriber.add(function () {
                buffers = completed = null;
            });
            var _loop_1 = function (sourceIndex) {
                innerFrom_1$q.innerFrom(sources[sourceIndex]).subscribe(OperatorSubscriber_1$L.createOperatorSubscriber(subscriber, function (value) {
                    buffers[sourceIndex].push(value);
                    if (buffers.every(function (buffer) { return buffer.length; })) {
                        var result = buffers.map(function (buffer) { return buffer.shift(); });
                        subscriber.next(resultSelector ? resultSelector.apply(void 0, __spreadArray$g([], __read$l(result))) : result);
                        if (buffers.some(function (buffer, i) { return !buffer.length && completed[i]; })) {
                            subscriber.complete();
                        }
                    }
                }, function () {
                    completed[sourceIndex] = true;
                    !buffers[sourceIndex].length && subscriber.complete();
                }));
            };
            for (var sourceIndex = 0; !subscriber.closed && sourceIndex < sources.length; sourceIndex++) {
                _loop_1(sourceIndex);
            }
            return function () {
                buffers = completed = null;
            };
        })
        : empty_1$3.EMPTY;
}
zip$3.zip = zip$2;

var types = {};

Object.defineProperty(types, "__esModule", { value: true });

var audit$1 = {};

Object.defineProperty(audit$1, "__esModule", { value: true });
audit$1.audit = void 0;
var lift_1$Z = lift;
var innerFrom_1$p = innerFrom$1;
var OperatorSubscriber_1$K = OperatorSubscriber$1;
function audit(durationSelector) {
    return lift_1$Z.operate(function (source, subscriber) {
        var hasValue = false;
        var lastValue = null;
        var durationSubscriber = null;
        var isComplete = false;
        var endDuration = function () {
            durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
            durationSubscriber = null;
            if (hasValue) {
                hasValue = false;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
            }
            isComplete && subscriber.complete();
        };
        var cleanupDuration = function () {
            durationSubscriber = null;
            isComplete && subscriber.complete();
        };
        source.subscribe(OperatorSubscriber_1$K.createOperatorSubscriber(subscriber, function (value) {
            hasValue = true;
            lastValue = value;
            if (!durationSubscriber) {
                innerFrom_1$p.innerFrom(durationSelector(value)).subscribe((durationSubscriber = OperatorSubscriber_1$K.createOperatorSubscriber(subscriber, endDuration, cleanupDuration)));
            }
        }, function () {
            isComplete = true;
            (!hasValue || !durationSubscriber || durationSubscriber.closed) && subscriber.complete();
        }));
    });
}
audit$1.audit = audit;

var auditTime$1 = {};

Object.defineProperty(auditTime$1, "__esModule", { value: true });
auditTime$1.auditTime = void 0;
var async_1$8 = async;
var audit_1 = audit$1;
var timer_1$4 = timer$1;
function auditTime(duration, scheduler) {
    if (scheduler === void 0) { scheduler = async_1$8.asyncScheduler; }
    return audit_1.audit(function () { return timer_1$4.timer(duration, scheduler); });
}
auditTime$1.auditTime = auditTime;

var buffer$2 = {};

Object.defineProperty(buffer$2, "__esModule", { value: true });
buffer$2.buffer = void 0;
var lift_1$Y = lift;
var noop_1$b = noop$1;
var OperatorSubscriber_1$J = OperatorSubscriber$1;
var innerFrom_1$o = innerFrom$1;
function buffer$1(closingNotifier) {
    return lift_1$Y.operate(function (source, subscriber) {
        var currentBuffer = [];
        source.subscribe(OperatorSubscriber_1$J.createOperatorSubscriber(subscriber, function (value) { return currentBuffer.push(value); }, function () {
            subscriber.next(currentBuffer);
            subscriber.complete();
        }));
        innerFrom_1$o.innerFrom(closingNotifier).subscribe(OperatorSubscriber_1$J.createOperatorSubscriber(subscriber, function () {
            var b = currentBuffer;
            currentBuffer = [];
            subscriber.next(b);
        }, noop_1$b.noop));
        return function () {
            currentBuffer = null;
        };
    });
}
buffer$2.buffer = buffer$1;

var bufferCount$1 = {};

var __values$7 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(bufferCount$1, "__esModule", { value: true });
bufferCount$1.bufferCount = void 0;
var lift_1$X = lift;
var OperatorSubscriber_1$I = OperatorSubscriber$1;
var arrRemove_1$4 = arrRemove$1;
function bufferCount(bufferSize, startBufferEvery) {
    if (startBufferEvery === void 0) { startBufferEvery = null; }
    startBufferEvery = startBufferEvery !== null && startBufferEvery !== void 0 ? startBufferEvery : bufferSize;
    return lift_1$X.operate(function (source, subscriber) {
        var buffers = [];
        var count = 0;
        source.subscribe(OperatorSubscriber_1$I.createOperatorSubscriber(subscriber, function (value) {
            var e_1, _a, e_2, _b;
            var toEmit = null;
            if (count++ % startBufferEvery === 0) {
                buffers.push([]);
            }
            try {
                for (var buffers_1 = __values$7(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
                    var buffer = buffers_1_1.value;
                    buffer.push(value);
                    if (bufferSize <= buffer.length) {
                        toEmit = toEmit !== null && toEmit !== void 0 ? toEmit : [];
                        toEmit.push(buffer);
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (buffers_1_1 && !buffers_1_1.done && (_a = buffers_1.return)) _a.call(buffers_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            if (toEmit) {
                try {
                    for (var toEmit_1 = __values$7(toEmit), toEmit_1_1 = toEmit_1.next(); !toEmit_1_1.done; toEmit_1_1 = toEmit_1.next()) {
                        var buffer = toEmit_1_1.value;
                        arrRemove_1$4.arrRemove(buffers, buffer);
                        subscriber.next(buffer);
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (toEmit_1_1 && !toEmit_1_1.done && (_b = toEmit_1.return)) _b.call(toEmit_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
        }, function () {
            var e_3, _a;
            try {
                for (var buffers_2 = __values$7(buffers), buffers_2_1 = buffers_2.next(); !buffers_2_1.done; buffers_2_1 = buffers_2.next()) {
                    var buffer = buffers_2_1.value;
                    subscriber.next(buffer);
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (buffers_2_1 && !buffers_2_1.done && (_a = buffers_2.return)) _a.call(buffers_2);
                }
                finally { if (e_3) throw e_3.error; }
            }
            subscriber.complete();
        }, undefined, function () {
            buffers = null;
        }));
    });
}
bufferCount$1.bufferCount = bufferCount;

var bufferTime$1 = {};

var __values$6 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(bufferTime$1, "__esModule", { value: true });
bufferTime$1.bufferTime = void 0;
var Subscription_1$3 = Subscription$1;
var lift_1$W = lift;
var OperatorSubscriber_1$H = OperatorSubscriber$1;
var arrRemove_1$3 = arrRemove$1;
var async_1$7 = async;
var args_1$6 = args;
var executeSchedule_1$1 = executeSchedule$1;
function bufferTime(bufferTimeSpan) {
    var _a, _b;
    var otherArgs = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        otherArgs[_i - 1] = arguments[_i];
    }
    var scheduler = (_a = args_1$6.popScheduler(otherArgs)) !== null && _a !== void 0 ? _a : async_1$7.asyncScheduler;
    var bufferCreationInterval = (_b = otherArgs[0]) !== null && _b !== void 0 ? _b : null;
    var maxBufferSize = otherArgs[1] || Infinity;
    return lift_1$W.operate(function (source, subscriber) {
        var bufferRecords = [];
        var restartOnEmit = false;
        var emit = function (record) {
            var buffer = record.buffer, subs = record.subs;
            subs.unsubscribe();
            arrRemove_1$3.arrRemove(bufferRecords, record);
            subscriber.next(buffer);
            restartOnEmit && startBuffer();
        };
        var startBuffer = function () {
            if (bufferRecords) {
                var subs = new Subscription_1$3.Subscription();
                subscriber.add(subs);
                var buffer = [];
                var record_1 = {
                    buffer: buffer,
                    subs: subs,
                };
                bufferRecords.push(record_1);
                executeSchedule_1$1.executeSchedule(subs, scheduler, function () { return emit(record_1); }, bufferTimeSpan);
            }
        };
        if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {
            executeSchedule_1$1.executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);
        }
        else {
            restartOnEmit = true;
        }
        startBuffer();
        var bufferTimeSubscriber = OperatorSubscriber_1$H.createOperatorSubscriber(subscriber, function (value) {
            var e_1, _a;
            var recordsCopy = bufferRecords.slice();
            try {
                for (var recordsCopy_1 = __values$6(recordsCopy), recordsCopy_1_1 = recordsCopy_1.next(); !recordsCopy_1_1.done; recordsCopy_1_1 = recordsCopy_1.next()) {
                    var record = recordsCopy_1_1.value;
                    var buffer = record.buffer;
                    buffer.push(value);
                    maxBufferSize <= buffer.length && emit(record);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (recordsCopy_1_1 && !recordsCopy_1_1.done && (_a = recordsCopy_1.return)) _a.call(recordsCopy_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }, function () {
            while (bufferRecords === null || bufferRecords === void 0 ? void 0 : bufferRecords.length) {
                subscriber.next(bufferRecords.shift().buffer);
            }
            bufferTimeSubscriber === null || bufferTimeSubscriber === void 0 ? void 0 : bufferTimeSubscriber.unsubscribe();
            subscriber.complete();
            subscriber.unsubscribe();
        }, undefined, function () { return (bufferRecords = null); });
        source.subscribe(bufferTimeSubscriber);
    });
}
bufferTime$1.bufferTime = bufferTime;

var bufferToggle$1 = {};

var __values$5 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(bufferToggle$1, "__esModule", { value: true });
bufferToggle$1.bufferToggle = void 0;
var Subscription_1$2 = Subscription$1;
var lift_1$V = lift;
var innerFrom_1$n = innerFrom$1;
var OperatorSubscriber_1$G = OperatorSubscriber$1;
var noop_1$a = noop$1;
var arrRemove_1$2 = arrRemove$1;
function bufferToggle(openings, closingSelector) {
    return lift_1$V.operate(function (source, subscriber) {
        var buffers = [];
        innerFrom_1$n.innerFrom(openings).subscribe(OperatorSubscriber_1$G.createOperatorSubscriber(subscriber, function (openValue) {
            var buffer = [];
            buffers.push(buffer);
            var closingSubscription = new Subscription_1$2.Subscription();
            var emitBuffer = function () {
                arrRemove_1$2.arrRemove(buffers, buffer);
                subscriber.next(buffer);
                closingSubscription.unsubscribe();
            };
            closingSubscription.add(innerFrom_1$n.innerFrom(closingSelector(openValue)).subscribe(OperatorSubscriber_1$G.createOperatorSubscriber(subscriber, emitBuffer, noop_1$a.noop)));
        }, noop_1$a.noop));
        source.subscribe(OperatorSubscriber_1$G.createOperatorSubscriber(subscriber, function (value) {
            var e_1, _a;
            try {
                for (var buffers_1 = __values$5(buffers), buffers_1_1 = buffers_1.next(); !buffers_1_1.done; buffers_1_1 = buffers_1.next()) {
                    var buffer = buffers_1_1.value;
                    buffer.push(value);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (buffers_1_1 && !buffers_1_1.done && (_a = buffers_1.return)) _a.call(buffers_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }, function () {
            while (buffers.length > 0) {
                subscriber.next(buffers.shift());
            }
            subscriber.complete();
        }));
    });
}
bufferToggle$1.bufferToggle = bufferToggle;

var bufferWhen$1 = {};

Object.defineProperty(bufferWhen$1, "__esModule", { value: true });
bufferWhen$1.bufferWhen = void 0;
var lift_1$U = lift;
var noop_1$9 = noop$1;
var OperatorSubscriber_1$F = OperatorSubscriber$1;
var innerFrom_1$m = innerFrom$1;
function bufferWhen(closingSelector) {
    return lift_1$U.operate(function (source, subscriber) {
        var buffer = null;
        var closingSubscriber = null;
        var openBuffer = function () {
            closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
            var b = buffer;
            buffer = [];
            b && subscriber.next(b);
            innerFrom_1$m.innerFrom(closingSelector()).subscribe((closingSubscriber = OperatorSubscriber_1$F.createOperatorSubscriber(subscriber, openBuffer, noop_1$9.noop)));
        };
        openBuffer();
        source.subscribe(OperatorSubscriber_1$F.createOperatorSubscriber(subscriber, function (value) { return buffer === null || buffer === void 0 ? void 0 : buffer.push(value); }, function () {
            buffer && subscriber.next(buffer);
            subscriber.complete();
        }, undefined, function () { return (buffer = closingSubscriber = null); }));
    });
}
bufferWhen$1.bufferWhen = bufferWhen;

var catchError$1 = {};

Object.defineProperty(catchError$1, "__esModule", { value: true });
catchError$1.catchError = void 0;
var innerFrom_1$l = innerFrom$1;
var OperatorSubscriber_1$E = OperatorSubscriber$1;
var lift_1$T = lift;
function catchError(selector) {
    return lift_1$T.operate(function (source, subscriber) {
        var innerSub = null;
        var syncUnsub = false;
        var handledResult;
        innerSub = source.subscribe(OperatorSubscriber_1$E.createOperatorSubscriber(subscriber, undefined, undefined, function (err) {
            handledResult = innerFrom_1$l.innerFrom(selector(err, catchError(selector)(source)));
            if (innerSub) {
                innerSub.unsubscribe();
                innerSub = null;
                handledResult.subscribe(subscriber);
            }
            else {
                syncUnsub = true;
            }
        }));
        if (syncUnsub) {
            innerSub.unsubscribe();
            innerSub = null;
            handledResult.subscribe(subscriber);
        }
    });
}
catchError$1.catchError = catchError;

var combineAll = {};

var combineLatestAll$1 = {};

var joinAllInternals$1 = {};

var toArray$1 = {};

var reduce$1 = {};

var scanInternals$1 = {};

Object.defineProperty(scanInternals$1, "__esModule", { value: true });
scanInternals$1.scanInternals = void 0;
var OperatorSubscriber_1$D = OperatorSubscriber$1;
function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
    return function (source, subscriber) {
        var hasState = hasSeed;
        var state = seed;
        var index = 0;
        source.subscribe(OperatorSubscriber_1$D.createOperatorSubscriber(subscriber, function (value) {
            var i = index++;
            state = hasState
                ?
                    accumulator(state, value, i)
                :
                    ((hasState = true), value);
            emitOnNext && subscriber.next(state);
        }, emitBeforeComplete &&
            (function () {
                hasState && subscriber.next(state);
                subscriber.complete();
            })));
    };
}
scanInternals$1.scanInternals = scanInternals;

Object.defineProperty(reduce$1, "__esModule", { value: true });
reduce$1.reduce = void 0;
var scanInternals_1$1 = scanInternals$1;
var lift_1$S = lift;
function reduce(accumulator, seed) {
    return lift_1$S.operate(scanInternals_1$1.scanInternals(accumulator, seed, arguments.length >= 2, false, true));
}
reduce$1.reduce = reduce;

Object.defineProperty(toArray$1, "__esModule", { value: true });
toArray$1.toArray = void 0;
var reduce_1$3 = reduce$1;
var lift_1$R = lift;
var arrReducer = function (arr, value) { return (arr.push(value), arr); };
function toArray() {
    return lift_1$R.operate(function (source, subscriber) {
        reduce_1$3.reduce(arrReducer, [])(source).subscribe(subscriber);
    });
}
toArray$1.toArray = toArray;

Object.defineProperty(joinAllInternals$1, "__esModule", { value: true });
joinAllInternals$1.joinAllInternals = void 0;
var identity_1$a = identity$2;
var mapOneOrManyArgs_1$1 = mapOneOrManyArgs$1;
var pipe_1$1 = pipe$1;
var mergeMap_1$4 = mergeMap$1;
var toArray_1 = toArray$1;
function joinAllInternals(joinFn, project) {
    return pipe_1$1.pipe(toArray_1.toArray(), mergeMap_1$4.mergeMap(function (sources) { return joinFn(sources); }), project ? mapOneOrManyArgs_1$1.mapOneOrManyArgs(project) : identity_1$a.identity);
}
joinAllInternals$1.joinAllInternals = joinAllInternals;

Object.defineProperty(combineLatestAll$1, "__esModule", { value: true });
combineLatestAll$1.combineLatestAll = void 0;
var combineLatest_1$2 = combineLatest$3;
var joinAllInternals_1$1 = joinAllInternals$1;
function combineLatestAll(project) {
    return joinAllInternals_1$1.joinAllInternals(combineLatest_1$2.combineLatest, project);
}
combineLatestAll$1.combineLatestAll = combineLatestAll;

Object.defineProperty(combineAll, "__esModule", { value: true });
combineAll.combineAll = void 0;
var combineLatestAll_1 = combineLatestAll$1;
combineAll.combineAll = combineLatestAll_1.combineLatestAll;

var combineLatestWith$1 = {};

var combineLatest$1 = {};

var __read$k = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$f = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(combineLatest$1, "__esModule", { value: true });
combineLatest$1.combineLatest = void 0;
var combineLatest_1$1 = combineLatest$3;
var lift_1$Q = lift;
var argsOrArgArray_1$2 = argsOrArgArray$1;
var mapOneOrManyArgs_1 = mapOneOrManyArgs$1;
var pipe_1 = pipe$1;
var args_1$5 = args;
function combineLatest() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var resultSelector = args_1$5.popResultSelector(args);
    return resultSelector
        ? pipe_1.pipe(combineLatest.apply(void 0, __spreadArray$f([], __read$k(args))), mapOneOrManyArgs_1.mapOneOrManyArgs(resultSelector))
        : lift_1$Q.operate(function (source, subscriber) {
            combineLatest_1$1.combineLatestInit(__spreadArray$f([source], __read$k(argsOrArgArray_1$2.argsOrArgArray(args))))(subscriber);
        });
}
combineLatest$1.combineLatest = combineLatest;

var __read$j = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$e = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(combineLatestWith$1, "__esModule", { value: true });
combineLatestWith$1.combineLatestWith = void 0;
var combineLatest_1 = combineLatest$1;
function combineLatestWith() {
    var otherSources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        otherSources[_i] = arguments[_i];
    }
    return combineLatest_1.combineLatest.apply(void 0, __spreadArray$e([], __read$j(otherSources)));
}
combineLatestWith$1.combineLatestWith = combineLatestWith;

var concatMap$1 = {};

Object.defineProperty(concatMap$1, "__esModule", { value: true });
concatMap$1.concatMap = void 0;
var mergeMap_1$3 = mergeMap$1;
var isFunction_1$8 = isFunction$1;
function concatMap(project, resultSelector) {
    return isFunction_1$8.isFunction(resultSelector) ? mergeMap_1$3.mergeMap(project, resultSelector, 1) : mergeMap_1$3.mergeMap(project, 1);
}
concatMap$1.concatMap = concatMap;

var concatMapTo$1 = {};

Object.defineProperty(concatMapTo$1, "__esModule", { value: true });
concatMapTo$1.concatMapTo = void 0;
var concatMap_1 = concatMap$1;
var isFunction_1$7 = isFunction$1;
function concatMapTo(innerObservable, resultSelector) {
    return isFunction_1$7.isFunction(resultSelector) ? concatMap_1.concatMap(function () { return innerObservable; }, resultSelector) : concatMap_1.concatMap(function () { return innerObservable; });
}
concatMapTo$1.concatMapTo = concatMapTo;

var concatWith$1 = {};

var concat$1 = {};

var __read$i = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$d = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(concat$1, "__esModule", { value: true });
concat$1.concat = void 0;
var lift_1$P = lift;
var concatAll_1 = concatAll$1;
var args_1$4 = args;
var from_1$1 = from$1;
function concat() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var scheduler = args_1$4.popScheduler(args);
    return lift_1$P.operate(function (source, subscriber) {
        concatAll_1.concatAll()(from_1$1.from(__spreadArray$d([source], __read$i(args)), scheduler)).subscribe(subscriber);
    });
}
concat$1.concat = concat;

var __read$h = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$c = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(concatWith$1, "__esModule", { value: true });
concatWith$1.concatWith = void 0;
var concat_1$3 = concat$1;
function concatWith() {
    var otherSources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        otherSources[_i] = arguments[_i];
    }
    return concat_1$3.concat.apply(void 0, __spreadArray$c([], __read$h(otherSources)));
}
concatWith$1.concatWith = concatWith;

var connect$1 = {};

var fromSubscribable$1 = {};

Object.defineProperty(fromSubscribable$1, "__esModule", { value: true });
fromSubscribable$1.fromSubscribable = void 0;
var Observable_1$1 = Observable$1;
function fromSubscribable(subscribable) {
    return new Observable_1$1.Observable(function (subscriber) { return subscribable.subscribe(subscriber); });
}
fromSubscribable$1.fromSubscribable = fromSubscribable;

Object.defineProperty(connect$1, "__esModule", { value: true });
connect$1.connect = void 0;
var Subject_1$a = Subject$1;
var innerFrom_1$k = innerFrom$1;
var lift_1$O = lift;
var fromSubscribable_1 = fromSubscribable$1;
var DEFAULT_CONFIG = {
    connector: function () { return new Subject_1$a.Subject(); },
};
function connect(selector, config) {
    if (config === void 0) { config = DEFAULT_CONFIG; }
    var connector = config.connector;
    return lift_1$O.operate(function (source, subscriber) {
        var subject = connector();
        innerFrom_1$k.innerFrom(selector(fromSubscribable_1.fromSubscribable(subject))).subscribe(subscriber);
        subscriber.add(source.subscribe(subject));
    });
}
connect$1.connect = connect;

var count$1 = {};

Object.defineProperty(count$1, "__esModule", { value: true });
count$1.count = void 0;
var reduce_1$2 = reduce$1;
function count(predicate) {
    return reduce_1$2.reduce(function (total, value, i) { return (!predicate || predicate(value, i) ? total + 1 : total); }, 0);
}
count$1.count = count;

var debounce$1 = {};

Object.defineProperty(debounce$1, "__esModule", { value: true });
debounce$1.debounce = void 0;
var lift_1$N = lift;
var noop_1$8 = noop$1;
var OperatorSubscriber_1$C = OperatorSubscriber$1;
var innerFrom_1$j = innerFrom$1;
function debounce(durationSelector) {
    return lift_1$N.operate(function (source, subscriber) {
        var hasValue = false;
        var lastValue = null;
        var durationSubscriber = null;
        var emit = function () {
            durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
            durationSubscriber = null;
            if (hasValue) {
                hasValue = false;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
            }
        };
        source.subscribe(OperatorSubscriber_1$C.createOperatorSubscriber(subscriber, function (value) {
            durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
            hasValue = true;
            lastValue = value;
            durationSubscriber = OperatorSubscriber_1$C.createOperatorSubscriber(subscriber, emit, noop_1$8.noop);
            innerFrom_1$j.innerFrom(durationSelector(value)).subscribe(durationSubscriber);
        }, function () {
            emit();
            subscriber.complete();
        }, undefined, function () {
            lastValue = durationSubscriber = null;
        }));
    });
}
debounce$1.debounce = debounce;

var debounceTime$1 = {};

Object.defineProperty(debounceTime$1, "__esModule", { value: true });
debounceTime$1.debounceTime = void 0;
var async_1$6 = async;
var lift_1$M = lift;
var OperatorSubscriber_1$B = OperatorSubscriber$1;
function debounceTime(dueTime, scheduler) {
    if (scheduler === void 0) { scheduler = async_1$6.asyncScheduler; }
    return lift_1$M.operate(function (source, subscriber) {
        var activeTask = null;
        var lastValue = null;
        var lastTime = null;
        var emit = function () {
            if (activeTask) {
                activeTask.unsubscribe();
                activeTask = null;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
            }
        };
        function emitWhenIdle() {
            var targetTime = lastTime + dueTime;
            var now = scheduler.now();
            if (now < targetTime) {
                activeTask = this.schedule(undefined, targetTime - now);
                subscriber.add(activeTask);
                return;
            }
            emit();
        }
        source.subscribe(OperatorSubscriber_1$B.createOperatorSubscriber(subscriber, function (value) {
            lastValue = value;
            lastTime = scheduler.now();
            if (!activeTask) {
                activeTask = scheduler.schedule(emitWhenIdle, dueTime);
                subscriber.add(activeTask);
            }
        }, function () {
            emit();
            subscriber.complete();
        }, undefined, function () {
            lastValue = activeTask = null;
        }));
    });
}
debounceTime$1.debounceTime = debounceTime;

var defaultIfEmpty$1 = {};

Object.defineProperty(defaultIfEmpty$1, "__esModule", { value: true });
defaultIfEmpty$1.defaultIfEmpty = void 0;
var lift_1$L = lift;
var OperatorSubscriber_1$A = OperatorSubscriber$1;
function defaultIfEmpty(defaultValue) {
    return lift_1$L.operate(function (source, subscriber) {
        var hasValue = false;
        source.subscribe(OperatorSubscriber_1$A.createOperatorSubscriber(subscriber, function (value) {
            hasValue = true;
            subscriber.next(value);
        }, function () {
            if (!hasValue) {
                subscriber.next(defaultValue);
            }
            subscriber.complete();
        }));
    });
}
defaultIfEmpty$1.defaultIfEmpty = defaultIfEmpty;

var delay$1 = {};

var delayWhen$1 = {};

var take$1 = {};

Object.defineProperty(take$1, "__esModule", { value: true });
take$1.take = void 0;
var empty_1$2 = empty;
var lift_1$K = lift;
var OperatorSubscriber_1$z = OperatorSubscriber$1;
function take(count) {
    return count <= 0
        ?
            function () { return empty_1$2.EMPTY; }
        : lift_1$K.operate(function (source, subscriber) {
            var seen = 0;
            source.subscribe(OperatorSubscriber_1$z.createOperatorSubscriber(subscriber, function (value) {
                if (++seen <= count) {
                    subscriber.next(value);
                    if (count <= seen) {
                        subscriber.complete();
                    }
                }
            }));
        });
}
take$1.take = take;

var ignoreElements$1 = {};

Object.defineProperty(ignoreElements$1, "__esModule", { value: true });
ignoreElements$1.ignoreElements = void 0;
var lift_1$J = lift;
var OperatorSubscriber_1$y = OperatorSubscriber$1;
var noop_1$7 = noop$1;
function ignoreElements() {
    return lift_1$J.operate(function (source, subscriber) {
        source.subscribe(OperatorSubscriber_1$y.createOperatorSubscriber(subscriber, noop_1$7.noop));
    });
}
ignoreElements$1.ignoreElements = ignoreElements;

var mapTo$1 = {};

Object.defineProperty(mapTo$1, "__esModule", { value: true });
mapTo$1.mapTo = void 0;
var map_1$3 = map$1;
function mapTo(value) {
    return map_1$3.map(function () { return value; });
}
mapTo$1.mapTo = mapTo;

Object.defineProperty(delayWhen$1, "__esModule", { value: true });
delayWhen$1.delayWhen = void 0;
var concat_1$2 = concat$3;
var take_1$2 = take$1;
var ignoreElements_1 = ignoreElements$1;
var mapTo_1 = mapTo$1;
var mergeMap_1$2 = mergeMap$1;
var innerFrom_1$i = innerFrom$1;
function delayWhen(delayDurationSelector, subscriptionDelay) {
    if (subscriptionDelay) {
        return function (source) {
            return concat_1$2.concat(subscriptionDelay.pipe(take_1$2.take(1), ignoreElements_1.ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));
        };
    }
    return mergeMap_1$2.mergeMap(function (value, index) { return innerFrom_1$i.innerFrom(delayDurationSelector(value, index)).pipe(take_1$2.take(1), mapTo_1.mapTo(value)); });
}
delayWhen$1.delayWhen = delayWhen;

Object.defineProperty(delay$1, "__esModule", { value: true });
delay$1.delay = void 0;
var async_1$5 = async;
var delayWhen_1 = delayWhen$1;
var timer_1$3 = timer$1;
function delay(due, scheduler) {
    if (scheduler === void 0) { scheduler = async_1$5.asyncScheduler; }
    var duration = timer_1$3.timer(due, scheduler);
    return delayWhen_1.delayWhen(function () { return duration; });
}
delay$1.delay = delay;

var dematerialize$1 = {};

Object.defineProperty(dematerialize$1, "__esModule", { value: true });
dematerialize$1.dematerialize = void 0;
var Notification_1$1 = Notification;
var lift_1$I = lift;
var OperatorSubscriber_1$x = OperatorSubscriber$1;
function dematerialize() {
    return lift_1$I.operate(function (source, subscriber) {
        source.subscribe(OperatorSubscriber_1$x.createOperatorSubscriber(subscriber, function (notification) { return Notification_1$1.observeNotification(notification, subscriber); }));
    });
}
dematerialize$1.dematerialize = dematerialize;

var distinct$1 = {};

Object.defineProperty(distinct$1, "__esModule", { value: true });
distinct$1.distinct = void 0;
var lift_1$H = lift;
var OperatorSubscriber_1$w = OperatorSubscriber$1;
var noop_1$6 = noop$1;
var innerFrom_1$h = innerFrom$1;
function distinct(keySelector, flushes) {
    return lift_1$H.operate(function (source, subscriber) {
        var distinctKeys = new Set();
        source.subscribe(OperatorSubscriber_1$w.createOperatorSubscriber(subscriber, function (value) {
            var key = keySelector ? keySelector(value) : value;
            if (!distinctKeys.has(key)) {
                distinctKeys.add(key);
                subscriber.next(value);
            }
        }));
        flushes && innerFrom_1$h.innerFrom(flushes).subscribe(OperatorSubscriber_1$w.createOperatorSubscriber(subscriber, function () { return distinctKeys.clear(); }, noop_1$6.noop));
    });
}
distinct$1.distinct = distinct;

var distinctUntilChanged$1 = {};

Object.defineProperty(distinctUntilChanged$1, "__esModule", { value: true });
distinctUntilChanged$1.distinctUntilChanged = void 0;
var identity_1$9 = identity$2;
var lift_1$G = lift;
var OperatorSubscriber_1$v = OperatorSubscriber$1;
function distinctUntilChanged(comparator, keySelector) {
    if (keySelector === void 0) { keySelector = identity_1$9.identity; }
    comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
    return lift_1$G.operate(function (source, subscriber) {
        var previousKey;
        var first = true;
        source.subscribe(OperatorSubscriber_1$v.createOperatorSubscriber(subscriber, function (value) {
            var currentKey = keySelector(value);
            if (first || !comparator(previousKey, currentKey)) {
                first = false;
                previousKey = currentKey;
                subscriber.next(value);
            }
        }));
    });
}
distinctUntilChanged$1.distinctUntilChanged = distinctUntilChanged;
function defaultCompare(a, b) {
    return a === b;
}

var distinctUntilKeyChanged$1 = {};

Object.defineProperty(distinctUntilKeyChanged$1, "__esModule", { value: true });
distinctUntilKeyChanged$1.distinctUntilKeyChanged = void 0;
var distinctUntilChanged_1 = distinctUntilChanged$1;
function distinctUntilKeyChanged(key, compare) {
    return distinctUntilChanged_1.distinctUntilChanged(function (x, y) { return (compare ? compare(x[key], y[key]) : x[key] === y[key]); });
}
distinctUntilKeyChanged$1.distinctUntilKeyChanged = distinctUntilKeyChanged;

var elementAt$1 = {};

var throwIfEmpty$1 = {};

Object.defineProperty(throwIfEmpty$1, "__esModule", { value: true });
throwIfEmpty$1.throwIfEmpty = void 0;
var EmptyError_1$3 = EmptyError;
var lift_1$F = lift;
var OperatorSubscriber_1$u = OperatorSubscriber$1;
function throwIfEmpty(errorFactory) {
    if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
    return lift_1$F.operate(function (source, subscriber) {
        var hasValue = false;
        source.subscribe(OperatorSubscriber_1$u.createOperatorSubscriber(subscriber, function (value) {
            hasValue = true;
            subscriber.next(value);
        }, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
    });
}
throwIfEmpty$1.throwIfEmpty = throwIfEmpty;
function defaultErrorFactory() {
    return new EmptyError_1$3.EmptyError();
}

Object.defineProperty(elementAt$1, "__esModule", { value: true });
elementAt$1.elementAt = void 0;
var ArgumentOutOfRangeError_1 = ArgumentOutOfRangeError;
var filter_1$4 = filter$1;
var throwIfEmpty_1$2 = throwIfEmpty$1;
var defaultIfEmpty_1$2 = defaultIfEmpty$1;
var take_1$1 = take$1;
function elementAt(index, defaultValue) {
    if (index < 0) {
        throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError();
    }
    var hasDefaultValue = arguments.length >= 2;
    return function (source) {
        return source.pipe(filter_1$4.filter(function (v, i) { return i === index; }), take_1$1.take(1), hasDefaultValue ? defaultIfEmpty_1$2.defaultIfEmpty(defaultValue) : throwIfEmpty_1$2.throwIfEmpty(function () { return new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError(); }));
    };
}
elementAt$1.elementAt = elementAt;

var endWith$1 = {};

var __read$g = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$b = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(endWith$1, "__esModule", { value: true });
endWith$1.endWith = void 0;
var concat_1$1 = concat$3;
var of_1 = of$1;
function endWith() {
    var values = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
    }
    return function (source) { return concat_1$1.concat(source, of_1.of.apply(void 0, __spreadArray$b([], __read$g(values)))); };
}
endWith$1.endWith = endWith;

var every$1 = {};

Object.defineProperty(every$1, "__esModule", { value: true });
every$1.every = void 0;
var lift_1$E = lift;
var OperatorSubscriber_1$t = OperatorSubscriber$1;
function every(predicate, thisArg) {
    return lift_1$E.operate(function (source, subscriber) {
        var index = 0;
        source.subscribe(OperatorSubscriber_1$t.createOperatorSubscriber(subscriber, function (value) {
            if (!predicate.call(thisArg, value, index++, source)) {
                subscriber.next(false);
                subscriber.complete();
            }
        }, function () {
            subscriber.next(true);
            subscriber.complete();
        }));
    });
}
every$1.every = every;

var exhaust = {};

var exhaustAll$1 = {};

var exhaustMap$1 = {};

Object.defineProperty(exhaustMap$1, "__esModule", { value: true });
exhaustMap$1.exhaustMap = void 0;
var map_1$2 = map$1;
var innerFrom_1$g = innerFrom$1;
var lift_1$D = lift;
var OperatorSubscriber_1$s = OperatorSubscriber$1;
function exhaustMap(project, resultSelector) {
    if (resultSelector) {
        return function (source) {
            return source.pipe(exhaustMap(function (a, i) { return innerFrom_1$g.innerFrom(project(a, i)).pipe(map_1$2.map(function (b, ii) { return resultSelector(a, b, i, ii); })); }));
        };
    }
    return lift_1$D.operate(function (source, subscriber) {
        var index = 0;
        var innerSub = null;
        var isComplete = false;
        source.subscribe(OperatorSubscriber_1$s.createOperatorSubscriber(subscriber, function (outerValue) {
            if (!innerSub) {
                innerSub = OperatorSubscriber_1$s.createOperatorSubscriber(subscriber, undefined, function () {
                    innerSub = null;
                    isComplete && subscriber.complete();
                });
                innerFrom_1$g.innerFrom(project(outerValue, index++)).subscribe(innerSub);
            }
        }, function () {
            isComplete = true;
            !innerSub && subscriber.complete();
        }));
    });
}
exhaustMap$1.exhaustMap = exhaustMap;

Object.defineProperty(exhaustAll$1, "__esModule", { value: true });
exhaustAll$1.exhaustAll = void 0;
var exhaustMap_1 = exhaustMap$1;
var identity_1$8 = identity$2;
function exhaustAll() {
    return exhaustMap_1.exhaustMap(identity_1$8.identity);
}
exhaustAll$1.exhaustAll = exhaustAll;

Object.defineProperty(exhaust, "__esModule", { value: true });
exhaust.exhaust = void 0;
var exhaustAll_1 = exhaustAll$1;
exhaust.exhaust = exhaustAll_1.exhaustAll;

var expand$1 = {};

Object.defineProperty(expand$1, "__esModule", { value: true });
expand$1.expand = void 0;
var lift_1$C = lift;
var mergeInternals_1$1 = mergeInternals$1;
function expand(project, concurrent, scheduler) {
    if (concurrent === void 0) { concurrent = Infinity; }
    concurrent = (concurrent || 0) < 1 ? Infinity : concurrent;
    return lift_1$C.operate(function (source, subscriber) {
        return mergeInternals_1$1.mergeInternals(source, subscriber, project, concurrent, undefined, true, scheduler);
    });
}
expand$1.expand = expand;

var finalize$1 = {};

Object.defineProperty(finalize$1, "__esModule", { value: true });
finalize$1.finalize = void 0;
var lift_1$B = lift;
function finalize(callback) {
    return lift_1$B.operate(function (source, subscriber) {
        try {
            source.subscribe(subscriber);
        }
        finally {
            subscriber.add(callback);
        }
    });
}
finalize$1.finalize = finalize;

var find$1 = {};

Object.defineProperty(find$1, "__esModule", { value: true });
find$1.createFind = find$1.find = void 0;
var lift_1$A = lift;
var OperatorSubscriber_1$r = OperatorSubscriber$1;
function find(predicate, thisArg) {
    return lift_1$A.operate(createFind(predicate, thisArg, 'value'));
}
find$1.find = find;
function createFind(predicate, thisArg, emit) {
    var findIndex = emit === 'index';
    return function (source, subscriber) {
        var index = 0;
        source.subscribe(OperatorSubscriber_1$r.createOperatorSubscriber(subscriber, function (value) {
            var i = index++;
            if (predicate.call(thisArg, value, i, source)) {
                subscriber.next(findIndex ? i : value);
                subscriber.complete();
            }
        }, function () {
            subscriber.next(findIndex ? -1 : undefined);
            subscriber.complete();
        }));
    };
}
find$1.createFind = createFind;

var findIndex$1 = {};

Object.defineProperty(findIndex$1, "__esModule", { value: true });
findIndex$1.findIndex = void 0;
var lift_1$z = lift;
var find_1 = find$1;
function findIndex(predicate, thisArg) {
    return lift_1$z.operate(find_1.createFind(predicate, thisArg, 'index'));
}
findIndex$1.findIndex = findIndex;

var first$1 = {};

Object.defineProperty(first$1, "__esModule", { value: true });
first$1.first = void 0;
var EmptyError_1$2 = EmptyError;
var filter_1$3 = filter$1;
var take_1 = take$1;
var defaultIfEmpty_1$1 = defaultIfEmpty$1;
var throwIfEmpty_1$1 = throwIfEmpty$1;
var identity_1$7 = identity$2;
function first(predicate, defaultValue) {
    var hasDefaultValue = arguments.length >= 2;
    return function (source) {
        return source.pipe(predicate ? filter_1$3.filter(function (v, i) { return predicate(v, i, source); }) : identity_1$7.identity, take_1.take(1), hasDefaultValue ? defaultIfEmpty_1$1.defaultIfEmpty(defaultValue) : throwIfEmpty_1$1.throwIfEmpty(function () { return new EmptyError_1$2.EmptyError(); }));
    };
}
first$1.first = first;

var groupBy$1 = {};

Object.defineProperty(groupBy$1, "__esModule", { value: true });
groupBy$1.groupBy = void 0;
var Observable_1 = Observable$1;
var innerFrom_1$f = innerFrom$1;
var Subject_1$9 = Subject$1;
var lift_1$y = lift;
var OperatorSubscriber_1$q = OperatorSubscriber$1;
function groupBy(keySelector, elementOrOptions, duration, connector) {
    return lift_1$y.operate(function (source, subscriber) {
        var element;
        if (!elementOrOptions || typeof elementOrOptions === 'function') {
            element = elementOrOptions;
        }
        else {
            (duration = elementOrOptions.duration, element = elementOrOptions.element, connector = elementOrOptions.connector);
        }
        var groups = new Map();
        var notify = function (cb) {
            groups.forEach(cb);
            cb(subscriber);
        };
        var handleError = function (err) { return notify(function (consumer) { return consumer.error(err); }); };
        var activeGroups = 0;
        var teardownAttempted = false;
        var groupBySourceSubscriber = new OperatorSubscriber_1$q.OperatorSubscriber(subscriber, function (value) {
            try {
                var key_1 = keySelector(value);
                var group_1 = groups.get(key_1);
                if (!group_1) {
                    groups.set(key_1, (group_1 = connector ? connector() : new Subject_1$9.Subject()));
                    var grouped = createGroupedObservable(key_1, group_1);
                    subscriber.next(grouped);
                    if (duration) {
                        var durationSubscriber_1 = OperatorSubscriber_1$q.createOperatorSubscriber(group_1, function () {
                            group_1.complete();
                            durationSubscriber_1 === null || durationSubscriber_1 === void 0 ? void 0 : durationSubscriber_1.unsubscribe();
                        }, undefined, undefined, function () { return groups.delete(key_1); });
                        groupBySourceSubscriber.add(innerFrom_1$f.innerFrom(duration(grouped)).subscribe(durationSubscriber_1));
                    }
                }
                group_1.next(element ? element(value) : value);
            }
            catch (err) {
                handleError(err);
            }
        }, function () { return notify(function (consumer) { return consumer.complete(); }); }, handleError, function () { return groups.clear(); }, function () {
            teardownAttempted = true;
            return activeGroups === 0;
        });
        source.subscribe(groupBySourceSubscriber);
        function createGroupedObservable(key, groupSubject) {
            var result = new Observable_1.Observable(function (groupSubscriber) {
                activeGroups++;
                var innerSub = groupSubject.subscribe(groupSubscriber);
                return function () {
                    innerSub.unsubscribe();
                    --activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();
                };
            });
            result.key = key;
            return result;
        }
    });
}
groupBy$1.groupBy = groupBy;

var isEmpty$1 = {};

Object.defineProperty(isEmpty$1, "__esModule", { value: true });
isEmpty$1.isEmpty = void 0;
var lift_1$x = lift;
var OperatorSubscriber_1$p = OperatorSubscriber$1;
function isEmpty() {
    return lift_1$x.operate(function (source, subscriber) {
        source.subscribe(OperatorSubscriber_1$p.createOperatorSubscriber(subscriber, function () {
            subscriber.next(false);
            subscriber.complete();
        }, function () {
            subscriber.next(true);
            subscriber.complete();
        }));
    });
}
isEmpty$1.isEmpty = isEmpty;

var last$1 = {};

var takeLast$1 = {};

var __values$4 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(takeLast$1, "__esModule", { value: true });
takeLast$1.takeLast = void 0;
var empty_1$1 = empty;
var lift_1$w = lift;
var OperatorSubscriber_1$o = OperatorSubscriber$1;
function takeLast(count) {
    return count <= 0
        ? function () { return empty_1$1.EMPTY; }
        : lift_1$w.operate(function (source, subscriber) {
            var buffer = [];
            source.subscribe(OperatorSubscriber_1$o.createOperatorSubscriber(subscriber, function (value) {
                buffer.push(value);
                count < buffer.length && buffer.shift();
            }, function () {
                var e_1, _a;
                try {
                    for (var buffer_1 = __values$4(buffer), buffer_1_1 = buffer_1.next(); !buffer_1_1.done; buffer_1_1 = buffer_1.next()) {
                        var value = buffer_1_1.value;
                        subscriber.next(value);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (buffer_1_1 && !buffer_1_1.done && (_a = buffer_1.return)) _a.call(buffer_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                subscriber.complete();
            }, undefined, function () {
                buffer = null;
            }));
        });
}
takeLast$1.takeLast = takeLast;

Object.defineProperty(last$1, "__esModule", { value: true });
last$1.last = void 0;
var EmptyError_1$1 = EmptyError;
var filter_1$2 = filter$1;
var takeLast_1 = takeLast$1;
var throwIfEmpty_1 = throwIfEmpty$1;
var defaultIfEmpty_1 = defaultIfEmpty$1;
var identity_1$6 = identity$2;
function last(predicate, defaultValue) {
    var hasDefaultValue = arguments.length >= 2;
    return function (source) {
        return source.pipe(predicate ? filter_1$2.filter(function (v, i) { return predicate(v, i, source); }) : identity_1$6.identity, takeLast_1.takeLast(1), hasDefaultValue ? defaultIfEmpty_1.defaultIfEmpty(defaultValue) : throwIfEmpty_1.throwIfEmpty(function () { return new EmptyError_1$1.EmptyError(); }));
    };
}
last$1.last = last;

var materialize$1 = {};

Object.defineProperty(materialize$1, "__esModule", { value: true });
materialize$1.materialize = void 0;
var Notification_1 = Notification;
var lift_1$v = lift;
var OperatorSubscriber_1$n = OperatorSubscriber$1;
function materialize() {
    return lift_1$v.operate(function (source, subscriber) {
        source.subscribe(OperatorSubscriber_1$n.createOperatorSubscriber(subscriber, function (value) {
            subscriber.next(Notification_1.Notification.createNext(value));
        }, function () {
            subscriber.next(Notification_1.Notification.createComplete());
            subscriber.complete();
        }, function (err) {
            subscriber.next(Notification_1.Notification.createError(err));
            subscriber.complete();
        }));
    });
}
materialize$1.materialize = materialize;

var max$1 = {};

Object.defineProperty(max$1, "__esModule", { value: true });
max$1.max = void 0;
var reduce_1$1 = reduce$1;
var isFunction_1$6 = isFunction$1;
function max(comparer) {
    return reduce_1$1.reduce(isFunction_1$6.isFunction(comparer) ? function (x, y) { return (comparer(x, y) > 0 ? x : y); } : function (x, y) { return (x > y ? x : y); });
}
max$1.max = max;

var flatMap = {};

Object.defineProperty(flatMap, "__esModule", { value: true });
flatMap.flatMap = void 0;
var mergeMap_1$1 = mergeMap$1;
flatMap.flatMap = mergeMap_1$1.mergeMap;

var mergeMapTo$1 = {};

Object.defineProperty(mergeMapTo$1, "__esModule", { value: true });
mergeMapTo$1.mergeMapTo = void 0;
var mergeMap_1 = mergeMap$1;
var isFunction_1$5 = isFunction$1;
function mergeMapTo(innerObservable, resultSelector, concurrent) {
    if (concurrent === void 0) { concurrent = Infinity; }
    if (isFunction_1$5.isFunction(resultSelector)) {
        return mergeMap_1.mergeMap(function () { return innerObservable; }, resultSelector, concurrent);
    }
    if (typeof resultSelector === 'number') {
        concurrent = resultSelector;
    }
    return mergeMap_1.mergeMap(function () { return innerObservable; }, concurrent);
}
mergeMapTo$1.mergeMapTo = mergeMapTo;

var mergeScan$1 = {};

Object.defineProperty(mergeScan$1, "__esModule", { value: true });
mergeScan$1.mergeScan = void 0;
var lift_1$u = lift;
var mergeInternals_1 = mergeInternals$1;
function mergeScan(accumulator, seed, concurrent) {
    if (concurrent === void 0) { concurrent = Infinity; }
    return lift_1$u.operate(function (source, subscriber) {
        var state = seed;
        return mergeInternals_1.mergeInternals(source, subscriber, function (value, index) { return accumulator(state, value, index); }, concurrent, function (value) {
            state = value;
        }, false, undefined, function () { return (state = null); });
    });
}
mergeScan$1.mergeScan = mergeScan;

var mergeWith$1 = {};

var merge$1 = {};

var __read$f = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$a = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(merge$1, "__esModule", { value: true });
merge$1.merge = void 0;
var lift_1$t = lift;
var mergeAll_1 = mergeAll$1;
var args_1$3 = args;
var from_1 = from$1;
function merge() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var scheduler = args_1$3.popScheduler(args);
    var concurrent = args_1$3.popNumber(args, Infinity);
    return lift_1$t.operate(function (source, subscriber) {
        mergeAll_1.mergeAll(concurrent)(from_1.from(__spreadArray$a([source], __read$f(args)), scheduler)).subscribe(subscriber);
    });
}
merge$1.merge = merge;

var __read$e = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$9 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(mergeWith$1, "__esModule", { value: true });
mergeWith$1.mergeWith = void 0;
var merge_1 = merge$1;
function mergeWith() {
    var otherSources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        otherSources[_i] = arguments[_i];
    }
    return merge_1.merge.apply(void 0, __spreadArray$9([], __read$e(otherSources)));
}
mergeWith$1.mergeWith = mergeWith;

var min$1 = {};

Object.defineProperty(min$1, "__esModule", { value: true });
min$1.min = void 0;
var reduce_1 = reduce$1;
var isFunction_1$4 = isFunction$1;
function min(comparer) {
    return reduce_1.reduce(isFunction_1$4.isFunction(comparer) ? function (x, y) { return (comparer(x, y) < 0 ? x : y); } : function (x, y) { return (x < y ? x : y); });
}
min$1.min = min;

var multicast$1 = {};

Object.defineProperty(multicast$1, "__esModule", { value: true });
multicast$1.multicast = void 0;
var ConnectableObservable_1$2 = ConnectableObservable$1;
var isFunction_1$3 = isFunction$1;
var connect_1$1 = connect$1;
function multicast(subjectOrSubjectFactory, selector) {
    var subjectFactory = isFunction_1$3.isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : function () { return subjectOrSubjectFactory; };
    if (isFunction_1$3.isFunction(selector)) {
        return connect_1$1.connect(selector, {
            connector: subjectFactory,
        });
    }
    return function (source) { return new ConnectableObservable_1$2.ConnectableObservable(source, subjectFactory); };
}
multicast$1.multicast = multicast;

var onErrorResumeNextWith$1 = {};

var __read$d = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$8 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(onErrorResumeNextWith$1, "__esModule", { value: true });
onErrorResumeNextWith$1.onErrorResumeNext = onErrorResumeNextWith$1.onErrorResumeNextWith = void 0;
var argsOrArgArray_1$1 = argsOrArgArray$1;
var onErrorResumeNext_1 = onErrorResumeNext$1;
function onErrorResumeNextWith() {
    var sources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        sources[_i] = arguments[_i];
    }
    var nextSources = argsOrArgArray_1$1.argsOrArgArray(sources);
    return function (source) { return onErrorResumeNext_1.onErrorResumeNext.apply(void 0, __spreadArray$8([source], __read$d(nextSources))); };
}
onErrorResumeNextWith$1.onErrorResumeNextWith = onErrorResumeNextWith;
onErrorResumeNextWith$1.onErrorResumeNext = onErrorResumeNextWith;

var pairwise$1 = {};

Object.defineProperty(pairwise$1, "__esModule", { value: true });
pairwise$1.pairwise = void 0;
var lift_1$s = lift;
var OperatorSubscriber_1$m = OperatorSubscriber$1;
function pairwise() {
    return lift_1$s.operate(function (source, subscriber) {
        var prev;
        var hasPrev = false;
        source.subscribe(OperatorSubscriber_1$m.createOperatorSubscriber(subscriber, function (value) {
            var p = prev;
            prev = value;
            hasPrev && subscriber.next([p, value]);
            hasPrev = true;
        }));
    });
}
pairwise$1.pairwise = pairwise;

var pluck$1 = {};

Object.defineProperty(pluck$1, "__esModule", { value: true });
pluck$1.pluck = void 0;
var map_1$1 = map$1;
function pluck() {
    var properties = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        properties[_i] = arguments[_i];
    }
    var length = properties.length;
    if (length === 0) {
        throw new Error('list of properties cannot be empty.');
    }
    return map_1$1.map(function (x) {
        var currentProp = x;
        for (var i = 0; i < length; i++) {
            var p = currentProp === null || currentProp === void 0 ? void 0 : currentProp[properties[i]];
            if (typeof p !== 'undefined') {
                currentProp = p;
            }
            else {
                return undefined;
            }
        }
        return currentProp;
    });
}
pluck$1.pluck = pluck;

var publish$1 = {};

Object.defineProperty(publish$1, "__esModule", { value: true });
publish$1.publish = void 0;
var Subject_1$8 = Subject$1;
var multicast_1$1 = multicast$1;
var connect_1 = connect$1;
function publish(selector) {
    return selector ? function (source) { return connect_1.connect(selector)(source); } : function (source) { return multicast_1$1.multicast(new Subject_1$8.Subject())(source); };
}
publish$1.publish = publish;

var publishBehavior$1 = {};

Object.defineProperty(publishBehavior$1, "__esModule", { value: true });
publishBehavior$1.publishBehavior = void 0;
var BehaviorSubject_1 = BehaviorSubject$1;
var ConnectableObservable_1$1 = ConnectableObservable$1;
function publishBehavior(initialValue) {
    return function (source) {
        var subject = new BehaviorSubject_1.BehaviorSubject(initialValue);
        return new ConnectableObservable_1$1.ConnectableObservable(source, function () { return subject; });
    };
}
publishBehavior$1.publishBehavior = publishBehavior;

var publishLast$1 = {};

Object.defineProperty(publishLast$1, "__esModule", { value: true });
publishLast$1.publishLast = void 0;
var AsyncSubject_1 = AsyncSubject$1;
var ConnectableObservable_1 = ConnectableObservable$1;
function publishLast() {
    return function (source) {
        var subject = new AsyncSubject_1.AsyncSubject();
        return new ConnectableObservable_1.ConnectableObservable(source, function () { return subject; });
    };
}
publishLast$1.publishLast = publishLast;

var publishReplay$1 = {};

Object.defineProperty(publishReplay$1, "__esModule", { value: true });
publishReplay$1.publishReplay = void 0;
var ReplaySubject_1$1 = ReplaySubject$1;
var multicast_1 = multicast$1;
var isFunction_1$2 = isFunction$1;
function publishReplay(bufferSize, windowTime, selectorOrScheduler, timestampProvider) {
    if (selectorOrScheduler && !isFunction_1$2.isFunction(selectorOrScheduler)) {
        timestampProvider = selectorOrScheduler;
    }
    var selector = isFunction_1$2.isFunction(selectorOrScheduler) ? selectorOrScheduler : undefined;
    return function (source) { return multicast_1.multicast(new ReplaySubject_1$1.ReplaySubject(bufferSize, windowTime, timestampProvider), selector)(source); };
}
publishReplay$1.publishReplay = publishReplay;

var raceWith$1 = {};

var __read$c = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$7 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(raceWith$1, "__esModule", { value: true });
raceWith$1.raceWith = void 0;
var race_1 = race$3;
var lift_1$r = lift;
var identity_1$5 = identity$2;
function raceWith() {
    var otherSources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        otherSources[_i] = arguments[_i];
    }
    return !otherSources.length
        ? identity_1$5.identity
        : lift_1$r.operate(function (source, subscriber) {
            race_1.raceInit(__spreadArray$7([source], __read$c(otherSources)))(subscriber);
        });
}
raceWith$1.raceWith = raceWith;

var repeat$1 = {};

Object.defineProperty(repeat$1, "__esModule", { value: true });
repeat$1.repeat = void 0;
var empty_1 = empty;
var lift_1$q = lift;
var OperatorSubscriber_1$l = OperatorSubscriber$1;
var innerFrom_1$e = innerFrom$1;
var timer_1$2 = timer$1;
function repeat(countOrConfig) {
    var _a;
    var count = Infinity;
    var delay;
    if (countOrConfig != null) {
        if (typeof countOrConfig === 'object') {
            (_a = countOrConfig.count, count = _a === void 0 ? Infinity : _a, delay = countOrConfig.delay);
        }
        else {
            count = countOrConfig;
        }
    }
    return count <= 0
        ? function () { return empty_1.EMPTY; }
        : lift_1$q.operate(function (source, subscriber) {
            var soFar = 0;
            var sourceSub;
            var resubscribe = function () {
                sourceSub === null || sourceSub === void 0 ? void 0 : sourceSub.unsubscribe();
                sourceSub = null;
                if (delay != null) {
                    var notifier = typeof delay === 'number' ? timer_1$2.timer(delay) : innerFrom_1$e.innerFrom(delay(soFar));
                    var notifierSubscriber_1 = OperatorSubscriber_1$l.createOperatorSubscriber(subscriber, function () {
                        notifierSubscriber_1.unsubscribe();
                        subscribeToSource();
                    });
                    notifier.subscribe(notifierSubscriber_1);
                }
                else {
                    subscribeToSource();
                }
            };
            var subscribeToSource = function () {
                var syncUnsub = false;
                sourceSub = source.subscribe(OperatorSubscriber_1$l.createOperatorSubscriber(subscriber, undefined, function () {
                    if (++soFar < count) {
                        if (sourceSub) {
                            resubscribe();
                        }
                        else {
                            syncUnsub = true;
                        }
                    }
                    else {
                        subscriber.complete();
                    }
                }));
                if (syncUnsub) {
                    resubscribe();
                }
            };
            subscribeToSource();
        });
}
repeat$1.repeat = repeat;

var repeatWhen$1 = {};

Object.defineProperty(repeatWhen$1, "__esModule", { value: true });
repeatWhen$1.repeatWhen = void 0;
var innerFrom_1$d = innerFrom$1;
var Subject_1$7 = Subject$1;
var lift_1$p = lift;
var OperatorSubscriber_1$k = OperatorSubscriber$1;
function repeatWhen(notifier) {
    return lift_1$p.operate(function (source, subscriber) {
        var innerSub;
        var syncResub = false;
        var completions$;
        var isNotifierComplete = false;
        var isMainComplete = false;
        var checkComplete = function () { return isMainComplete && isNotifierComplete && (subscriber.complete(), true); };
        var getCompletionSubject = function () {
            if (!completions$) {
                completions$ = new Subject_1$7.Subject();
                innerFrom_1$d.innerFrom(notifier(completions$)).subscribe(OperatorSubscriber_1$k.createOperatorSubscriber(subscriber, function () {
                    if (innerSub) {
                        subscribeForRepeatWhen();
                    }
                    else {
                        syncResub = true;
                    }
                }, function () {
                    isNotifierComplete = true;
                    checkComplete();
                }));
            }
            return completions$;
        };
        var subscribeForRepeatWhen = function () {
            isMainComplete = false;
            innerSub = source.subscribe(OperatorSubscriber_1$k.createOperatorSubscriber(subscriber, undefined, function () {
                isMainComplete = true;
                !checkComplete() && getCompletionSubject().next();
            }));
            if (syncResub) {
                innerSub.unsubscribe();
                innerSub = null;
                syncResub = false;
                subscribeForRepeatWhen();
            }
        };
        subscribeForRepeatWhen();
    });
}
repeatWhen$1.repeatWhen = repeatWhen;

var retry$1 = {};

Object.defineProperty(retry$1, "__esModule", { value: true });
retry$1.retry = void 0;
var lift_1$o = lift;
var OperatorSubscriber_1$j = OperatorSubscriber$1;
var identity_1$4 = identity$2;
var timer_1$1 = timer$1;
var innerFrom_1$c = innerFrom$1;
function retry(configOrCount) {
    if (configOrCount === void 0) { configOrCount = Infinity; }
    var config;
    if (configOrCount && typeof configOrCount === 'object') {
        config = configOrCount;
    }
    else {
        config = {
            count: configOrCount,
        };
    }
    var _a = config.count, count = _a === void 0 ? Infinity : _a, delay = config.delay, _b = config.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b;
    return count <= 0
        ? identity_1$4.identity
        : lift_1$o.operate(function (source, subscriber) {
            var soFar = 0;
            var innerSub;
            var subscribeForRetry = function () {
                var syncUnsub = false;
                innerSub = source.subscribe(OperatorSubscriber_1$j.createOperatorSubscriber(subscriber, function (value) {
                    if (resetOnSuccess) {
                        soFar = 0;
                    }
                    subscriber.next(value);
                }, undefined, function (err) {
                    if (soFar++ < count) {
                        var resub_1 = function () {
                            if (innerSub) {
                                innerSub.unsubscribe();
                                innerSub = null;
                                subscribeForRetry();
                            }
                            else {
                                syncUnsub = true;
                            }
                        };
                        if (delay != null) {
                            var notifier = typeof delay === 'number' ? timer_1$1.timer(delay) : innerFrom_1$c.innerFrom(delay(err, soFar));
                            var notifierSubscriber_1 = OperatorSubscriber_1$j.createOperatorSubscriber(subscriber, function () {
                                notifierSubscriber_1.unsubscribe();
                                resub_1();
                            }, function () {
                                subscriber.complete();
                            });
                            notifier.subscribe(notifierSubscriber_1);
                        }
                        else {
                            resub_1();
                        }
                    }
                    else {
                        subscriber.error(err);
                    }
                }));
                if (syncUnsub) {
                    innerSub.unsubscribe();
                    innerSub = null;
                    subscribeForRetry();
                }
            };
            subscribeForRetry();
        });
}
retry$1.retry = retry;

var retryWhen$1 = {};

Object.defineProperty(retryWhen$1, "__esModule", { value: true });
retryWhen$1.retryWhen = void 0;
var innerFrom_1$b = innerFrom$1;
var Subject_1$6 = Subject$1;
var lift_1$n = lift;
var OperatorSubscriber_1$i = OperatorSubscriber$1;
function retryWhen(notifier) {
    return lift_1$n.operate(function (source, subscriber) {
        var innerSub;
        var syncResub = false;
        var errors$;
        var subscribeForRetryWhen = function () {
            innerSub = source.subscribe(OperatorSubscriber_1$i.createOperatorSubscriber(subscriber, undefined, undefined, function (err) {
                if (!errors$) {
                    errors$ = new Subject_1$6.Subject();
                    innerFrom_1$b.innerFrom(notifier(errors$)).subscribe(OperatorSubscriber_1$i.createOperatorSubscriber(subscriber, function () {
                        return innerSub ? subscribeForRetryWhen() : (syncResub = true);
                    }));
                }
                if (errors$) {
                    errors$.next(err);
                }
            }));
            if (syncResub) {
                innerSub.unsubscribe();
                innerSub = null;
                syncResub = false;
                subscribeForRetryWhen();
            }
        };
        subscribeForRetryWhen();
    });
}
retryWhen$1.retryWhen = retryWhen;

var sample$1 = {};

Object.defineProperty(sample$1, "__esModule", { value: true });
sample$1.sample = void 0;
var innerFrom_1$a = innerFrom$1;
var lift_1$m = lift;
var noop_1$5 = noop$1;
var OperatorSubscriber_1$h = OperatorSubscriber$1;
function sample(notifier) {
    return lift_1$m.operate(function (source, subscriber) {
        var hasValue = false;
        var lastValue = null;
        source.subscribe(OperatorSubscriber_1$h.createOperatorSubscriber(subscriber, function (value) {
            hasValue = true;
            lastValue = value;
        }));
        innerFrom_1$a.innerFrom(notifier).subscribe(OperatorSubscriber_1$h.createOperatorSubscriber(subscriber, function () {
            if (hasValue) {
                hasValue = false;
                var value = lastValue;
                lastValue = null;
                subscriber.next(value);
            }
        }, noop_1$5.noop));
    });
}
sample$1.sample = sample;

var sampleTime$1 = {};

Object.defineProperty(sampleTime$1, "__esModule", { value: true });
sampleTime$1.sampleTime = void 0;
var async_1$4 = async;
var sample_1 = sample$1;
var interval_1 = interval$1;
function sampleTime(period, scheduler) {
    if (scheduler === void 0) { scheduler = async_1$4.asyncScheduler; }
    return sample_1.sample(interval_1.interval(period, scheduler));
}
sampleTime$1.sampleTime = sampleTime;

var scan$1 = {};

Object.defineProperty(scan$1, "__esModule", { value: true });
scan$1.scan = void 0;
var lift_1$l = lift;
var scanInternals_1 = scanInternals$1;
function scan(accumulator, seed) {
    return lift_1$l.operate(scanInternals_1.scanInternals(accumulator, seed, arguments.length >= 2, true));
}
scan$1.scan = scan;

var sequenceEqual$1 = {};

Object.defineProperty(sequenceEqual$1, "__esModule", { value: true });
sequenceEqual$1.sequenceEqual = void 0;
var lift_1$k = lift;
var OperatorSubscriber_1$g = OperatorSubscriber$1;
var innerFrom_1$9 = innerFrom$1;
function sequenceEqual(compareTo, comparator) {
    if (comparator === void 0) { comparator = function (a, b) { return a === b; }; }
    return lift_1$k.operate(function (source, subscriber) {
        var aState = createState();
        var bState = createState();
        var emit = function (isEqual) {
            subscriber.next(isEqual);
            subscriber.complete();
        };
        var createSubscriber = function (selfState, otherState) {
            var sequenceEqualSubscriber = OperatorSubscriber_1$g.createOperatorSubscriber(subscriber, function (a) {
                var buffer = otherState.buffer, complete = otherState.complete;
                if (buffer.length === 0) {
                    complete ? emit(false) : selfState.buffer.push(a);
                }
                else {
                    !comparator(a, buffer.shift()) && emit(false);
                }
            }, function () {
                selfState.complete = true;
                var complete = otherState.complete, buffer = otherState.buffer;
                complete && emit(buffer.length === 0);
                sequenceEqualSubscriber === null || sequenceEqualSubscriber === void 0 ? void 0 : sequenceEqualSubscriber.unsubscribe();
            });
            return sequenceEqualSubscriber;
        };
        source.subscribe(createSubscriber(aState, bState));
        innerFrom_1$9.innerFrom(compareTo).subscribe(createSubscriber(bState, aState));
    });
}
sequenceEqual$1.sequenceEqual = sequenceEqual;
function createState() {
    return {
        buffer: [],
        complete: false,
    };
}

var share$1 = {};

var __read$b = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$6 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(share$1, "__esModule", { value: true });
share$1.share = void 0;
var innerFrom_1$8 = innerFrom$1;
var Subject_1$5 = Subject$1;
var Subscriber_1 = Subscriber;
var lift_1$j = lift;
function share(options) {
    if (options === void 0) { options = {}; }
    var _a = options.connector, connector = _a === void 0 ? function () { return new Subject_1$5.Subject(); } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d;
    return function (wrapperSource) {
        var connection;
        var resetConnection;
        var subject;
        var refCount = 0;
        var hasCompleted = false;
        var hasErrored = false;
        var cancelReset = function () {
            resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();
            resetConnection = undefined;
        };
        var reset = function () {
            cancelReset();
            connection = subject = undefined;
            hasCompleted = hasErrored = false;
        };
        var resetAndUnsubscribe = function () {
            var conn = connection;
            reset();
            conn === null || conn === void 0 ? void 0 : conn.unsubscribe();
        };
        return lift_1$j.operate(function (source, subscriber) {
            refCount++;
            if (!hasErrored && !hasCompleted) {
                cancelReset();
            }
            var dest = (subject = subject !== null && subject !== void 0 ? subject : connector());
            subscriber.add(function () {
                refCount--;
                if (refCount === 0 && !hasErrored && !hasCompleted) {
                    resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);
                }
            });
            dest.subscribe(subscriber);
            if (!connection &&
                refCount > 0) {
                connection = new Subscriber_1.SafeSubscriber({
                    next: function (value) { return dest.next(value); },
                    error: function (err) {
                        hasErrored = true;
                        cancelReset();
                        resetConnection = handleReset(reset, resetOnError, err);
                        dest.error(err);
                    },
                    complete: function () {
                        hasCompleted = true;
                        cancelReset();
                        resetConnection = handleReset(reset, resetOnComplete);
                        dest.complete();
                    },
                });
                innerFrom_1$8.innerFrom(source).subscribe(connection);
            }
        })(wrapperSource);
    };
}
share$1.share = share;
function handleReset(reset, on) {
    var args = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        args[_i - 2] = arguments[_i];
    }
    if (on === true) {
        reset();
        return;
    }
    if (on === false) {
        return;
    }
    var onSubscriber = new Subscriber_1.SafeSubscriber({
        next: function () {
            onSubscriber.unsubscribe();
            reset();
        },
    });
    return innerFrom_1$8.innerFrom(on.apply(void 0, __spreadArray$6([], __read$b(args)))).subscribe(onSubscriber);
}

var shareReplay$1 = {};

Object.defineProperty(shareReplay$1, "__esModule", { value: true });
shareReplay$1.shareReplay = void 0;
var ReplaySubject_1 = ReplaySubject$1;
var share_1 = share$1;
function shareReplay(configOrBufferSize, windowTime, scheduler) {
    var _a, _b, _c;
    var bufferSize;
    var refCount = false;
    if (configOrBufferSize && typeof configOrBufferSize === 'object') {
        (_a = configOrBufferSize.bufferSize, bufferSize = _a === void 0 ? Infinity : _a, _b = configOrBufferSize.windowTime, windowTime = _b === void 0 ? Infinity : _b, _c = configOrBufferSize.refCount, refCount = _c === void 0 ? false : _c, scheduler = configOrBufferSize.scheduler);
    }
    else {
        bufferSize = (configOrBufferSize !== null && configOrBufferSize !== void 0 ? configOrBufferSize : Infinity);
    }
    return share_1.share({
        connector: function () { return new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler); },
        resetOnError: true,
        resetOnComplete: false,
        resetOnRefCountZero: refCount,
    });
}
shareReplay$1.shareReplay = shareReplay;

var single$1 = {};

Object.defineProperty(single$1, "__esModule", { value: true });
single$1.single = void 0;
var EmptyError_1 = EmptyError;
var SequenceError_1 = SequenceError;
var NotFoundError_1 = NotFoundError;
var lift_1$i = lift;
var OperatorSubscriber_1$f = OperatorSubscriber$1;
function single(predicate) {
    return lift_1$i.operate(function (source, subscriber) {
        var hasValue = false;
        var singleValue;
        var seenValue = false;
        var index = 0;
        source.subscribe(OperatorSubscriber_1$f.createOperatorSubscriber(subscriber, function (value) {
            seenValue = true;
            if (!predicate || predicate(value, index++, source)) {
                hasValue && subscriber.error(new SequenceError_1.SequenceError('Too many matching values'));
                hasValue = true;
                singleValue = value;
            }
        }, function () {
            if (hasValue) {
                subscriber.next(singleValue);
                subscriber.complete();
            }
            else {
                subscriber.error(seenValue ? new NotFoundError_1.NotFoundError('No matching values') : new EmptyError_1.EmptyError());
            }
        }));
    });
}
single$1.single = single;

var skip$1 = {};

Object.defineProperty(skip$1, "__esModule", { value: true });
skip$1.skip = void 0;
var filter_1$1 = filter$1;
function skip(count) {
    return filter_1$1.filter(function (_, index) { return count <= index; });
}
skip$1.skip = skip;

var skipLast$1 = {};

Object.defineProperty(skipLast$1, "__esModule", { value: true });
skipLast$1.skipLast = void 0;
var identity_1$3 = identity$2;
var lift_1$h = lift;
var OperatorSubscriber_1$e = OperatorSubscriber$1;
function skipLast(skipCount) {
    return skipCount <= 0
        ?
            identity_1$3.identity
        : lift_1$h.operate(function (source, subscriber) {
            var ring = new Array(skipCount);
            var seen = 0;
            source.subscribe(OperatorSubscriber_1$e.createOperatorSubscriber(subscriber, function (value) {
                var valueIndex = seen++;
                if (valueIndex < skipCount) {
                    ring[valueIndex] = value;
                }
                else {
                    var index = valueIndex % skipCount;
                    var oldValue = ring[index];
                    ring[index] = value;
                    subscriber.next(oldValue);
                }
            }));
            return function () {
                ring = null;
            };
        });
}
skipLast$1.skipLast = skipLast;

var skipUntil$1 = {};

Object.defineProperty(skipUntil$1, "__esModule", { value: true });
skipUntil$1.skipUntil = void 0;
var lift_1$g = lift;
var OperatorSubscriber_1$d = OperatorSubscriber$1;
var innerFrom_1$7 = innerFrom$1;
var noop_1$4 = noop$1;
function skipUntil(notifier) {
    return lift_1$g.operate(function (source, subscriber) {
        var taking = false;
        var skipSubscriber = OperatorSubscriber_1$d.createOperatorSubscriber(subscriber, function () {
            skipSubscriber === null || skipSubscriber === void 0 ? void 0 : skipSubscriber.unsubscribe();
            taking = true;
        }, noop_1$4.noop);
        innerFrom_1$7.innerFrom(notifier).subscribe(skipSubscriber);
        source.subscribe(OperatorSubscriber_1$d.createOperatorSubscriber(subscriber, function (value) { return taking && subscriber.next(value); }));
    });
}
skipUntil$1.skipUntil = skipUntil;

var skipWhile$1 = {};

Object.defineProperty(skipWhile$1, "__esModule", { value: true });
skipWhile$1.skipWhile = void 0;
var lift_1$f = lift;
var OperatorSubscriber_1$c = OperatorSubscriber$1;
function skipWhile(predicate) {
    return lift_1$f.operate(function (source, subscriber) {
        var taking = false;
        var index = 0;
        source.subscribe(OperatorSubscriber_1$c.createOperatorSubscriber(subscriber, function (value) { return (taking || (taking = !predicate(value, index++))) && subscriber.next(value); }));
    });
}
skipWhile$1.skipWhile = skipWhile;

var startWith$1 = {};

Object.defineProperty(startWith$1, "__esModule", { value: true });
startWith$1.startWith = void 0;
var concat_1 = concat$3;
var args_1$2 = args;
var lift_1$e = lift;
function startWith() {
    var values = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
    }
    var scheduler = args_1$2.popScheduler(values);
    return lift_1$e.operate(function (source, subscriber) {
        (scheduler ? concat_1.concat(values, source, scheduler) : concat_1.concat(values, source)).subscribe(subscriber);
    });
}
startWith$1.startWith = startWith;

var switchAll$1 = {};

var switchMap$1 = {};

Object.defineProperty(switchMap$1, "__esModule", { value: true });
switchMap$1.switchMap = void 0;
var innerFrom_1$6 = innerFrom$1;
var lift_1$d = lift;
var OperatorSubscriber_1$b = OperatorSubscriber$1;
function switchMap(project, resultSelector) {
    return lift_1$d.operate(function (source, subscriber) {
        var innerSubscriber = null;
        var index = 0;
        var isComplete = false;
        var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
        source.subscribe(OperatorSubscriber_1$b.createOperatorSubscriber(subscriber, function (value) {
            innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
            var innerIndex = 0;
            var outerIndex = index++;
            innerFrom_1$6.innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = OperatorSubscriber_1$b.createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
                innerSubscriber = null;
                checkComplete();
            })));
        }, function () {
            isComplete = true;
            checkComplete();
        }));
    });
}
switchMap$1.switchMap = switchMap;

Object.defineProperty(switchAll$1, "__esModule", { value: true });
switchAll$1.switchAll = void 0;
var switchMap_1$2 = switchMap$1;
var identity_1$2 = identity$2;
function switchAll() {
    return switchMap_1$2.switchMap(identity_1$2.identity);
}
switchAll$1.switchAll = switchAll;

var switchMapTo$1 = {};

Object.defineProperty(switchMapTo$1, "__esModule", { value: true });
switchMapTo$1.switchMapTo = void 0;
var switchMap_1$1 = switchMap$1;
var isFunction_1$1 = isFunction$1;
function switchMapTo(innerObservable, resultSelector) {
    return isFunction_1$1.isFunction(resultSelector) ? switchMap_1$1.switchMap(function () { return innerObservable; }, resultSelector) : switchMap_1$1.switchMap(function () { return innerObservable; });
}
switchMapTo$1.switchMapTo = switchMapTo;

var switchScan$1 = {};

Object.defineProperty(switchScan$1, "__esModule", { value: true });
switchScan$1.switchScan = void 0;
var switchMap_1 = switchMap$1;
var lift_1$c = lift;
function switchScan(accumulator, seed) {
    return lift_1$c.operate(function (source, subscriber) {
        var state = seed;
        switchMap_1.switchMap(function (value, index) { return accumulator(state, value, index); }, function (_, innerValue) { return ((state = innerValue), innerValue); })(source).subscribe(subscriber);
        return function () {
            state = null;
        };
    });
}
switchScan$1.switchScan = switchScan;

var takeUntil$1 = {};

Object.defineProperty(takeUntil$1, "__esModule", { value: true });
takeUntil$1.takeUntil = void 0;
var lift_1$b = lift;
var OperatorSubscriber_1$a = OperatorSubscriber$1;
var innerFrom_1$5 = innerFrom$1;
var noop_1$3 = noop$1;
function takeUntil(notifier) {
    return lift_1$b.operate(function (source, subscriber) {
        innerFrom_1$5.innerFrom(notifier).subscribe(OperatorSubscriber_1$a.createOperatorSubscriber(subscriber, function () { return subscriber.complete(); }, noop_1$3.noop));
        !subscriber.closed && source.subscribe(subscriber);
    });
}
takeUntil$1.takeUntil = takeUntil;

var takeWhile$1 = {};

Object.defineProperty(takeWhile$1, "__esModule", { value: true });
takeWhile$1.takeWhile = void 0;
var lift_1$a = lift;
var OperatorSubscriber_1$9 = OperatorSubscriber$1;
function takeWhile(predicate, inclusive) {
    if (inclusive === void 0) { inclusive = false; }
    return lift_1$a.operate(function (source, subscriber) {
        var index = 0;
        source.subscribe(OperatorSubscriber_1$9.createOperatorSubscriber(subscriber, function (value) {
            var result = predicate(value, index++);
            (result || inclusive) && subscriber.next(value);
            !result && subscriber.complete();
        }));
    });
}
takeWhile$1.takeWhile = takeWhile;

var tap$1 = {};

Object.defineProperty(tap$1, "__esModule", { value: true });
tap$1.tap = void 0;
var isFunction_1 = isFunction$1;
var lift_1$9 = lift;
var OperatorSubscriber_1$8 = OperatorSubscriber$1;
var identity_1$1 = identity$2;
function tap(observerOrNext, error, complete) {
    var tapObserver = isFunction_1.isFunction(observerOrNext) || error || complete
        ?
            { next: observerOrNext, error: error, complete: complete }
        : observerOrNext;
    return tapObserver
        ? lift_1$9.operate(function (source, subscriber) {
            var _a;
            (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
            var isUnsub = true;
            source.subscribe(OperatorSubscriber_1$8.createOperatorSubscriber(subscriber, function (value) {
                var _a;
                (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);
                subscriber.next(value);
            }, function () {
                var _a;
                isUnsub = false;
                (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
                subscriber.complete();
            }, function (err) {
                var _a;
                isUnsub = false;
                (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);
                subscriber.error(err);
            }, function () {
                var _a, _b;
                if (isUnsub) {
                    (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
                }
                (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
            }));
        })
        :
            identity_1$1.identity;
}
tap$1.tap = tap;

var throttle$1 = {};

Object.defineProperty(throttle$1, "__esModule", { value: true });
throttle$1.throttle = void 0;
var lift_1$8 = lift;
var OperatorSubscriber_1$7 = OperatorSubscriber$1;
var innerFrom_1$4 = innerFrom$1;
function throttle(durationSelector, config) {
    return lift_1$8.operate(function (source, subscriber) {
        var _a = config !== null && config !== void 0 ? config : {}, _b = _a.leading, leading = _b === void 0 ? true : _b, _c = _a.trailing, trailing = _c === void 0 ? false : _c;
        var hasValue = false;
        var sendValue = null;
        var throttled = null;
        var isComplete = false;
        var endThrottling = function () {
            throttled === null || throttled === void 0 ? void 0 : throttled.unsubscribe();
            throttled = null;
            if (trailing) {
                send();
                isComplete && subscriber.complete();
            }
        };
        var cleanupThrottling = function () {
            throttled = null;
            isComplete && subscriber.complete();
        };
        var startThrottle = function (value) {
            return (throttled = innerFrom_1$4.innerFrom(durationSelector(value)).subscribe(OperatorSubscriber_1$7.createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling)));
        };
        var send = function () {
            if (hasValue) {
                hasValue = false;
                var value = sendValue;
                sendValue = null;
                subscriber.next(value);
                !isComplete && startThrottle(value);
            }
        };
        source.subscribe(OperatorSubscriber_1$7.createOperatorSubscriber(subscriber, function (value) {
            hasValue = true;
            sendValue = value;
            !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));
        }, function () {
            isComplete = true;
            !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();
        }));
    });
}
throttle$1.throttle = throttle;

var throttleTime$1 = {};

Object.defineProperty(throttleTime$1, "__esModule", { value: true });
throttleTime$1.throttleTime = void 0;
var async_1$3 = async;
var throttle_1 = throttle$1;
var timer_1 = timer$1;
function throttleTime(duration, scheduler, config) {
    if (scheduler === void 0) { scheduler = async_1$3.asyncScheduler; }
    var duration$ = timer_1.timer(duration, scheduler);
    return throttle_1.throttle(function () { return duration$; }, config);
}
throttleTime$1.throttleTime = throttleTime;

var timeInterval$1 = {};

Object.defineProperty(timeInterval$1, "__esModule", { value: true });
timeInterval$1.TimeInterval = timeInterval$1.timeInterval = void 0;
var async_1$2 = async;
var lift_1$7 = lift;
var OperatorSubscriber_1$6 = OperatorSubscriber$1;
function timeInterval(scheduler) {
    if (scheduler === void 0) { scheduler = async_1$2.asyncScheduler; }
    return lift_1$7.operate(function (source, subscriber) {
        var last = scheduler.now();
        source.subscribe(OperatorSubscriber_1$6.createOperatorSubscriber(subscriber, function (value) {
            var now = scheduler.now();
            var interval = now - last;
            last = now;
            subscriber.next(new TimeInterval(value, interval));
        }));
    });
}
timeInterval$1.timeInterval = timeInterval;
var TimeInterval = (function () {
    function TimeInterval(value, interval) {
        this.value = value;
        this.interval = interval;
    }
    return TimeInterval;
}());
timeInterval$1.TimeInterval = TimeInterval;

var timeoutWith$1 = {};

Object.defineProperty(timeoutWith$1, "__esModule", { value: true });
timeoutWith$1.timeoutWith = void 0;
var async_1$1 = async;
var isDate_1 = isDate;
var timeout_1 = timeout;
function timeoutWith(due, withObservable, scheduler) {
    var first;
    var each;
    var _with;
    scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : async_1$1.async;
    if (isDate_1.isValidDate(due)) {
        first = due;
    }
    else if (typeof due === 'number') {
        each = due;
    }
    if (withObservable) {
        _with = function () { return withObservable; };
    }
    else {
        throw new TypeError('No observable provided to switch to');
    }
    if (first == null && each == null) {
        throw new TypeError('No timeout provided.');
    }
    return timeout_1.timeout({
        first: first,
        each: each,
        scheduler: scheduler,
        with: _with,
    });
}
timeoutWith$1.timeoutWith = timeoutWith;

var timestamp$1 = {};

Object.defineProperty(timestamp$1, "__esModule", { value: true });
timestamp$1.timestamp = void 0;
var dateTimestampProvider_1 = dateTimestampProvider;
var map_1 = map$1;
function timestamp(timestampProvider) {
    if (timestampProvider === void 0) { timestampProvider = dateTimestampProvider_1.dateTimestampProvider; }
    return map_1.map(function (value) { return ({ value: value, timestamp: timestampProvider.now() }); });
}
timestamp$1.timestamp = timestamp;

var window$2 = {};

Object.defineProperty(window$2, "__esModule", { value: true });
window$2.window = void 0;
var Subject_1$4 = Subject$1;
var lift_1$6 = lift;
var OperatorSubscriber_1$5 = OperatorSubscriber$1;
var noop_1$2 = noop$1;
var innerFrom_1$3 = innerFrom$1;
function window$1(windowBoundaries) {
    return lift_1$6.operate(function (source, subscriber) {
        var windowSubject = new Subject_1$4.Subject();
        subscriber.next(windowSubject.asObservable());
        var errorHandler = function (err) {
            windowSubject.error(err);
            subscriber.error(err);
        };
        source.subscribe(OperatorSubscriber_1$5.createOperatorSubscriber(subscriber, function (value) { return windowSubject === null || windowSubject === void 0 ? void 0 : windowSubject.next(value); }, function () {
            windowSubject.complete();
            subscriber.complete();
        }, errorHandler));
        innerFrom_1$3.innerFrom(windowBoundaries).subscribe(OperatorSubscriber_1$5.createOperatorSubscriber(subscriber, function () {
            windowSubject.complete();
            subscriber.next((windowSubject = new Subject_1$4.Subject()));
        }, noop_1$2.noop, errorHandler));
        return function () {
            windowSubject === null || windowSubject === void 0 ? void 0 : windowSubject.unsubscribe();
            windowSubject = null;
        };
    });
}
window$2.window = window$1;

var windowCount$1 = {};

var __values$3 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(windowCount$1, "__esModule", { value: true });
windowCount$1.windowCount = void 0;
var Subject_1$3 = Subject$1;
var lift_1$5 = lift;
var OperatorSubscriber_1$4 = OperatorSubscriber$1;
function windowCount(windowSize, startWindowEvery) {
    if (startWindowEvery === void 0) { startWindowEvery = 0; }
    var startEvery = startWindowEvery > 0 ? startWindowEvery : windowSize;
    return lift_1$5.operate(function (source, subscriber) {
        var windows = [new Subject_1$3.Subject()];
        var count = 0;
        subscriber.next(windows[0].asObservable());
        source.subscribe(OperatorSubscriber_1$4.createOperatorSubscriber(subscriber, function (value) {
            var e_1, _a;
            try {
                for (var windows_1 = __values$3(windows), windows_1_1 = windows_1.next(); !windows_1_1.done; windows_1_1 = windows_1.next()) {
                    var window_1 = windows_1_1.value;
                    window_1.next(value);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (windows_1_1 && !windows_1_1.done && (_a = windows_1.return)) _a.call(windows_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            var c = count - windowSize + 1;
            if (c >= 0 && c % startEvery === 0) {
                windows.shift().complete();
            }
            if (++count % startEvery === 0) {
                var window_2 = new Subject_1$3.Subject();
                windows.push(window_2);
                subscriber.next(window_2.asObservable());
            }
        }, function () {
            while (windows.length > 0) {
                windows.shift().complete();
            }
            subscriber.complete();
        }, function (err) {
            while (windows.length > 0) {
                windows.shift().error(err);
            }
            subscriber.error(err);
        }, function () {
            windows = null;
        }));
    });
}
windowCount$1.windowCount = windowCount;

var windowTime$1 = {};

Object.defineProperty(windowTime$1, "__esModule", { value: true });
windowTime$1.windowTime = void 0;
var Subject_1$2 = Subject$1;
var async_1 = async;
var Subscription_1$1 = Subscription$1;
var lift_1$4 = lift;
var OperatorSubscriber_1$3 = OperatorSubscriber$1;
var arrRemove_1$1 = arrRemove$1;
var args_1$1 = args;
var executeSchedule_1 = executeSchedule$1;
function windowTime(windowTimeSpan) {
    var _a, _b;
    var otherArgs = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        otherArgs[_i - 1] = arguments[_i];
    }
    var scheduler = (_a = args_1$1.popScheduler(otherArgs)) !== null && _a !== void 0 ? _a : async_1.asyncScheduler;
    var windowCreationInterval = (_b = otherArgs[0]) !== null && _b !== void 0 ? _b : null;
    var maxWindowSize = otherArgs[1] || Infinity;
    return lift_1$4.operate(function (source, subscriber) {
        var windowRecords = [];
        var restartOnClose = false;
        var closeWindow = function (record) {
            var window = record.window, subs = record.subs;
            window.complete();
            subs.unsubscribe();
            arrRemove_1$1.arrRemove(windowRecords, record);
            restartOnClose && startWindow();
        };
        var startWindow = function () {
            if (windowRecords) {
                var subs = new Subscription_1$1.Subscription();
                subscriber.add(subs);
                var window_1 = new Subject_1$2.Subject();
                var record_1 = {
                    window: window_1,
                    subs: subs,
                    seen: 0,
                };
                windowRecords.push(record_1);
                subscriber.next(window_1.asObservable());
                executeSchedule_1.executeSchedule(subs, scheduler, function () { return closeWindow(record_1); }, windowTimeSpan);
            }
        };
        if (windowCreationInterval !== null && windowCreationInterval >= 0) {
            executeSchedule_1.executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);
        }
        else {
            restartOnClose = true;
        }
        startWindow();
        var loop = function (cb) { return windowRecords.slice().forEach(cb); };
        var terminate = function (cb) {
            loop(function (_a) {
                var window = _a.window;
                return cb(window);
            });
            cb(subscriber);
            subscriber.unsubscribe();
        };
        source.subscribe(OperatorSubscriber_1$3.createOperatorSubscriber(subscriber, function (value) {
            loop(function (record) {
                record.window.next(value);
                maxWindowSize <= ++record.seen && closeWindow(record);
            });
        }, function () { return terminate(function (consumer) { return consumer.complete(); }); }, function (err) { return terminate(function (consumer) { return consumer.error(err); }); }));
        return function () {
            windowRecords = null;
        };
    });
}
windowTime$1.windowTime = windowTime;

var windowToggle$1 = {};

var __values$2 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(windowToggle$1, "__esModule", { value: true });
windowToggle$1.windowToggle = void 0;
var Subject_1$1 = Subject$1;
var Subscription_1 = Subscription$1;
var lift_1$3 = lift;
var innerFrom_1$2 = innerFrom$1;
var OperatorSubscriber_1$2 = OperatorSubscriber$1;
var noop_1$1 = noop$1;
var arrRemove_1 = arrRemove$1;
function windowToggle(openings, closingSelector) {
    return lift_1$3.operate(function (source, subscriber) {
        var windows = [];
        var handleError = function (err) {
            while (0 < windows.length) {
                windows.shift().error(err);
            }
            subscriber.error(err);
        };
        innerFrom_1$2.innerFrom(openings).subscribe(OperatorSubscriber_1$2.createOperatorSubscriber(subscriber, function (openValue) {
            var window = new Subject_1$1.Subject();
            windows.push(window);
            var closingSubscription = new Subscription_1.Subscription();
            var closeWindow = function () {
                arrRemove_1.arrRemove(windows, window);
                window.complete();
                closingSubscription.unsubscribe();
            };
            var closingNotifier;
            try {
                closingNotifier = innerFrom_1$2.innerFrom(closingSelector(openValue));
            }
            catch (err) {
                handleError(err);
                return;
            }
            subscriber.next(window.asObservable());
            closingSubscription.add(closingNotifier.subscribe(OperatorSubscriber_1$2.createOperatorSubscriber(subscriber, closeWindow, noop_1$1.noop, handleError)));
        }, noop_1$1.noop));
        source.subscribe(OperatorSubscriber_1$2.createOperatorSubscriber(subscriber, function (value) {
            var e_1, _a;
            var windowsCopy = windows.slice();
            try {
                for (var windowsCopy_1 = __values$2(windowsCopy), windowsCopy_1_1 = windowsCopy_1.next(); !windowsCopy_1_1.done; windowsCopy_1_1 = windowsCopy_1.next()) {
                    var window_1 = windowsCopy_1_1.value;
                    window_1.next(value);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (windowsCopy_1_1 && !windowsCopy_1_1.done && (_a = windowsCopy_1.return)) _a.call(windowsCopy_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }, function () {
            while (0 < windows.length) {
                windows.shift().complete();
            }
            subscriber.complete();
        }, handleError, function () {
            while (0 < windows.length) {
                windows.shift().unsubscribe();
            }
        }));
    });
}
windowToggle$1.windowToggle = windowToggle;

var windowWhen$1 = {};

Object.defineProperty(windowWhen$1, "__esModule", { value: true });
windowWhen$1.windowWhen = void 0;
var Subject_1 = Subject$1;
var lift_1$2 = lift;
var OperatorSubscriber_1$1 = OperatorSubscriber$1;
var innerFrom_1$1 = innerFrom$1;
function windowWhen(closingSelector) {
    return lift_1$2.operate(function (source, subscriber) {
        var window;
        var closingSubscriber;
        var handleError = function (err) {
            window.error(err);
            subscriber.error(err);
        };
        var openWindow = function () {
            closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
            window === null || window === void 0 ? void 0 : window.complete();
            window = new Subject_1.Subject();
            subscriber.next(window.asObservable());
            var closingNotifier;
            try {
                closingNotifier = innerFrom_1$1.innerFrom(closingSelector());
            }
            catch (err) {
                handleError(err);
                return;
            }
            closingNotifier.subscribe((closingSubscriber = OperatorSubscriber_1$1.createOperatorSubscriber(subscriber, openWindow, openWindow, handleError)));
        };
        openWindow();
        source.subscribe(OperatorSubscriber_1$1.createOperatorSubscriber(subscriber, function (value) { return window.next(value); }, function () {
            window.complete();
            subscriber.complete();
        }, handleError, function () {
            closingSubscriber === null || closingSubscriber === void 0 ? void 0 : closingSubscriber.unsubscribe();
            window = null;
        }));
    });
}
windowWhen$1.windowWhen = windowWhen;

var withLatestFrom$1 = {};

var __read$a = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$5 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(withLatestFrom$1, "__esModule", { value: true });
withLatestFrom$1.withLatestFrom = void 0;
var lift_1$1 = lift;
var OperatorSubscriber_1 = OperatorSubscriber$1;
var innerFrom_1 = innerFrom$1;
var identity_1 = identity$2;
var noop_1 = noop$1;
var args_1 = args;
function withLatestFrom() {
    var inputs = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        inputs[_i] = arguments[_i];
    }
    var project = args_1.popResultSelector(inputs);
    return lift_1$1.operate(function (source, subscriber) {
        var len = inputs.length;
        var otherValues = new Array(len);
        var hasValue = inputs.map(function () { return false; });
        var ready = false;
        var _loop_1 = function (i) {
            innerFrom_1.innerFrom(inputs[i]).subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
                otherValues[i] = value;
                if (!ready && !hasValue[i]) {
                    hasValue[i] = true;
                    (ready = hasValue.every(identity_1.identity)) && (hasValue = null);
                }
            }, noop_1.noop));
        };
        for (var i = 0; i < len; i++) {
            _loop_1(i);
        }
        source.subscribe(OperatorSubscriber_1.createOperatorSubscriber(subscriber, function (value) {
            if (ready) {
                var values = __spreadArray$5([value], __read$a(otherValues));
                subscriber.next(project ? project.apply(void 0, __spreadArray$5([], __read$a(values))) : values);
            }
        }));
    });
}
withLatestFrom$1.withLatestFrom = withLatestFrom;

var zipAll$1 = {};

Object.defineProperty(zipAll$1, "__esModule", { value: true });
zipAll$1.zipAll = void 0;
var zip_1$2 = zip$3;
var joinAllInternals_1 = joinAllInternals$1;
function zipAll(project) {
    return joinAllInternals_1.joinAllInternals(zip_1$2.zip, project);
}
zipAll$1.zipAll = zipAll;

var zipWith$1 = {};

var zip$1 = {};

var __read$9 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$4 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(zip$1, "__esModule", { value: true });
zip$1.zip = void 0;
var zip_1$1 = zip$3;
var lift_1 = lift;
function zip() {
    var sources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        sources[_i] = arguments[_i];
    }
    return lift_1.operate(function (source, subscriber) {
        zip_1$1.zip.apply(void 0, __spreadArray$4([source], __read$9(sources))).subscribe(subscriber);
    });
}
zip$1.zip = zip;

var __read$8 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$3 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(zipWith$1, "__esModule", { value: true });
zipWith$1.zipWith = void 0;
var zip_1 = zip$1;
function zipWith() {
    var otherInputs = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        otherInputs[_i] = arguments[_i];
    }
    return zip_1.zip.apply(void 0, __spreadArray$3([], __read$8(otherInputs)));
}
zipWith$1.zipWith = zipWith;

(function (exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.interval = exports.iif = exports.generate = exports.fromEventPattern = exports.fromEvent = exports.from = exports.forkJoin = exports.empty = exports.defer = exports.connectable = exports.concat = exports.combineLatest = exports.bindNodeCallback = exports.bindCallback = exports.UnsubscriptionError = exports.TimeoutError = exports.SequenceError = exports.ObjectUnsubscribedError = exports.NotFoundError = exports.EmptyError = exports.ArgumentOutOfRangeError = exports.firstValueFrom = exports.lastValueFrom = exports.isObservable = exports.identity = exports.noop = exports.pipe = exports.NotificationKind = exports.Notification = exports.Subscriber = exports.Subscription = exports.Scheduler = exports.VirtualAction = exports.VirtualTimeScheduler = exports.animationFrameScheduler = exports.animationFrame = exports.queueScheduler = exports.queue = exports.asyncScheduler = exports.async = exports.asapScheduler = exports.asap = exports.AsyncSubject = exports.ReplaySubject = exports.BehaviorSubject = exports.Subject = exports.animationFrames = exports.observable = exports.ConnectableObservable = exports.Observable = void 0;
exports.filter = exports.expand = exports.exhaustMap = exports.exhaustAll = exports.exhaust = exports.every = exports.endWith = exports.elementAt = exports.distinctUntilKeyChanged = exports.distinctUntilChanged = exports.distinct = exports.dematerialize = exports.delayWhen = exports.delay = exports.defaultIfEmpty = exports.debounceTime = exports.debounce = exports.count = exports.connect = exports.concatWith = exports.concatMapTo = exports.concatMap = exports.concatAll = exports.combineLatestWith = exports.combineLatestAll = exports.combineAll = exports.catchError = exports.bufferWhen = exports.bufferToggle = exports.bufferTime = exports.bufferCount = exports.buffer = exports.auditTime = exports.audit = exports.config = exports.NEVER = exports.EMPTY = exports.scheduled = exports.zip = exports.using = exports.timer = exports.throwError = exports.range = exports.race = exports.partition = exports.pairs = exports.onErrorResumeNext = exports.of = exports.never = exports.merge = void 0;
exports.switchMap = exports.switchAll = exports.subscribeOn = exports.startWith = exports.skipWhile = exports.skipUntil = exports.skipLast = exports.skip = exports.single = exports.shareReplay = exports.share = exports.sequenceEqual = exports.scan = exports.sampleTime = exports.sample = exports.refCount = exports.retryWhen = exports.retry = exports.repeatWhen = exports.repeat = exports.reduce = exports.raceWith = exports.publishReplay = exports.publishLast = exports.publishBehavior = exports.publish = exports.pluck = exports.pairwise = exports.onErrorResumeNextWith = exports.observeOn = exports.multicast = exports.min = exports.mergeWith = exports.mergeScan = exports.mergeMapTo = exports.mergeMap = exports.flatMap = exports.mergeAll = exports.max = exports.materialize = exports.mapTo = exports.map = exports.last = exports.isEmpty = exports.ignoreElements = exports.groupBy = exports.first = exports.findIndex = exports.find = exports.finalize = void 0;
exports.zipWith = exports.zipAll = exports.withLatestFrom = exports.windowWhen = exports.windowToggle = exports.windowTime = exports.windowCount = exports.window = exports.toArray = exports.timestamp = exports.timeoutWith = exports.timeout = exports.timeInterval = exports.throwIfEmpty = exports.throttleTime = exports.throttle = exports.tap = exports.takeWhile = exports.takeUntil = exports.takeLast = exports.take = exports.switchScan = exports.switchMapTo = void 0;
var Observable_1 = Observable$1;
Object.defineProperty(exports, "Observable", { enumerable: true, get: function () { return Observable_1.Observable; } });
var ConnectableObservable_1 = ConnectableObservable$1;
Object.defineProperty(exports, "ConnectableObservable", { enumerable: true, get: function () { return ConnectableObservable_1.ConnectableObservable; } });
var observable_1 = observable;
Object.defineProperty(exports, "observable", { enumerable: true, get: function () { return observable_1.observable; } });
var animationFrames_1 = animationFrames$1;
Object.defineProperty(exports, "animationFrames", { enumerable: true, get: function () { return animationFrames_1.animationFrames; } });
var Subject_1 = Subject$1;
Object.defineProperty(exports, "Subject", { enumerable: true, get: function () { return Subject_1.Subject; } });
var BehaviorSubject_1 = BehaviorSubject$1;
Object.defineProperty(exports, "BehaviorSubject", { enumerable: true, get: function () { return BehaviorSubject_1.BehaviorSubject; } });
var ReplaySubject_1 = ReplaySubject$1;
Object.defineProperty(exports, "ReplaySubject", { enumerable: true, get: function () { return ReplaySubject_1.ReplaySubject; } });
var AsyncSubject_1 = AsyncSubject$1;
Object.defineProperty(exports, "AsyncSubject", { enumerable: true, get: function () { return AsyncSubject_1.AsyncSubject; } });
var asap_1 = asap;
Object.defineProperty(exports, "asap", { enumerable: true, get: function () { return asap_1.asap; } });
Object.defineProperty(exports, "asapScheduler", { enumerable: true, get: function () { return asap_1.asapScheduler; } });
var async_1 = async;
Object.defineProperty(exports, "async", { enumerable: true, get: function () { return async_1.async; } });
Object.defineProperty(exports, "asyncScheduler", { enumerable: true, get: function () { return async_1.asyncScheduler; } });
var queue_1 = queue;
Object.defineProperty(exports, "queue", { enumerable: true, get: function () { return queue_1.queue; } });
Object.defineProperty(exports, "queueScheduler", { enumerable: true, get: function () { return queue_1.queueScheduler; } });
var animationFrame_1 = animationFrame;
Object.defineProperty(exports, "animationFrame", { enumerable: true, get: function () { return animationFrame_1.animationFrame; } });
Object.defineProperty(exports, "animationFrameScheduler", { enumerable: true, get: function () { return animationFrame_1.animationFrameScheduler; } });
var VirtualTimeScheduler_1 = VirtualTimeScheduler$1;
Object.defineProperty(exports, "VirtualTimeScheduler", { enumerable: true, get: function () { return VirtualTimeScheduler_1.VirtualTimeScheduler; } });
Object.defineProperty(exports, "VirtualAction", { enumerable: true, get: function () { return VirtualTimeScheduler_1.VirtualAction; } });
var Scheduler_1 = Scheduler$1;
Object.defineProperty(exports, "Scheduler", { enumerable: true, get: function () { return Scheduler_1.Scheduler; } });
var Subscription_1 = Subscription$1;
Object.defineProperty(exports, "Subscription", { enumerable: true, get: function () { return Subscription_1.Subscription; } });
var Subscriber_1 = Subscriber;
Object.defineProperty(exports, "Subscriber", { enumerable: true, get: function () { return Subscriber_1.Subscriber; } });
var Notification_1 = Notification;
Object.defineProperty(exports, "Notification", { enumerable: true, get: function () { return Notification_1.Notification; } });
Object.defineProperty(exports, "NotificationKind", { enumerable: true, get: function () { return Notification_1.NotificationKind; } });
var pipe_1 = pipe$1;
Object.defineProperty(exports, "pipe", { enumerable: true, get: function () { return pipe_1.pipe; } });
var noop_1 = noop$1;
Object.defineProperty(exports, "noop", { enumerable: true, get: function () { return noop_1.noop; } });
var identity_1 = identity$2;
Object.defineProperty(exports, "identity", { enumerable: true, get: function () { return identity_1.identity; } });
var isObservable_1 = isObservable$1;
Object.defineProperty(exports, "isObservable", { enumerable: true, get: function () { return isObservable_1.isObservable; } });
var lastValueFrom_1 = lastValueFrom$1;
Object.defineProperty(exports, "lastValueFrom", { enumerable: true, get: function () { return lastValueFrom_1.lastValueFrom; } });
var firstValueFrom_1 = firstValueFrom$1;
Object.defineProperty(exports, "firstValueFrom", { enumerable: true, get: function () { return firstValueFrom_1.firstValueFrom; } });
var ArgumentOutOfRangeError_1 = ArgumentOutOfRangeError;
Object.defineProperty(exports, "ArgumentOutOfRangeError", { enumerable: true, get: function () { return ArgumentOutOfRangeError_1.ArgumentOutOfRangeError; } });
var EmptyError_1 = EmptyError;
Object.defineProperty(exports, "EmptyError", { enumerable: true, get: function () { return EmptyError_1.EmptyError; } });
var NotFoundError_1 = NotFoundError;
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return NotFoundError_1.NotFoundError; } });
var ObjectUnsubscribedError_1 = ObjectUnsubscribedError;
Object.defineProperty(exports, "ObjectUnsubscribedError", { enumerable: true, get: function () { return ObjectUnsubscribedError_1.ObjectUnsubscribedError; } });
var SequenceError_1 = SequenceError;
Object.defineProperty(exports, "SequenceError", { enumerable: true, get: function () { return SequenceError_1.SequenceError; } });
var timeout_1 = timeout;
Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return timeout_1.TimeoutError; } });
var UnsubscriptionError_1 = UnsubscriptionError;
Object.defineProperty(exports, "UnsubscriptionError", { enumerable: true, get: function () { return UnsubscriptionError_1.UnsubscriptionError; } });
var bindCallback_1 = bindCallback$1;
Object.defineProperty(exports, "bindCallback", { enumerable: true, get: function () { return bindCallback_1.bindCallback; } });
var bindNodeCallback_1 = bindNodeCallback$1;
Object.defineProperty(exports, "bindNodeCallback", { enumerable: true, get: function () { return bindNodeCallback_1.bindNodeCallback; } });
var combineLatest_1 = combineLatest$3;
Object.defineProperty(exports, "combineLatest", { enumerable: true, get: function () { return combineLatest_1.combineLatest; } });
var concat_1 = concat$3;
Object.defineProperty(exports, "concat", { enumerable: true, get: function () { return concat_1.concat; } });
var connectable_1 = connectable$1;
Object.defineProperty(exports, "connectable", { enumerable: true, get: function () { return connectable_1.connectable; } });
var defer_1 = defer$1;
Object.defineProperty(exports, "defer", { enumerable: true, get: function () { return defer_1.defer; } });
var empty_1 = empty;
Object.defineProperty(exports, "empty", { enumerable: true, get: function () { return empty_1.empty; } });
var forkJoin_1 = forkJoin$1;
Object.defineProperty(exports, "forkJoin", { enumerable: true, get: function () { return forkJoin_1.forkJoin; } });
var from_1 = from$1;
Object.defineProperty(exports, "from", { enumerable: true, get: function () { return from_1.from; } });
var fromEvent_1 = fromEvent$1;
Object.defineProperty(exports, "fromEvent", { enumerable: true, get: function () { return fromEvent_1.fromEvent; } });
var fromEventPattern_1 = fromEventPattern$1;
Object.defineProperty(exports, "fromEventPattern", { enumerable: true, get: function () { return fromEventPattern_1.fromEventPattern; } });
var generate_1 = generate$1;
Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return generate_1.generate; } });
var iif_1 = iif$1;
Object.defineProperty(exports, "iif", { enumerable: true, get: function () { return iif_1.iif; } });
var interval_1 = interval$1;
Object.defineProperty(exports, "interval", { enumerable: true, get: function () { return interval_1.interval; } });
var merge_1 = merge$3;
Object.defineProperty(exports, "merge", { enumerable: true, get: function () { return merge_1.merge; } });
var never_1 = never;
Object.defineProperty(exports, "never", { enumerable: true, get: function () { return never_1.never; } });
var of_1 = of$1;
Object.defineProperty(exports, "of", { enumerable: true, get: function () { return of_1.of; } });
var onErrorResumeNext_1 = onErrorResumeNext$1;
Object.defineProperty(exports, "onErrorResumeNext", { enumerable: true, get: function () { return onErrorResumeNext_1.onErrorResumeNext; } });
var pairs_1 = pairs$1;
Object.defineProperty(exports, "pairs", { enumerable: true, get: function () { return pairs_1.pairs; } });
var partition_1 = partition$3;
Object.defineProperty(exports, "partition", { enumerable: true, get: function () { return partition_1.partition; } });
var race_1 = race$3;
Object.defineProperty(exports, "race", { enumerable: true, get: function () { return race_1.race; } });
var range_1 = range$1;
Object.defineProperty(exports, "range", { enumerable: true, get: function () { return range_1.range; } });
var throwError_1 = throwError$1;
Object.defineProperty(exports, "throwError", { enumerable: true, get: function () { return throwError_1.throwError; } });
var timer_1 = timer$1;
Object.defineProperty(exports, "timer", { enumerable: true, get: function () { return timer_1.timer; } });
var using_1 = using$1;
Object.defineProperty(exports, "using", { enumerable: true, get: function () { return using_1.using; } });
var zip_1 = zip$3;
Object.defineProperty(exports, "zip", { enumerable: true, get: function () { return zip_1.zip; } });
var scheduled_1 = scheduled$1;
Object.defineProperty(exports, "scheduled", { enumerable: true, get: function () { return scheduled_1.scheduled; } });
var empty_2 = empty;
Object.defineProperty(exports, "EMPTY", { enumerable: true, get: function () { return empty_2.EMPTY; } });
var never_2 = never;
Object.defineProperty(exports, "NEVER", { enumerable: true, get: function () { return never_2.NEVER; } });
__exportStar(types, exports);
var config_1 = config;
Object.defineProperty(exports, "config", { enumerable: true, get: function () { return config_1.config; } });
var audit_1 = audit$1;
Object.defineProperty(exports, "audit", { enumerable: true, get: function () { return audit_1.audit; } });
var auditTime_1 = auditTime$1;
Object.defineProperty(exports, "auditTime", { enumerable: true, get: function () { return auditTime_1.auditTime; } });
var buffer_1 = buffer$2;
Object.defineProperty(exports, "buffer", { enumerable: true, get: function () { return buffer_1.buffer; } });
var bufferCount_1 = bufferCount$1;
Object.defineProperty(exports, "bufferCount", { enumerable: true, get: function () { return bufferCount_1.bufferCount; } });
var bufferTime_1 = bufferTime$1;
Object.defineProperty(exports, "bufferTime", { enumerable: true, get: function () { return bufferTime_1.bufferTime; } });
var bufferToggle_1 = bufferToggle$1;
Object.defineProperty(exports, "bufferToggle", { enumerable: true, get: function () { return bufferToggle_1.bufferToggle; } });
var bufferWhen_1 = bufferWhen$1;
Object.defineProperty(exports, "bufferWhen", { enumerable: true, get: function () { return bufferWhen_1.bufferWhen; } });
var catchError_1 = catchError$1;
Object.defineProperty(exports, "catchError", { enumerable: true, get: function () { return catchError_1.catchError; } });
var combineAll_1 = combineAll;
Object.defineProperty(exports, "combineAll", { enumerable: true, get: function () { return combineAll_1.combineAll; } });
var combineLatestAll_1 = combineLatestAll$1;
Object.defineProperty(exports, "combineLatestAll", { enumerable: true, get: function () { return combineLatestAll_1.combineLatestAll; } });
var combineLatestWith_1 = combineLatestWith$1;
Object.defineProperty(exports, "combineLatestWith", { enumerable: true, get: function () { return combineLatestWith_1.combineLatestWith; } });
var concatAll_1 = concatAll$1;
Object.defineProperty(exports, "concatAll", { enumerable: true, get: function () { return concatAll_1.concatAll; } });
var concatMap_1 = concatMap$1;
Object.defineProperty(exports, "concatMap", { enumerable: true, get: function () { return concatMap_1.concatMap; } });
var concatMapTo_1 = concatMapTo$1;
Object.defineProperty(exports, "concatMapTo", { enumerable: true, get: function () { return concatMapTo_1.concatMapTo; } });
var concatWith_1 = concatWith$1;
Object.defineProperty(exports, "concatWith", { enumerable: true, get: function () { return concatWith_1.concatWith; } });
var connect_1 = connect$1;
Object.defineProperty(exports, "connect", { enumerable: true, get: function () { return connect_1.connect; } });
var count_1 = count$1;
Object.defineProperty(exports, "count", { enumerable: true, get: function () { return count_1.count; } });
var debounce_1 = debounce$1;
Object.defineProperty(exports, "debounce", { enumerable: true, get: function () { return debounce_1.debounce; } });
var debounceTime_1 = debounceTime$1;
Object.defineProperty(exports, "debounceTime", { enumerable: true, get: function () { return debounceTime_1.debounceTime; } });
var defaultIfEmpty_1 = defaultIfEmpty$1;
Object.defineProperty(exports, "defaultIfEmpty", { enumerable: true, get: function () { return defaultIfEmpty_1.defaultIfEmpty; } });
var delay_1 = delay$1;
Object.defineProperty(exports, "delay", { enumerable: true, get: function () { return delay_1.delay; } });
var delayWhen_1 = delayWhen$1;
Object.defineProperty(exports, "delayWhen", { enumerable: true, get: function () { return delayWhen_1.delayWhen; } });
var dematerialize_1 = dematerialize$1;
Object.defineProperty(exports, "dematerialize", { enumerable: true, get: function () { return dematerialize_1.dematerialize; } });
var distinct_1 = distinct$1;
Object.defineProperty(exports, "distinct", { enumerable: true, get: function () { return distinct_1.distinct; } });
var distinctUntilChanged_1 = distinctUntilChanged$1;
Object.defineProperty(exports, "distinctUntilChanged", { enumerable: true, get: function () { return distinctUntilChanged_1.distinctUntilChanged; } });
var distinctUntilKeyChanged_1 = distinctUntilKeyChanged$1;
Object.defineProperty(exports, "distinctUntilKeyChanged", { enumerable: true, get: function () { return distinctUntilKeyChanged_1.distinctUntilKeyChanged; } });
var elementAt_1 = elementAt$1;
Object.defineProperty(exports, "elementAt", { enumerable: true, get: function () { return elementAt_1.elementAt; } });
var endWith_1 = endWith$1;
Object.defineProperty(exports, "endWith", { enumerable: true, get: function () { return endWith_1.endWith; } });
var every_1 = every$1;
Object.defineProperty(exports, "every", { enumerable: true, get: function () { return every_1.every; } });
var exhaust_1 = exhaust;
Object.defineProperty(exports, "exhaust", { enumerable: true, get: function () { return exhaust_1.exhaust; } });
var exhaustAll_1 = exhaustAll$1;
Object.defineProperty(exports, "exhaustAll", { enumerable: true, get: function () { return exhaustAll_1.exhaustAll; } });
var exhaustMap_1 = exhaustMap$1;
Object.defineProperty(exports, "exhaustMap", { enumerable: true, get: function () { return exhaustMap_1.exhaustMap; } });
var expand_1 = expand$1;
Object.defineProperty(exports, "expand", { enumerable: true, get: function () { return expand_1.expand; } });
var filter_1 = filter$1;
Object.defineProperty(exports, "filter", { enumerable: true, get: function () { return filter_1.filter; } });
var finalize_1 = finalize$1;
Object.defineProperty(exports, "finalize", { enumerable: true, get: function () { return finalize_1.finalize; } });
var find_1 = find$1;
Object.defineProperty(exports, "find", { enumerable: true, get: function () { return find_1.find; } });
var findIndex_1 = findIndex$1;
Object.defineProperty(exports, "findIndex", { enumerable: true, get: function () { return findIndex_1.findIndex; } });
var first_1 = first$1;
Object.defineProperty(exports, "first", { enumerable: true, get: function () { return first_1.first; } });
var groupBy_1 = groupBy$1;
Object.defineProperty(exports, "groupBy", { enumerable: true, get: function () { return groupBy_1.groupBy; } });
var ignoreElements_1 = ignoreElements$1;
Object.defineProperty(exports, "ignoreElements", { enumerable: true, get: function () { return ignoreElements_1.ignoreElements; } });
var isEmpty_1 = isEmpty$1;
Object.defineProperty(exports, "isEmpty", { enumerable: true, get: function () { return isEmpty_1.isEmpty; } });
var last_1 = last$1;
Object.defineProperty(exports, "last", { enumerable: true, get: function () { return last_1.last; } });
var map_1 = map$1;
Object.defineProperty(exports, "map", { enumerable: true, get: function () { return map_1.map; } });
var mapTo_1 = mapTo$1;
Object.defineProperty(exports, "mapTo", { enumerable: true, get: function () { return mapTo_1.mapTo; } });
var materialize_1 = materialize$1;
Object.defineProperty(exports, "materialize", { enumerable: true, get: function () { return materialize_1.materialize; } });
var max_1 = max$1;
Object.defineProperty(exports, "max", { enumerable: true, get: function () { return max_1.max; } });
var mergeAll_1 = mergeAll$1;
Object.defineProperty(exports, "mergeAll", { enumerable: true, get: function () { return mergeAll_1.mergeAll; } });
var flatMap_1 = flatMap;
Object.defineProperty(exports, "flatMap", { enumerable: true, get: function () { return flatMap_1.flatMap; } });
var mergeMap_1 = mergeMap$1;
Object.defineProperty(exports, "mergeMap", { enumerable: true, get: function () { return mergeMap_1.mergeMap; } });
var mergeMapTo_1 = mergeMapTo$1;
Object.defineProperty(exports, "mergeMapTo", { enumerable: true, get: function () { return mergeMapTo_1.mergeMapTo; } });
var mergeScan_1 = mergeScan$1;
Object.defineProperty(exports, "mergeScan", { enumerable: true, get: function () { return mergeScan_1.mergeScan; } });
var mergeWith_1 = mergeWith$1;
Object.defineProperty(exports, "mergeWith", { enumerable: true, get: function () { return mergeWith_1.mergeWith; } });
var min_1 = min$1;
Object.defineProperty(exports, "min", { enumerable: true, get: function () { return min_1.min; } });
var multicast_1 = multicast$1;
Object.defineProperty(exports, "multicast", { enumerable: true, get: function () { return multicast_1.multicast; } });
var observeOn_1 = observeOn$1;
Object.defineProperty(exports, "observeOn", { enumerable: true, get: function () { return observeOn_1.observeOn; } });
var onErrorResumeNextWith_1 = onErrorResumeNextWith$1;
Object.defineProperty(exports, "onErrorResumeNextWith", { enumerable: true, get: function () { return onErrorResumeNextWith_1.onErrorResumeNextWith; } });
var pairwise_1 = pairwise$1;
Object.defineProperty(exports, "pairwise", { enumerable: true, get: function () { return pairwise_1.pairwise; } });
var pluck_1 = pluck$1;
Object.defineProperty(exports, "pluck", { enumerable: true, get: function () { return pluck_1.pluck; } });
var publish_1 = publish$1;
Object.defineProperty(exports, "publish", { enumerable: true, get: function () { return publish_1.publish; } });
var publishBehavior_1 = publishBehavior$1;
Object.defineProperty(exports, "publishBehavior", { enumerable: true, get: function () { return publishBehavior_1.publishBehavior; } });
var publishLast_1 = publishLast$1;
Object.defineProperty(exports, "publishLast", { enumerable: true, get: function () { return publishLast_1.publishLast; } });
var publishReplay_1 = publishReplay$1;
Object.defineProperty(exports, "publishReplay", { enumerable: true, get: function () { return publishReplay_1.publishReplay; } });
var raceWith_1 = raceWith$1;
Object.defineProperty(exports, "raceWith", { enumerable: true, get: function () { return raceWith_1.raceWith; } });
var reduce_1 = reduce$1;
Object.defineProperty(exports, "reduce", { enumerable: true, get: function () { return reduce_1.reduce; } });
var repeat_1 = repeat$1;
Object.defineProperty(exports, "repeat", { enumerable: true, get: function () { return repeat_1.repeat; } });
var repeatWhen_1 = repeatWhen$1;
Object.defineProperty(exports, "repeatWhen", { enumerable: true, get: function () { return repeatWhen_1.repeatWhen; } });
var retry_1 = retry$1;
Object.defineProperty(exports, "retry", { enumerable: true, get: function () { return retry_1.retry; } });
var retryWhen_1 = retryWhen$1;
Object.defineProperty(exports, "retryWhen", { enumerable: true, get: function () { return retryWhen_1.retryWhen; } });
var refCount_1 = refCount$1;
Object.defineProperty(exports, "refCount", { enumerable: true, get: function () { return refCount_1.refCount; } });
var sample_1 = sample$1;
Object.defineProperty(exports, "sample", { enumerable: true, get: function () { return sample_1.sample; } });
var sampleTime_1 = sampleTime$1;
Object.defineProperty(exports, "sampleTime", { enumerable: true, get: function () { return sampleTime_1.sampleTime; } });
var scan_1 = scan$1;
Object.defineProperty(exports, "scan", { enumerable: true, get: function () { return scan_1.scan; } });
var sequenceEqual_1 = sequenceEqual$1;
Object.defineProperty(exports, "sequenceEqual", { enumerable: true, get: function () { return sequenceEqual_1.sequenceEqual; } });
var share_1 = share$1;
Object.defineProperty(exports, "share", { enumerable: true, get: function () { return share_1.share; } });
var shareReplay_1 = shareReplay$1;
Object.defineProperty(exports, "shareReplay", { enumerable: true, get: function () { return shareReplay_1.shareReplay; } });
var single_1 = single$1;
Object.defineProperty(exports, "single", { enumerable: true, get: function () { return single_1.single; } });
var skip_1 = skip$1;
Object.defineProperty(exports, "skip", { enumerable: true, get: function () { return skip_1.skip; } });
var skipLast_1 = skipLast$1;
Object.defineProperty(exports, "skipLast", { enumerable: true, get: function () { return skipLast_1.skipLast; } });
var skipUntil_1 = skipUntil$1;
Object.defineProperty(exports, "skipUntil", { enumerable: true, get: function () { return skipUntil_1.skipUntil; } });
var skipWhile_1 = skipWhile$1;
Object.defineProperty(exports, "skipWhile", { enumerable: true, get: function () { return skipWhile_1.skipWhile; } });
var startWith_1 = startWith$1;
Object.defineProperty(exports, "startWith", { enumerable: true, get: function () { return startWith_1.startWith; } });
var subscribeOn_1 = subscribeOn$1;
Object.defineProperty(exports, "subscribeOn", { enumerable: true, get: function () { return subscribeOn_1.subscribeOn; } });
var switchAll_1 = switchAll$1;
Object.defineProperty(exports, "switchAll", { enumerable: true, get: function () { return switchAll_1.switchAll; } });
var switchMap_1 = switchMap$1;
Object.defineProperty(exports, "switchMap", { enumerable: true, get: function () { return switchMap_1.switchMap; } });
var switchMapTo_1 = switchMapTo$1;
Object.defineProperty(exports, "switchMapTo", { enumerable: true, get: function () { return switchMapTo_1.switchMapTo; } });
var switchScan_1 = switchScan$1;
Object.defineProperty(exports, "switchScan", { enumerable: true, get: function () { return switchScan_1.switchScan; } });
var take_1 = take$1;
Object.defineProperty(exports, "take", { enumerable: true, get: function () { return take_1.take; } });
var takeLast_1 = takeLast$1;
Object.defineProperty(exports, "takeLast", { enumerable: true, get: function () { return takeLast_1.takeLast; } });
var takeUntil_1 = takeUntil$1;
Object.defineProperty(exports, "takeUntil", { enumerable: true, get: function () { return takeUntil_1.takeUntil; } });
var takeWhile_1 = takeWhile$1;
Object.defineProperty(exports, "takeWhile", { enumerable: true, get: function () { return takeWhile_1.takeWhile; } });
var tap_1 = tap$1;
Object.defineProperty(exports, "tap", { enumerable: true, get: function () { return tap_1.tap; } });
var throttle_1 = throttle$1;
Object.defineProperty(exports, "throttle", { enumerable: true, get: function () { return throttle_1.throttle; } });
var throttleTime_1 = throttleTime$1;
Object.defineProperty(exports, "throttleTime", { enumerable: true, get: function () { return throttleTime_1.throttleTime; } });
var throwIfEmpty_1 = throwIfEmpty$1;
Object.defineProperty(exports, "throwIfEmpty", { enumerable: true, get: function () { return throwIfEmpty_1.throwIfEmpty; } });
var timeInterval_1 = timeInterval$1;
Object.defineProperty(exports, "timeInterval", { enumerable: true, get: function () { return timeInterval_1.timeInterval; } });
var timeout_2 = timeout;
Object.defineProperty(exports, "timeout", { enumerable: true, get: function () { return timeout_2.timeout; } });
var timeoutWith_1 = timeoutWith$1;
Object.defineProperty(exports, "timeoutWith", { enumerable: true, get: function () { return timeoutWith_1.timeoutWith; } });
var timestamp_1 = timestamp$1;
Object.defineProperty(exports, "timestamp", { enumerable: true, get: function () { return timestamp_1.timestamp; } });
var toArray_1 = toArray$1;
Object.defineProperty(exports, "toArray", { enumerable: true, get: function () { return toArray_1.toArray; } });
var window_1 = window$2;
Object.defineProperty(exports, "window", { enumerable: true, get: function () { return window_1.window; } });
var windowCount_1 = windowCount$1;
Object.defineProperty(exports, "windowCount", { enumerable: true, get: function () { return windowCount_1.windowCount; } });
var windowTime_1 = windowTime$1;
Object.defineProperty(exports, "windowTime", { enumerable: true, get: function () { return windowTime_1.windowTime; } });
var windowToggle_1 = windowToggle$1;
Object.defineProperty(exports, "windowToggle", { enumerable: true, get: function () { return windowToggle_1.windowToggle; } });
var windowWhen_1 = windowWhen$1;
Object.defineProperty(exports, "windowWhen", { enumerable: true, get: function () { return windowWhen_1.windowWhen; } });
var withLatestFrom_1 = withLatestFrom$1;
Object.defineProperty(exports, "withLatestFrom", { enumerable: true, get: function () { return withLatestFrom_1.withLatestFrom; } });
var zipAll_1 = zipAll$1;
Object.defineProperty(exports, "zipAll", { enumerable: true, get: function () { return zipAll_1.zipAll; } });
var zipWith_1 = zipWith$1;
Object.defineProperty(exports, "zipWith", { enumerable: true, get: function () { return zipWith_1.zipWith; } });

}(cjs));

var operators = {};

var partition$1 = {};

Object.defineProperty(partition$1, "__esModule", { value: true });
partition$1.partition = void 0;
var not_1 = not$1;
var filter_1 = filter$1;
function partition(predicate, thisArg) {
    return function (source) {
        return [filter_1.filter(predicate, thisArg)(source), filter_1.filter(not_1.not(predicate, thisArg))(source)];
    };
}
partition$1.partition = partition;

var race$1 = {};

var __read$7 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$2 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(race$1, "__esModule", { value: true });
race$1.race = void 0;
var argsOrArgArray_1 = argsOrArgArray$1;
var raceWith_1 = raceWith$1;
function race() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    return raceWith_1.raceWith.apply(void 0, __spreadArray$2([], __read$7(argsOrArgArray_1.argsOrArgArray(args))));
}
race$1.race = race;

(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeAll = exports.merge = exports.max = exports.materialize = exports.mapTo = exports.map = exports.last = exports.isEmpty = exports.ignoreElements = exports.groupBy = exports.first = exports.findIndex = exports.find = exports.finalize = exports.filter = exports.expand = exports.exhaustMap = exports.exhaustAll = exports.exhaust = exports.every = exports.endWith = exports.elementAt = exports.distinctUntilKeyChanged = exports.distinctUntilChanged = exports.distinct = exports.dematerialize = exports.delayWhen = exports.delay = exports.defaultIfEmpty = exports.debounceTime = exports.debounce = exports.count = exports.connect = exports.concatWith = exports.concatMapTo = exports.concatMap = exports.concatAll = exports.concat = exports.combineLatestWith = exports.combineLatest = exports.combineLatestAll = exports.combineAll = exports.catchError = exports.bufferWhen = exports.bufferToggle = exports.bufferTime = exports.bufferCount = exports.buffer = exports.auditTime = exports.audit = void 0;
exports.timeInterval = exports.throwIfEmpty = exports.throttleTime = exports.throttle = exports.tap = exports.takeWhile = exports.takeUntil = exports.takeLast = exports.take = exports.switchScan = exports.switchMapTo = exports.switchMap = exports.switchAll = exports.subscribeOn = exports.startWith = exports.skipWhile = exports.skipUntil = exports.skipLast = exports.skip = exports.single = exports.shareReplay = exports.share = exports.sequenceEqual = exports.scan = exports.sampleTime = exports.sample = exports.refCount = exports.retryWhen = exports.retry = exports.repeatWhen = exports.repeat = exports.reduce = exports.raceWith = exports.race = exports.publishReplay = exports.publishLast = exports.publishBehavior = exports.publish = exports.pluck = exports.partition = exports.pairwise = exports.onErrorResumeNext = exports.observeOn = exports.multicast = exports.min = exports.mergeWith = exports.mergeScan = exports.mergeMapTo = exports.mergeMap = exports.flatMap = void 0;
exports.zipWith = exports.zipAll = exports.zip = exports.withLatestFrom = exports.windowWhen = exports.windowToggle = exports.windowTime = exports.windowCount = exports.window = exports.toArray = exports.timestamp = exports.timeoutWith = exports.timeout = void 0;
var audit_1 = audit$1;
Object.defineProperty(exports, "audit", { enumerable: true, get: function () { return audit_1.audit; } });
var auditTime_1 = auditTime$1;
Object.defineProperty(exports, "auditTime", { enumerable: true, get: function () { return auditTime_1.auditTime; } });
var buffer_1 = buffer$2;
Object.defineProperty(exports, "buffer", { enumerable: true, get: function () { return buffer_1.buffer; } });
var bufferCount_1 = bufferCount$1;
Object.defineProperty(exports, "bufferCount", { enumerable: true, get: function () { return bufferCount_1.bufferCount; } });
var bufferTime_1 = bufferTime$1;
Object.defineProperty(exports, "bufferTime", { enumerable: true, get: function () { return bufferTime_1.bufferTime; } });
var bufferToggle_1 = bufferToggle$1;
Object.defineProperty(exports, "bufferToggle", { enumerable: true, get: function () { return bufferToggle_1.bufferToggle; } });
var bufferWhen_1 = bufferWhen$1;
Object.defineProperty(exports, "bufferWhen", { enumerable: true, get: function () { return bufferWhen_1.bufferWhen; } });
var catchError_1 = catchError$1;
Object.defineProperty(exports, "catchError", { enumerable: true, get: function () { return catchError_1.catchError; } });
var combineAll_1 = combineAll;
Object.defineProperty(exports, "combineAll", { enumerable: true, get: function () { return combineAll_1.combineAll; } });
var combineLatestAll_1 = combineLatestAll$1;
Object.defineProperty(exports, "combineLatestAll", { enumerable: true, get: function () { return combineLatestAll_1.combineLatestAll; } });
var combineLatest_1 = combineLatest$1;
Object.defineProperty(exports, "combineLatest", { enumerable: true, get: function () { return combineLatest_1.combineLatest; } });
var combineLatestWith_1 = combineLatestWith$1;
Object.defineProperty(exports, "combineLatestWith", { enumerable: true, get: function () { return combineLatestWith_1.combineLatestWith; } });
var concat_1 = concat$1;
Object.defineProperty(exports, "concat", { enumerable: true, get: function () { return concat_1.concat; } });
var concatAll_1 = concatAll$1;
Object.defineProperty(exports, "concatAll", { enumerable: true, get: function () { return concatAll_1.concatAll; } });
var concatMap_1 = concatMap$1;
Object.defineProperty(exports, "concatMap", { enumerable: true, get: function () { return concatMap_1.concatMap; } });
var concatMapTo_1 = concatMapTo$1;
Object.defineProperty(exports, "concatMapTo", { enumerable: true, get: function () { return concatMapTo_1.concatMapTo; } });
var concatWith_1 = concatWith$1;
Object.defineProperty(exports, "concatWith", { enumerable: true, get: function () { return concatWith_1.concatWith; } });
var connect_1 = connect$1;
Object.defineProperty(exports, "connect", { enumerable: true, get: function () { return connect_1.connect; } });
var count_1 = count$1;
Object.defineProperty(exports, "count", { enumerable: true, get: function () { return count_1.count; } });
var debounce_1 = debounce$1;
Object.defineProperty(exports, "debounce", { enumerable: true, get: function () { return debounce_1.debounce; } });
var debounceTime_1 = debounceTime$1;
Object.defineProperty(exports, "debounceTime", { enumerable: true, get: function () { return debounceTime_1.debounceTime; } });
var defaultIfEmpty_1 = defaultIfEmpty$1;
Object.defineProperty(exports, "defaultIfEmpty", { enumerable: true, get: function () { return defaultIfEmpty_1.defaultIfEmpty; } });
var delay_1 = delay$1;
Object.defineProperty(exports, "delay", { enumerable: true, get: function () { return delay_1.delay; } });
var delayWhen_1 = delayWhen$1;
Object.defineProperty(exports, "delayWhen", { enumerable: true, get: function () { return delayWhen_1.delayWhen; } });
var dematerialize_1 = dematerialize$1;
Object.defineProperty(exports, "dematerialize", { enumerable: true, get: function () { return dematerialize_1.dematerialize; } });
var distinct_1 = distinct$1;
Object.defineProperty(exports, "distinct", { enumerable: true, get: function () { return distinct_1.distinct; } });
var distinctUntilChanged_1 = distinctUntilChanged$1;
Object.defineProperty(exports, "distinctUntilChanged", { enumerable: true, get: function () { return distinctUntilChanged_1.distinctUntilChanged; } });
var distinctUntilKeyChanged_1 = distinctUntilKeyChanged$1;
Object.defineProperty(exports, "distinctUntilKeyChanged", { enumerable: true, get: function () { return distinctUntilKeyChanged_1.distinctUntilKeyChanged; } });
var elementAt_1 = elementAt$1;
Object.defineProperty(exports, "elementAt", { enumerable: true, get: function () { return elementAt_1.elementAt; } });
var endWith_1 = endWith$1;
Object.defineProperty(exports, "endWith", { enumerable: true, get: function () { return endWith_1.endWith; } });
var every_1 = every$1;
Object.defineProperty(exports, "every", { enumerable: true, get: function () { return every_1.every; } });
var exhaust_1 = exhaust;
Object.defineProperty(exports, "exhaust", { enumerable: true, get: function () { return exhaust_1.exhaust; } });
var exhaustAll_1 = exhaustAll$1;
Object.defineProperty(exports, "exhaustAll", { enumerable: true, get: function () { return exhaustAll_1.exhaustAll; } });
var exhaustMap_1 = exhaustMap$1;
Object.defineProperty(exports, "exhaustMap", { enumerable: true, get: function () { return exhaustMap_1.exhaustMap; } });
var expand_1 = expand$1;
Object.defineProperty(exports, "expand", { enumerable: true, get: function () { return expand_1.expand; } });
var filter_1 = filter$1;
Object.defineProperty(exports, "filter", { enumerable: true, get: function () { return filter_1.filter; } });
var finalize_1 = finalize$1;
Object.defineProperty(exports, "finalize", { enumerable: true, get: function () { return finalize_1.finalize; } });
var find_1 = find$1;
Object.defineProperty(exports, "find", { enumerable: true, get: function () { return find_1.find; } });
var findIndex_1 = findIndex$1;
Object.defineProperty(exports, "findIndex", { enumerable: true, get: function () { return findIndex_1.findIndex; } });
var first_1 = first$1;
Object.defineProperty(exports, "first", { enumerable: true, get: function () { return first_1.first; } });
var groupBy_1 = groupBy$1;
Object.defineProperty(exports, "groupBy", { enumerable: true, get: function () { return groupBy_1.groupBy; } });
var ignoreElements_1 = ignoreElements$1;
Object.defineProperty(exports, "ignoreElements", { enumerable: true, get: function () { return ignoreElements_1.ignoreElements; } });
var isEmpty_1 = isEmpty$1;
Object.defineProperty(exports, "isEmpty", { enumerable: true, get: function () { return isEmpty_1.isEmpty; } });
var last_1 = last$1;
Object.defineProperty(exports, "last", { enumerable: true, get: function () { return last_1.last; } });
var map_1 = map$1;
Object.defineProperty(exports, "map", { enumerable: true, get: function () { return map_1.map; } });
var mapTo_1 = mapTo$1;
Object.defineProperty(exports, "mapTo", { enumerable: true, get: function () { return mapTo_1.mapTo; } });
var materialize_1 = materialize$1;
Object.defineProperty(exports, "materialize", { enumerable: true, get: function () { return materialize_1.materialize; } });
var max_1 = max$1;
Object.defineProperty(exports, "max", { enumerable: true, get: function () { return max_1.max; } });
var merge_1 = merge$1;
Object.defineProperty(exports, "merge", { enumerable: true, get: function () { return merge_1.merge; } });
var mergeAll_1 = mergeAll$1;
Object.defineProperty(exports, "mergeAll", { enumerable: true, get: function () { return mergeAll_1.mergeAll; } });
var flatMap_1 = flatMap;
Object.defineProperty(exports, "flatMap", { enumerable: true, get: function () { return flatMap_1.flatMap; } });
var mergeMap_1 = mergeMap$1;
Object.defineProperty(exports, "mergeMap", { enumerable: true, get: function () { return mergeMap_1.mergeMap; } });
var mergeMapTo_1 = mergeMapTo$1;
Object.defineProperty(exports, "mergeMapTo", { enumerable: true, get: function () { return mergeMapTo_1.mergeMapTo; } });
var mergeScan_1 = mergeScan$1;
Object.defineProperty(exports, "mergeScan", { enumerable: true, get: function () { return mergeScan_1.mergeScan; } });
var mergeWith_1 = mergeWith$1;
Object.defineProperty(exports, "mergeWith", { enumerable: true, get: function () { return mergeWith_1.mergeWith; } });
var min_1 = min$1;
Object.defineProperty(exports, "min", { enumerable: true, get: function () { return min_1.min; } });
var multicast_1 = multicast$1;
Object.defineProperty(exports, "multicast", { enumerable: true, get: function () { return multicast_1.multicast; } });
var observeOn_1 = observeOn$1;
Object.defineProperty(exports, "observeOn", { enumerable: true, get: function () { return observeOn_1.observeOn; } });
var onErrorResumeNextWith_1 = onErrorResumeNextWith$1;
Object.defineProperty(exports, "onErrorResumeNext", { enumerable: true, get: function () { return onErrorResumeNextWith_1.onErrorResumeNext; } });
var pairwise_1 = pairwise$1;
Object.defineProperty(exports, "pairwise", { enumerable: true, get: function () { return pairwise_1.pairwise; } });
var partition_1 = partition$1;
Object.defineProperty(exports, "partition", { enumerable: true, get: function () { return partition_1.partition; } });
var pluck_1 = pluck$1;
Object.defineProperty(exports, "pluck", { enumerable: true, get: function () { return pluck_1.pluck; } });
var publish_1 = publish$1;
Object.defineProperty(exports, "publish", { enumerable: true, get: function () { return publish_1.publish; } });
var publishBehavior_1 = publishBehavior$1;
Object.defineProperty(exports, "publishBehavior", { enumerable: true, get: function () { return publishBehavior_1.publishBehavior; } });
var publishLast_1 = publishLast$1;
Object.defineProperty(exports, "publishLast", { enumerable: true, get: function () { return publishLast_1.publishLast; } });
var publishReplay_1 = publishReplay$1;
Object.defineProperty(exports, "publishReplay", { enumerable: true, get: function () { return publishReplay_1.publishReplay; } });
var race_1 = race$1;
Object.defineProperty(exports, "race", { enumerable: true, get: function () { return race_1.race; } });
var raceWith_1 = raceWith$1;
Object.defineProperty(exports, "raceWith", { enumerable: true, get: function () { return raceWith_1.raceWith; } });
var reduce_1 = reduce$1;
Object.defineProperty(exports, "reduce", { enumerable: true, get: function () { return reduce_1.reduce; } });
var repeat_1 = repeat$1;
Object.defineProperty(exports, "repeat", { enumerable: true, get: function () { return repeat_1.repeat; } });
var repeatWhen_1 = repeatWhen$1;
Object.defineProperty(exports, "repeatWhen", { enumerable: true, get: function () { return repeatWhen_1.repeatWhen; } });
var retry_1 = retry$1;
Object.defineProperty(exports, "retry", { enumerable: true, get: function () { return retry_1.retry; } });
var retryWhen_1 = retryWhen$1;
Object.defineProperty(exports, "retryWhen", { enumerable: true, get: function () { return retryWhen_1.retryWhen; } });
var refCount_1 = refCount$1;
Object.defineProperty(exports, "refCount", { enumerable: true, get: function () { return refCount_1.refCount; } });
var sample_1 = sample$1;
Object.defineProperty(exports, "sample", { enumerable: true, get: function () { return sample_1.sample; } });
var sampleTime_1 = sampleTime$1;
Object.defineProperty(exports, "sampleTime", { enumerable: true, get: function () { return sampleTime_1.sampleTime; } });
var scan_1 = scan$1;
Object.defineProperty(exports, "scan", { enumerable: true, get: function () { return scan_1.scan; } });
var sequenceEqual_1 = sequenceEqual$1;
Object.defineProperty(exports, "sequenceEqual", { enumerable: true, get: function () { return sequenceEqual_1.sequenceEqual; } });
var share_1 = share$1;
Object.defineProperty(exports, "share", { enumerable: true, get: function () { return share_1.share; } });
var shareReplay_1 = shareReplay$1;
Object.defineProperty(exports, "shareReplay", { enumerable: true, get: function () { return shareReplay_1.shareReplay; } });
var single_1 = single$1;
Object.defineProperty(exports, "single", { enumerable: true, get: function () { return single_1.single; } });
var skip_1 = skip$1;
Object.defineProperty(exports, "skip", { enumerable: true, get: function () { return skip_1.skip; } });
var skipLast_1 = skipLast$1;
Object.defineProperty(exports, "skipLast", { enumerable: true, get: function () { return skipLast_1.skipLast; } });
var skipUntil_1 = skipUntil$1;
Object.defineProperty(exports, "skipUntil", { enumerable: true, get: function () { return skipUntil_1.skipUntil; } });
var skipWhile_1 = skipWhile$1;
Object.defineProperty(exports, "skipWhile", { enumerable: true, get: function () { return skipWhile_1.skipWhile; } });
var startWith_1 = startWith$1;
Object.defineProperty(exports, "startWith", { enumerable: true, get: function () { return startWith_1.startWith; } });
var subscribeOn_1 = subscribeOn$1;
Object.defineProperty(exports, "subscribeOn", { enumerable: true, get: function () { return subscribeOn_1.subscribeOn; } });
var switchAll_1 = switchAll$1;
Object.defineProperty(exports, "switchAll", { enumerable: true, get: function () { return switchAll_1.switchAll; } });
var switchMap_1 = switchMap$1;
Object.defineProperty(exports, "switchMap", { enumerable: true, get: function () { return switchMap_1.switchMap; } });
var switchMapTo_1 = switchMapTo$1;
Object.defineProperty(exports, "switchMapTo", { enumerable: true, get: function () { return switchMapTo_1.switchMapTo; } });
var switchScan_1 = switchScan$1;
Object.defineProperty(exports, "switchScan", { enumerable: true, get: function () { return switchScan_1.switchScan; } });
var take_1 = take$1;
Object.defineProperty(exports, "take", { enumerable: true, get: function () { return take_1.take; } });
var takeLast_1 = takeLast$1;
Object.defineProperty(exports, "takeLast", { enumerable: true, get: function () { return takeLast_1.takeLast; } });
var takeUntil_1 = takeUntil$1;
Object.defineProperty(exports, "takeUntil", { enumerable: true, get: function () { return takeUntil_1.takeUntil; } });
var takeWhile_1 = takeWhile$1;
Object.defineProperty(exports, "takeWhile", { enumerable: true, get: function () { return takeWhile_1.takeWhile; } });
var tap_1 = tap$1;
Object.defineProperty(exports, "tap", { enumerable: true, get: function () { return tap_1.tap; } });
var throttle_1 = throttle$1;
Object.defineProperty(exports, "throttle", { enumerable: true, get: function () { return throttle_1.throttle; } });
var throttleTime_1 = throttleTime$1;
Object.defineProperty(exports, "throttleTime", { enumerable: true, get: function () { return throttleTime_1.throttleTime; } });
var throwIfEmpty_1 = throwIfEmpty$1;
Object.defineProperty(exports, "throwIfEmpty", { enumerable: true, get: function () { return throwIfEmpty_1.throwIfEmpty; } });
var timeInterval_1 = timeInterval$1;
Object.defineProperty(exports, "timeInterval", { enumerable: true, get: function () { return timeInterval_1.timeInterval; } });
var timeout_1 = timeout;
Object.defineProperty(exports, "timeout", { enumerable: true, get: function () { return timeout_1.timeout; } });
var timeoutWith_1 = timeoutWith$1;
Object.defineProperty(exports, "timeoutWith", { enumerable: true, get: function () { return timeoutWith_1.timeoutWith; } });
var timestamp_1 = timestamp$1;
Object.defineProperty(exports, "timestamp", { enumerable: true, get: function () { return timestamp_1.timestamp; } });
var toArray_1 = toArray$1;
Object.defineProperty(exports, "toArray", { enumerable: true, get: function () { return toArray_1.toArray; } });
var window_1 = window$2;
Object.defineProperty(exports, "window", { enumerable: true, get: function () { return window_1.window; } });
var windowCount_1 = windowCount$1;
Object.defineProperty(exports, "windowCount", { enumerable: true, get: function () { return windowCount_1.windowCount; } });
var windowTime_1 = windowTime$1;
Object.defineProperty(exports, "windowTime", { enumerable: true, get: function () { return windowTime_1.windowTime; } });
var windowToggle_1 = windowToggle$1;
Object.defineProperty(exports, "windowToggle", { enumerable: true, get: function () { return windowToggle_1.windowToggle; } });
var windowWhen_1 = windowWhen$1;
Object.defineProperty(exports, "windowWhen", { enumerable: true, get: function () { return windowWhen_1.windowWhen; } });
var withLatestFrom_1 = withLatestFrom$1;
Object.defineProperty(exports, "withLatestFrom", { enumerable: true, get: function () { return withLatestFrom_1.withLatestFrom; } });
var zip_1 = zip$1;
Object.defineProperty(exports, "zip", { enumerable: true, get: function () { return zip_1.zip; } });
var zipAll_1 = zipAll$1;
Object.defineProperty(exports, "zipAll", { enumerable: true, get: function () { return zipAll_1.zipAll; } });
var zipWith_1 = zipWith$1;
Object.defineProperty(exports, "zipWith", { enumerable: true, get: function () { return zipWith_1.zipWith; } });

}(operators));

var resultRx = {};

var __awaiter$8 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$8 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(resultRx, "__esModule", { value: true });
/**
 * 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 no-unused-vars */
var neo4j_driver_core_1$M = lib$1;
var rxjs_1$3 = cjs;
var operators_1$2 = operators;
var States = {
    READY: 0,
    STREAMING: 1,
    COMPLETED: 2
};
/**
 * The reactive result interface.
 */
var RxResult = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {Observable<Result>} result - An observable of single Result instance to relay requests.
     * @param {number} state - The streaming state
     */
    function RxResult(result, state) {
        var replayedResult = result.pipe((0, operators_1$2.publishReplay)(1), (0, operators_1$2.refCount)());
        this._result = replayedResult;
        this._keys = replayedResult.pipe((0, operators_1$2.mergeMap)(function (r) { return (0, rxjs_1$3.from)(r.keys()); }), (0, operators_1$2.publishReplay)(1), (0, operators_1$2.refCount)());
        this._records = undefined;
        this._controls = new StreamControl();
        this._summary = new rxjs_1$3.ReplaySubject();
        this._state = state || States.READY;
    }
    /**
     * Returns an observable that exposes a single item containing field names
     * returned by the executing query.
     *
     * Errors raised by actual query execution can surface on the returned
     * observable stream.
     *
     * @public
     * @returns {Observable<string[]>} - An observable stream (with exactly one element) of field names.
     */
    RxResult.prototype.keys = function () {
        return this._keys;
    };
    /**
     * Returns an observable that exposes each record returned by the executing query.
     *
     * Errors raised during the streaming phase can surface on the returned observable stream.
     *
     * @public
     * @returns {Observable<Record>} - An observable stream of records.
     */
    RxResult.prototype.records = function () {
        var _this = this;
        var result = this._result.pipe((0, operators_1$2.mergeMap)(function (result) {
            return new rxjs_1$3.Observable(function (recordsObserver) {
                return _this._startStreaming({ result: result, recordsObserver: recordsObserver });
            });
        }));
        result.push = function () { return _this._push(); };
        return result;
    };
    /**
     * Returns an observable that exposes a single item of {@link ResultSummary} that is generated by
     * the server after the streaming of the executing query is completed.
     *
     * *Subscribing to this stream before subscribing to records() stream causes the results to be discarded on the server.*
     *
     * @public
     * @returns {Observable<ResultSummary>} - An observable stream (with exactly one element) of result summary.
     */
    RxResult.prototype.consume = function () {
        var _this = this;
        return this._result.pipe((0, operators_1$2.mergeMap)(function (result) {
            return new rxjs_1$3.Observable(function (summaryObserver) {
                return _this._startStreaming({ result: result, summaryObserver: summaryObserver });
            });
        }));
    };
    /**
     * Pauses the automatic streaming of records.
     *
     * This method provides a way of control the flow of records
     *
     * @experimental
     */
    RxResult.prototype.pause = function () {
        this._controls.pause();
    };
    /**
     * Resumes the automatic streaming of records.
     *
     * This method won't need to be called in normal stream operation. It only applies to the case when the stream is paused.
     *
     * This method is method won't start the consuming records if the {@link records} stream didn't get subscribed.
     * @experimental
     * @returns {Promise<void>} - A promise that resolves when the stream is resumed.
     */
    RxResult.prototype.resume = function () {
        return this._controls.resume();
    };
    /**
     * Pushes the next record to the stream.
     *
     * This method automatic pause the auto-streaming of records and then push next record to the stream.
     *
     * For returning the automatic streaming of records, use {@link resume} method.
     *
     * @experimental
     * @returns {Promise<void>} - A promise that resolves when the push is completed.
     */
    RxResult.prototype.push = function () {
        return this._controls.push();
    };
    RxResult.prototype._startStreaming = function (_a) {
        var _b = _a === void 0 ? {} : _a, result = _b.result, _c = _b.recordsObserver, recordsObserver = _c === void 0 ? null : _c, _d = _b.summaryObserver, summaryObserver = _d === void 0 ? null : _d;
        var subscriptions = [];
        if (summaryObserver) {
            subscriptions.push(this._summary.subscribe(summaryObserver));
        }
        if (this._state < States.STREAMING) {
            this._state = States.STREAMING;
            this._setupRecordsStream(result);
            if (recordsObserver) {
                subscriptions.push(this._records.subscribe(recordsObserver));
            }
            else {
                result._cancel();
            }
            subscriptions.push({
                unsubscribe: function () {
                    if (result._cancel) {
                        result._cancel();
                    }
                }
            });
        }
        else if (recordsObserver) {
            recordsObserver.error((0, neo4j_driver_core_1$M.newError)('Streaming has already started/consumed with a previous records or summary subscription.'));
        }
        return function () {
            subscriptions.forEach(function (s) { return s.unsubscribe(); });
        };
    };
    /**
     * Create a {@link Observable} for the current {@link RxResult}
     *
     *
     * @package
     * @experimental
     * @since 5.0
     * @return {Observable<RxResult>}
     */
    RxResult.prototype._toObservable = function () {
        var _this = this;
        function wrap(result) {
            return new rxjs_1$3.Observable(function (observer) {
                observer.next(result);
                observer.complete();
            });
        }
        return new rxjs_1$3.Observable(function (observer) {
            _this._result.subscribe({
                complete: function () { return observer.complete(); },
                next: function (result) { return observer.next(new RxResult(wrap(result)), _this._state); },
                error: function (e) { return observer.error(e); }
            });
        });
    };
    RxResult.prototype._setupRecordsStream = function (result) {
        var _this = this;
        if (this._records) {
            return this._records;
        }
        this._records = createFullyControlledSubject(result[Symbol.asyncIterator](), {
            complete: function () { return __awaiter$8(_this, void 0, void 0, function () {
                var _a, _b;
                return __generator$8(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            this._state = States.COMPLETED;
                            _b = (_a = this._summary).next;
                            return [4 /*yield*/, result.summary()];
                        case 1:
                            _b.apply(_a, [_c.sent()]);
                            this._summary.complete();
                            return [2 /*return*/];
                    }
                });
            }); },
            error: function (error) {
                _this._state = States.COMPLETED;
                _this._summary.error(error);
            }
        }, this._controls);
        return this._records;
    };
    return RxResult;
}());
resultRx.default = RxResult;
function createFullyControlledSubject(iterator, completeObserver, streamControl) {
    var _this = this;
    if (streamControl === void 0) { streamControl = new StreamControl(); }
    var subject = new rxjs_1$3.Subject();
    var pushNextValue = function (result) { return __awaiter$8(_this, void 0, void 0, function () {
        var _a, done, value, error_1;
        return __generator$8(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 2, 3, 4]);
                    streamControl.pushing = true;
                    return [4 /*yield*/, result];
                case 1:
                    _a = _b.sent(), done = _a.done, value = _a.value;
                    if (done) {
                        subject.complete();
                        completeObserver.complete();
                    }
                    else {
                        subject.next(value);
                        if (!streamControl.paused) {
                            pushNextValue(iterator.next())
                                .catch(function () { });
                        }
                    }
                    return [3 /*break*/, 4];
                case 2:
                    error_1 = _b.sent();
                    subject.error(error_1);
                    completeObserver.error(error_1);
                    return [3 /*break*/, 4];
                case 3:
                    streamControl.pushing = false;
                    return [7 /*endfinally*/];
                case 4: return [2 /*return*/];
            }
        });
    }); };
    function push(value) {
        return __awaiter$8(this, void 0, void 0, function () {
            return __generator$8(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, pushNextValue(iterator.next(value))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    streamControl.pusher = push;
    push();
    return subject;
}
var StreamControl = /** @class */ (function () {
    function StreamControl(push) {
        if (push === void 0) { push = function () { return __awaiter$8(_this, void 0, void 0, function () { return __generator$8(this, function (_a) {
            return [2 /*return*/];
        }); }); }; }
        var _this = this;
        this._paused = false;
        this._pushing = false;
        this._push = push;
    }
    StreamControl.prototype.pause = function () {
        this._paused = true;
    };
    Object.defineProperty(StreamControl.prototype, "paused", {
        get: function () {
            return this._paused;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StreamControl.prototype, "pushing", {
        get: function () {
            return this._pushing;
        },
        set: function (pushing) {
            this._pushing = pushing;
        },
        enumerable: false,
        configurable: true
    });
    StreamControl.prototype.resume = function () {
        return __awaiter$8(this, void 0, void 0, function () {
            var wasPaused;
            return __generator$8(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        wasPaused = this._paused;
                        this._paused = false;
                        if (!(wasPaused && !this._pushing)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._push()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    StreamControl.prototype.push = function () {
        return __awaiter$8(this, void 0, void 0, function () {
            return __generator$8(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.pause();
                        return [4 /*yield*/, this._push()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    Object.defineProperty(StreamControl.prototype, "pusher", {
        get: function () {
            return this._push;
        },
        set: function (push) {
            this._push = push;
        },
        enumerable: false,
        configurable: true
    });
    return StreamControl;
}());

var transactionRx = {};

var __importDefault$T = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(transactionRx, "__esModule", { value: true });
/**
 * 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 rxjs_1$2 = cjs;
var result_rx_1$1 = __importDefault$T(resultRx);
// eslint-disable-next-line no-unused-vars
__importDefault$T(lib$1);
/**
 * A reactive transaction, which provides the same functionality as {@link Transaction} but through a Reactive API.
 */
var RxTransaction = /** @class */ (function () {
    /**
     * @constructor
     * @protected
     * @param {Transaction} txc - The underlying transaction instance to relay requests
     */
    function RxTransaction(txc) {
        this._txc = txc;
    }
    /**
     * Creates a reactive result that will execute the query in this transaction, with the provided parameters.
     *
     * @public
     * @param {string} query - Query to be executed.
     * @param {Object} parameters - Parameter values to use in query execution.
     * @returns {RxResult} - A reactive result
     */
    RxTransaction.prototype.run = function (query, parameters) {
        var _this = this;
        return new result_rx_1$1.default(new rxjs_1$2.Observable(function (observer) {
            try {
                observer.next(_this._txc.run(query, parameters));
                observer.complete();
            }
            catch (err) {
                observer.error(err);
            }
            return function () { };
        }));
    };
    /**
     *  Commits the transaction.
     *
     * @public
     * @returns {Observable} - An empty observable
     */
    RxTransaction.prototype.commit = function () {
        var _this = this;
        return new rxjs_1$2.Observable(function (observer) {
            _this._txc
                .commit()
                .then(function () {
                observer.complete();
            })
                .catch(function (err) { return observer.error(err); });
        });
    };
    /**
     *  Rolls back the transaction.
     *
     * @public
     * @returns {Observable} - An empty observable
     */
    RxTransaction.prototype.rollback = function () {
        var _this = this;
        return new rxjs_1$2.Observable(function (observer) {
            _this._txc
                .rollback()
                .then(function () {
                observer.complete();
            })
                .catch(function (err) { return observer.error(err); });
        });
    };
    /**
     * Check if this transaction is active, which means commit and rollback did not happen.
     * @return {boolean} `true` when not committed and not rolled back, `false` otherwise.
     */
    RxTransaction.prototype.isOpen = function () {
        return this._txc.isOpen();
    };
    /**
     * Closes the transaction
     *
     * This method will roll back the transaction if it is not already committed or rolled back.
     *
     * @returns {Observable} - An empty observable
     */
    RxTransaction.prototype.close = function () {
        var _this = this;
        return new rxjs_1$2.Observable(function (observer) {
            _this._txc
                .close()
                .then(function () {
                observer.complete();
            })
                .catch(function (err) { return observer.error(err); });
        });
    };
    return RxTransaction;
}());
transactionRx.default = RxTransaction;

var transactionManagedRx = {};

var __importDefault$S = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(transactionManagedRx, "__esModule", { value: true });
/**
 * 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 no-unused-vars
__importDefault$S(resultRx);
// eslint-disable-next-line no-unused-vars
__importDefault$S(transactionRx);
/**
 * Represents a rx transaction that is managed by the transaction executor.
 *
 * @public
 */
var RxManagedTransaction = /** @class */ (function () {
    /**
     * @private
     */
    function RxManagedTransaction(_a) {
        var run = _a.run;
        this._run = run;
    }
    /**
     * @private
     * @param {RxTransaction} txc - The transaction to be wrapped
     * @returns {RxManagedTransaction} The managed transaction
     */
    RxManagedTransaction.fromTransaction = function (txc) {
        return new RxManagedTransaction({
            run: txc.run.bind(txc)
        });
    };
    /**
     * Creates a reactive result that will execute the query in this transaction, with the provided parameters.
     *
     * @public
     * @param {string} query - Query to be executed.
     * @param {Object} parameters - Parameter values to use in query execution.
     * @returns {RxResult} - A reactive result
     */
    RxManagedTransaction.prototype.run = function (query, parameters) {
        return this._run(query, parameters);
    };
    return RxManagedTransaction;
}());
transactionManagedRx.default = RxManagedTransaction;

var retryLogicRx = {};

/**
 * 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(retryLogicRx, "__esModule", { value: true });
var neo4j_driver_core_1$L = lib$1;
// eslint-disable-next-line no-unused-vars
var rxjs_1$1 = cjs;
var operators_1$1 = operators;
// eslint-disable-next-line no-unused-vars
neo4j_driver_core_1$L.internal.logger.Logger;
var SERVICE_UNAVAILABLE$5 = neo4j_driver_core_1$L.error.SERVICE_UNAVAILABLE;
var DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000; // 30 seconds
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 RxRetryLogic = /** @class */ (function () {
    /**
     *
     * @param {Object} args
     * @param {Logger} args.logger
     */
    function RxRetryLogic(_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.maxRetryTimeout, maxRetryTimeout = _c === void 0 ? DEFAULT_MAX_RETRY_TIME_MS : _c, _d = _b.initialDelay, initialDelay = _d === void 0 ? DEFAULT_INITIAL_RETRY_DELAY_MS : _d, _e = _b.delayMultiplier, delayMultiplier = _e === void 0 ? DEFAULT_RETRY_DELAY_MULTIPLIER : _e, _f = _b.delayJitter, delayJitter = _f === void 0 ? DEFAULT_RETRY_DELAY_JITTER_FACTOR : _f, _g = _b.logger, logger = _g === void 0 ? null : _g;
        this._maxRetryTimeout = valueOrDefault(maxRetryTimeout, DEFAULT_MAX_RETRY_TIME_MS);
        this._initialDelay = valueOrDefault(initialDelay, DEFAULT_INITIAL_RETRY_DELAY_MS);
        this._delayMultiplier = valueOrDefault(delayMultiplier, DEFAULT_RETRY_DELAY_MULTIPLIER);
        this._delayJitter = valueOrDefault(delayJitter, DEFAULT_RETRY_DELAY_JITTER_FACTOR);
        this._logger = logger;
    }
    /**
     *
     * @param {Observable<Any>} work
     */
    RxRetryLogic.prototype.retry = function (work) {
        var _this = this;
        return work.pipe((0, operators_1$1.retryWhen)(function (failedWork) {
            var handledExceptions = [];
            var startTime = Date.now();
            var retryCount = 1;
            var delayDuration = _this._initialDelay;
            return failedWork.pipe((0, operators_1$1.mergeMap)(function (err) {
                if (!(0, neo4j_driver_core_1$L.isRetriableError)(err)) {
                    return (0, rxjs_1$1.throwError)(function () { return err; });
                }
                handledExceptions.push(err);
                if (retryCount >= 2 &&
                    Date.now() - startTime >= _this._maxRetryTimeout) {
                    var error_1 = (0, neo4j_driver_core_1$L.newError)("Failed after retried for ".concat(retryCount, " times in ").concat(_this._maxRetryTimeout, " ms. Make sure that your database is online and retry again."), SERVICE_UNAVAILABLE$5);
                    error_1.seenErrors = handledExceptions;
                    return (0, rxjs_1$1.throwError)(function () { return error_1; });
                }
                var nextDelayDuration = _this._computeNextDelay(delayDuration);
                delayDuration = delayDuration * _this._delayMultiplier;
                retryCount++;
                if (_this._logger) {
                    _this._logger.warn("Transaction failed and will be retried in ".concat(nextDelayDuration));
                }
                return (0, rxjs_1$1.of)(1).pipe((0, operators_1$1.delay)(nextDelayDuration));
            }));
        }));
    };
    RxRetryLogic.prototype._computeNextDelay = function (delay) {
        var jitter = delay * this._delayJitter;
        return delay - jitter + 2 * jitter * Math.random();
    };
    return RxRetryLogic;
}());
retryLogicRx.default = RxRetryLogic;
function valueOrDefault(value, defaultValue) {
    if (value || value === 0) {
        return value;
    }
    return defaultValue;
}

var __importDefault$R = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(sessionRx, "__esModule", { value: true });
/**
 * 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 rxjs_1 = cjs;
var operators_1 = operators;
var result_rx_1 = __importDefault$R(resultRx);
// eslint-disable-next-line no-unused-vars
var neo4j_driver_core_1$K = lib$1;
var transaction_rx_1 = __importDefault$R(transactionRx);
var transaction_managed_rx_1 = __importDefault$R(transactionManagedRx);
var retry_logic_rx_1 = __importDefault$R(retryLogicRx);
var _a$f = neo4j_driver_core_1$K.internal.constants, ACCESS_MODE_READ$1 = _a$f.ACCESS_MODE_READ, ACCESS_MODE_WRITE$1 = _a$f.ACCESS_MODE_WRITE, TELEMETRY_APIS = _a$f.TELEMETRY_APIS, TxConfig$3 = neo4j_driver_core_1$K.internal.txConfig.TxConfig;
/**
 * A Reactive session, which provides the same functionality as {@link Session} but through a Reactive API.
 */
var RxSession = /** @class */ (function () {
    /**
     * Constructs a reactive session with given default session instance and provided driver configuration.
     *
     * @protected
     * @param {Object} param - Object parameter
     * @param {Session} param.session - The underlying session instance to relay requests
     */
    function RxSession(_a) {
        var _b = _a === void 0 ? {} : _a, session = _b.session, config = _b.config, log = _b.log;
        this._session = session;
        this._retryLogic = _createRetryLogic(config);
        this._log = log;
    }
    /**
     * Creates a reactive result that will execute the  query with the provided parameters and the provided
     * transaction configuration that applies to the underlying auto-commit transaction.
     *
     * @public
     * @param {string} query - Query to be executed.
     * @param {Object} parameters - Parameter values to use in query execution.
     * @param {TransactionConfig} transactionConfig - Configuration for the new auto-commit transaction.
     * @returns {RxResult} - A reactive result
     */
    RxSession.prototype.run = function (query, parameters, transactionConfig) {
        var _this = this;
        return new result_rx_1.default(new rxjs_1.Observable(function (observer) {
            try {
                observer.next(_this._session.run(query, parameters, transactionConfig));
                observer.complete();
            }
            catch (err) {
                observer.error(err);
            }
            return function () { };
        }));
    };
    /**
     * Starts a new explicit transaction with the provided transaction configuration.
     *
     * @public
     * @param {TransactionConfig} transactionConfig - Configuration for the new transaction.
     * @returns {Observable<RxTransaction>} - A reactive stream that will generate at most **one** RxTransaction instance.
     */
    RxSession.prototype.beginTransaction = function (transactionConfig) {
        return this._beginTransaction(this._session._mode, transactionConfig, { api: TELEMETRY_APIS.UNMANAGED_TRANSACTION });
    };
    /**
     * Executes the provided unit of work in a {@link READ} reactive transaction which is created with the provided
     * transaction configuration.
     * @public
     * @deprecated This method will be removed in version 6.0. Please, use {@link RxSession#executeRead} instead.
     * @param {function(txc: RxTransaction): Observable} work - A unit of work to be executed.
     * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver.
     * @returns {Observable} - A reactive stream returned by the unit of work.
     */
    RxSession.prototype.readTransaction = function (work, transactionConfig) {
        return this._runTransaction(ACCESS_MODE_READ$1, work, transactionConfig);
    };
    /**
     * Executes the provided unit of work in a {@link WRITE} reactive transaction which is created with the provided
     * transaction configuration.
     * @public
     * @deprecated This method will be removed in version 6.0. Please, use {@link RxSession#executeWrite} instead.
     * @param {function(txc: RxTransaction): Observable} work - A unit of work to be executed.
     * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver.
     * @returns {Observable} - A reactive stream returned by the unit of work.
     */
    RxSession.prototype.writeTransaction = function (work, transactionConfig) {
        return this._runTransaction(ACCESS_MODE_WRITE$1, work, transactionConfig);
    };
    /**
     * Executes the provided unit of work in a {@link READ} reactive transaction which is created with the provided
     * transaction configuration.
     * @public
     * @param {function(txc: RxManagedTransaction): Observable} work - A unit of work to be executed.
     * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver.
     * @returns {Observable} - A reactive stream returned by the unit of work.
     */
    RxSession.prototype.executeRead = function (work, transactionConfig) {
        return this._executeInTransaction(ACCESS_MODE_READ$1, work, transactionConfig);
    };
    /**
     * Executes the provided unit of work in a {@link WRITE} reactive transaction which is created with the provided
     * transaction configuration.
     * @public
     * @param {function(txc: RxManagedTransaction): Observable} work - A unit of work to be executed.
     * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver.
     * @returns {Observable} - A reactive stream returned by the unit of work.
     */
    RxSession.prototype.executeWrite = function (work, transactionConfig) {
        return this._executeInTransaction(ACCESS_MODE_WRITE$1, work, transactionConfig);
    };
    /**
     * @private
     * @param {function(txc: RxManagedTransaction): Observable} work
     * @param {TransactionConfig} transactionConfig
     * @returns {Observable}
     */
    RxSession.prototype._executeInTransaction = function (accessMode, work, transactionConfig) {
        var wrapper = function (txc) { return new transaction_managed_rx_1.default({
            run: txc.run.bind(txc)
        }); };
        return this._runTransaction(accessMode, work, transactionConfig, wrapper);
    };
    /**
     * Closes this reactive session.
     *
     * @public
     * @returns {Observable} - An empty reactive stream
     */
    RxSession.prototype.close = function () {
        var _this = this;
        return new rxjs_1.Observable(function (observer) {
            _this._session
                .close()
                .then(function () {
                observer.complete();
            })
                .catch(function (err) { return observer.error(err); });
        });
    };
    RxSession.prototype[Symbol.asyncDispose] = function () {
        return this.close();
    };
    /**
     * Returns the bookmarks received following the last successfully completed query, which is executed
     * either in an {@link RxTransaction} obtained from this session instance or directly through one of
     * the {@link RxSession#run} method of this session instance.
     *
     * If no bookmarks were received or if this transaction was rolled back, the bookmarks value will not be
     * changed.
     *
     * @deprecated This method will be removed in 6.0 version. Please, use {@link RxSession#lastBookmarks} instead.
     *
     * @public
     * @returns {string[]}
     */
    RxSession.prototype.lastBookmark = function () {
        return this.lastBookmarks();
    };
    /**
     * Returns the bookmarks received following the last successfully completed query, which is executed
     * either in an {@link RxTransaction} obtained from this session instance or directly through one of
     * the {@link RxSession#run} method of this session instance.
     *
     * If no bookmarks were received or if this transaction was rolled back, the bookmarks value will not be
     * changed.
     *
     * @public
     * @returns {string[]}
     */
    RxSession.prototype.lastBookmarks = function () {
        return this._session.lastBookmarks();
    };
    /**
     * @private
     */
    RxSession.prototype._beginTransaction = function (accessMode, transactionConfig, apiTelemetryConfig) {
        var _this = this;
        var txConfig = TxConfig$3.empty();
        if (transactionConfig) {
            txConfig = new TxConfig$3(transactionConfig, this._log);
        }
        return new rxjs_1.Observable(function (observer) {
            try {
                _this._session._beginTransaction(accessMode, txConfig, apiTelemetryConfig)
                    .then(function (tx) {
                    observer.next(new transaction_rx_1.default(tx));
                    observer.complete();
                })
                    .catch(function (err) { return observer.error(err); });
            }
            catch (err) {
                observer.error(err);
            }
            return function () { };
        });
    };
    /**
     * @private
     */
    RxSession.prototype._runTransaction = function (accessMode, work, transactionConfig, transactionWrapper) {
        var _this = this;
        if (transactionWrapper === void 0) { transactionWrapper = function (tx) { return tx; }; }
        var txConfig = TxConfig$3.empty();
        if (transactionConfig) {
            txConfig = new TxConfig$3(transactionConfig);
        }
        var context = {
            apiTelemetryConfig: {
                api: TELEMETRY_APIS.MANAGED_TRANSACTION,
                onTelemetrySuccess: function () {
                    context.apiTelemetryConfig = undefined;
                }
            }
        };
        return this._retryLogic.retry((0, rxjs_1.of)(1).pipe((0, operators_1.mergeMap)(function () { return _this._beginTransaction(accessMode, txConfig, context.apiTelemetryConfig); }), (0, operators_1.mergeMap)(function (txc) {
            return (0, rxjs_1.defer)(function () {
                try {
                    return work(transactionWrapper(txc));
                }
                catch (err) {
                    return (0, rxjs_1.throwError)(function () { return err; });
                }
            }).pipe((0, operators_1.catchError)(function (err) { return txc.rollback().pipe((0, operators_1.concatWith)((0, rxjs_1.throwError)(function () { return err; }))); }), (0, operators_1.concatWith)(txc.commit()));
        })));
    };
    return RxSession;
}());
sessionRx.default = RxSession;
function _createRetryLogic(config) {
    var maxRetryTimeout = config && config.maxTransactionRetryTime
        ? config.maxTransactionRetryTime
        : null;
    return new retry_logic_rx_1.default({ maxRetryTimeout: maxRetryTimeout });
}

/**
 * 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$w = (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 __importDefault$Q = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(driver$1, "__esModule", { value: true });
driver$1.WRITE = driver$1.READ = driver$1.Driver = void 0;
var neo4j_driver_core_1$J = lib$1;
var session_rx_1 = __importDefault$Q(sessionRx);
var FETCH_ALL$7 = neo4j_driver_core_1$J.internal.constants.FETCH_ALL;
var READ$2 = neo4j_driver_core_1$J.driver.READ, WRITE$2 = neo4j_driver_core_1$J.driver.WRITE;
driver$1.READ = READ$2;
driver$1.WRITE = WRITE$2;
/**
 * A driver maintains one or more {@link Session}s with a remote
 * Neo4j instance. Through the {@link Session}s you can send queries
 * 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 = /** @class */ (function (_super) {
    __extends$w(Driver, _super);
    function Driver() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Acquire a reactive session to communicate with the database. The session will
     * borrow connections from the underlying connection pool as required and
     * should be considered lightweight and disposable.
     *
     * 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 closed, the underlying connection will be released to the connection
     * pool and made available for others to use.
     *
     * @public
     * @param {SessionConfig} config
     * @returns {RxSession} new reactive session.
     */
    Driver.prototype.rxSession = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.defaultAccessMode, defaultAccessMode = _c === void 0 ? WRITE$2 : _c, bookmarks = _b.bookmarks, _d = _b.database, database = _d === void 0 ? '' : _d, fetchSize = _b.fetchSize, impersonatedUser = _b.impersonatedUser, bookmarkManager = _b.bookmarkManager, notificationFilter = _b.notificationFilter, auth = _b.auth;
        return new session_rx_1.default({
            session: this._newSession({
                defaultAccessMode: defaultAccessMode,
                bookmarkOrBookmarks: bookmarks,
                database: database,
                impersonatedUser: impersonatedUser,
                auth: auth,
                reactive: false,
                fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize),
                bookmarkManager: bookmarkManager,
                notificationFilter: notificationFilter,
                log: this._log
            }),
            config: this._config,
            log: this._log
        });
    };
    return Driver;
}(neo4j_driver_core_1$J.Driver));
driver$1.Driver = Driver;
/**
 * @private
 */
function validateFetchSizeValue(rawValue, defaultWhenAbsent) {
    var fetchSize = parseInt(rawValue, 10);
    if (fetchSize > 0 || fetchSize === FETCH_ALL$7) {
        return fetchSize;
    }
    else if (fetchSize === 0 || fetchSize < 0) {
        throw new Error("The fetch size can only be a positive value or ".concat(FETCH_ALL$7, " for ALL. However fetchSize = ").concat(fetchSize));
    }
    else {
        return defaultWhenAbsent;
    }
}
driver$1.default = Driver;

var version$1 = {};

/**
 * 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(version$1, "__esModule", { value: true });
// DO NOT CHANGE THE VERSION BELOW HERE
// This is set by the build system at release time, using
//
// gulp set --x <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.
version$1.default = '5.28.3';

var lib = {};

var loadBalancing = {};

var loadBalancingStrategy = {};

/**
 * 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(loadBalancingStrategy, "__esModule", { value: true });
/**
 * A facility to select most appropriate reader or writer among the given addresses for request processing.
 */
var LoadBalancingStrategy = /** @class */ (function () {
    function LoadBalancingStrategy() {
    }
    /**
     * 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 `null` if given array is empty.
     */
    LoadBalancingStrategy.prototype.selectReader = function (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 `null` if given array is empty.
     */
    LoadBalancingStrategy.prototype.selectWriter = function (knownWriters) {
        throw new Error('Abstract function');
    };
    return LoadBalancingStrategy;
}());
loadBalancingStrategy.default = LoadBalancingStrategy;

var leastConnectedLoadBalancingStrategy = {};

var roundRobinArrayIndex = {};

/**
 * 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(roundRobinArrayIndex, "__esModule", { value: true });
var RoundRobinArrayIndex = /** @class */ (function () {
    /**
     * @constructor
     * @param {number} [initialOffset=0] the initial offset for round robin.
     */
    function RoundRobinArrayIndex(initialOffset) {
        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.
     */
    RoundRobinArrayIndex.prototype.next = function (arrayLength) {
        if (arrayLength === 0) {
            return -1;
        }
        var nextOffset = this._offset;
        this._offset += 1;
        if (this._offset === Number.MAX_SAFE_INTEGER) {
            this._offset = 0;
        }
        return nextOffset % arrayLength;
    };
    return RoundRobinArrayIndex;
}());
roundRobinArrayIndex.default = RoundRobinArrayIndex;

var __extends$v = (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 __importDefault$P = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(leastConnectedLoadBalancingStrategy, "__esModule", { value: true });
/**
 * 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 round_robin_array_index_1 = __importDefault$P(roundRobinArrayIndex);
var load_balancing_strategy_1$1 = __importDefault$P(loadBalancingStrategy);
var LeastConnectedLoadBalancingStrategy = /** @class */ (function (_super) {
    __extends$v(LeastConnectedLoadBalancingStrategy, _super);
    /**
     * @constructor
     * @param {Pool} connectionPool the connection pool of this driver.
     */
    function LeastConnectedLoadBalancingStrategy(connectionPool) {
        var _this = _super.call(this) || this;
        _this._readersIndex = new round_robin_array_index_1.default();
        _this._writersIndex = new round_robin_array_index_1.default();
        _this._connectionPool = connectionPool;
        return _this;
    }
    /**
     * @inheritDoc
     */
    LeastConnectedLoadBalancingStrategy.prototype.selectReader = function (knownReaders) {
        return this._select(knownReaders, this._readersIndex);
    };
    /**
     * @inheritDoc
     */
    LeastConnectedLoadBalancingStrategy.prototype.selectWriter = function (knownWriters) {
        return this._select(knownWriters, this._writersIndex);
    };
    LeastConnectedLoadBalancingStrategy.prototype._select = function (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 = Number.MAX_SAFE_INTEGER;
        // 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;
}(load_balancing_strategy_1$1.default));
leastConnectedLoadBalancingStrategy.default = LeastConnectedLoadBalancingStrategy;

var __importDefault$O = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(loadBalancing, "__esModule", { value: true });
loadBalancing.LeastConnectedLoadBalancingStrategy = loadBalancing.LoadBalancingStrategy = 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.
 */
var load_balancing_strategy_1 = __importDefault$O(loadBalancingStrategy);
loadBalancing.LoadBalancingStrategy = load_balancing_strategy_1.default;
var least_connected_load_balancing_strategy_1 = __importDefault$O(leastConnectedLoadBalancingStrategy);
loadBalancing.LeastConnectedLoadBalancingStrategy = least_connected_load_balancing_strategy_1.default;
loadBalancing.default = least_connected_load_balancing_strategy_1.default;

var bolt = {};

var handshake$1 = {};

var channel = {};

var browser = {};

var browserChannel = {};

var channelBuf = {};

var buffer = {};

var base64Js = {};

base64Js.byteLength = byteLength;
base64Js.toByteArray = toByteArray;
base64Js.fromByteArray = fromByteArray;

var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i];
  revLookup[code.charCodeAt(i)] = i;
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;

function getLens (b64) {
  var len = b64.length;

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=');
  if (validLen === -1) validLen = len;

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4);

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64);
  var validLen = lens[0];
  var placeHoldersLen = lens[1];
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp;
  var lens = getLens(b64);
  var validLen = lens[0];
  var placeHoldersLen = lens[1];

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));

  var curByte = 0;

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen;

  var i;
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)];
    arr[curByte++] = (tmp >> 16) & 0xFF;
    arr[curByte++] = (tmp >> 8) & 0xFF;
    arr[curByte++] = tmp & 0xFF;
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4);
    arr[curByte++] = tmp & 0xFF;
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2);
    arr[curByte++] = (tmp >> 8) & 0xFF;
    arr[curByte++] = tmp & 0xFF;
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp;
  var output = [];
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF);
    output.push(tripletToBase64(tmp));
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp;
  var len = uint8.length;
  var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  var parts = [];
  var maxChunkLength = 16383; // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1];
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    );
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1];
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    );
  }

  return parts.join('')
}

var ieee754 = {};

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */

ieee754.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m;
  var eLen = (nBytes * 8) - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var nBits = -7;
  var i = isLE ? (nBytes - 1) : 0;
  var d = isLE ? -1 : 1;
  var s = buffer[offset + i];

  i += d;

  e = s & ((1 << (-nBits)) - 1);
  s >>= (-nBits);
  nBits += eLen;
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1);
  e >>= (-nBits);
  nBits += mLen;
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
};

ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c;
  var eLen = (nBytes * 8) - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  var i = isLE ? 0 : (nBytes - 1);
  var d = isLE ? 1 : -1;
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;

  value = Math.abs(value);

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }
    if (value * c >= 2) {
      e++;
      c /= 2;
    }

    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128;
};

/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */

(function (exports) {

const base64 = base64Js;
const ieee754$1 = ieee754;
const customInspectSymbol =
  (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
    ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
    : null;

exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;

const K_MAX_LENGTH = 0x7fffffff;
exports.kMaxLength = K_MAX_LENGTH;

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  );
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    const arr = new Uint8Array(1);
    const proto = { foo: function () { return 42 } };
    Object.setPrototypeOf(proto, Uint8Array.prototype);
    Object.setPrototypeOf(arr, proto);
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
});

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
});

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  const buf = new Uint8Array(length);
  Object.setPrototypeOf(buf, Buffer.prototype);
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192; // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayView(value)
  }

  if (value == null) {
    throw new TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof SharedArrayBuffer !== 'undefined' &&
      (isInstance(value, SharedArrayBuffer) ||
      (value && isInstance(value.buffer, SharedArrayBuffer)))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  const valueOf = value.valueOf && value.valueOf();
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  const b = fromObject(value);
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
};

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
Object.setPrototypeOf(Buffer, Uint8Array);

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size);
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpreted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
};

function allocUnsafe (size) {
  assertSize(size);
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
};
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
};

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8';
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  const length = byteLength(string, encoding) | 0;
  let buf = createBuffer(length);

  const actual = buf.write(string, encoding);

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual);
  }

  return buf
}

function fromArrayLike (array) {
  const length = array.length < 0 ? 0 : checked(array.length) | 0;
  const buf = createBuffer(length);
  for (let i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255;
  }
  return buf
}

function fromArrayView (arrayView) {
  if (isInstance(arrayView, Uint8Array)) {
    const copy = new Uint8Array(arrayView);
    return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
  }
  return fromArrayLike(arrayView)
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  let buf;
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array);
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset);
  } else {
    buf = new Uint8Array(array, byteOffset, length);
  }

  // Return an augmented `Uint8Array` instance
  Object.setPrototypeOf(buf, Buffer.prototype);

  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    const len = checked(obj.length) | 0;
    const buf = createBuffer(len);

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len);
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0;
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
};

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  let x = a.length;
  let y = b.length;

  for (let i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
};

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
};

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  let i;
  if (length === undefined) {
    length = 0;
    for (i = 0; i < list.length; ++i) {
      length += list[i].length;
    }
  }

  const buffer = Buffer.allocUnsafe(length);
  let pos = 0;
  for (i = 0; i < list.length; ++i) {
    let buf = list[i];
    if (isInstance(buf, Uint8Array)) {
      if (pos + buf.length > buffer.length) {
        if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
        buf.copy(buffer, pos);
      } else {
        Uint8Array.prototype.set.call(
          buffer,
          buf,
          pos
        );
      }
    } else if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    } else {
      buf.copy(buffer, pos);
    }
    pos += buf.length;
  }
  return buffer
};

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  const len = string.length;
  const mustMatch = (arguments.length > 2 && arguments[2] === true);
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  let loweredCase = false;
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase();
        loweredCase = true;
    }
  }
}
Buffer.byteLength = byteLength;

function slowToString (encoding, start, end) {
  let loweredCase = false;

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0;
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length;
  }

  if (end <= 0) {
    return ''
  }

  // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0;
  start >>>= 0;

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8';

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase();
        loweredCase = true;
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true;

function swap (b, n, m) {
  const i = b[n];
  b[n] = b[m];
  b[m] = i;
}

Buffer.prototype.swap16 = function swap16 () {
  const len = this.length;
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (let i = 0; i < len; i += 2) {
    swap(this, i, i + 1);
  }
  return this
};

Buffer.prototype.swap32 = function swap32 () {
  const len = this.length;
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (let i = 0; i < len; i += 4) {
    swap(this, i, i + 3);
    swap(this, i + 1, i + 2);
  }
  return this
};

Buffer.prototype.swap64 = function swap64 () {
  const len = this.length;
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (let i = 0; i < len; i += 8) {
    swap(this, i, i + 7);
    swap(this, i + 1, i + 6);
    swap(this, i + 2, i + 5);
    swap(this, i + 3, i + 4);
  }
  return this
};

Buffer.prototype.toString = function toString () {
  const length = this.length;
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
};

Buffer.prototype.toLocaleString = Buffer.prototype.toString;

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
};

Buffer.prototype.inspect = function inspect () {
  let str = '';
  const max = exports.INSPECT_MAX_BYTES;
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
  if (this.length > max) str += ' ... ';
  return '<Buffer ' + str + '>'
};
if (customInspectSymbol) {
  Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength);
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0;
  }
  if (end === undefined) {
    end = target ? target.length : 0;
  }
  if (thisStart === undefined) {
    thisStart = 0;
  }
  if (thisEnd === undefined) {
    thisEnd = this.length;
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0;
  end >>>= 0;
  thisStart >>>= 0;
  thisEnd >>>= 0;

  if (this === target) return 0

  let x = thisEnd - thisStart;
  let y = end - start;
  const len = Math.min(x, y);

  const thisCopy = this.slice(thisStart, thisEnd);
  const targetCopy = target.slice(start, end);

  for (let i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i];
      y = targetCopy[i];
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
};

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset;
    byteOffset = 0;
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff;
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000;
  }
  byteOffset = +byteOffset; // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1);
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1;
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0;
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding);
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF; // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  let indexSize = 1;
  let arrLength = arr.length;
  let valLength = val.length;

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase();
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2;
      arrLength /= 2;
      valLength /= 2;
      byteOffset /= 2;
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  let i;
  if (dir) {
    let foundIndex = -1;
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i;
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex;
        foundIndex = -1;
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
    for (i = byteOffset; i >= 0; i--) {
      let found = true;
      for (let j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false;
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
};

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
};

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
};

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0;
  const remaining = buf.length - offset;
  if (!length) {
    length = remaining;
  } else {
    length = Number(length);
    if (length > remaining) {
      length = remaining;
    }
  }

  const strLen = string.length;

  if (length > strLen / 2) {
    length = strLen / 2;
  }
  let i;
  for (i = 0; i < length; ++i) {
    const parsed = parseInt(string.substr(i * 2, 2), 16);
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed;
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8';
    length = this.length;
    offset = 0;
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset;
    length = this.length;
    offset = 0;
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0;
    if (isFinite(length)) {
      length = length >>> 0;
      if (encoding === undefined) encoding = 'utf8';
    } else {
      encoding = length;
      length = undefined;
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  const remaining = this.length - offset;
  if (length === undefined || length > remaining) length = remaining;

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8';

  let loweredCase = false;
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
      case 'latin1':
      case 'binary':
        return asciiWrite(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase();
        loweredCase = true;
    }
  }
};

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
};

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end);
  const res = [];

  let i = start;
  while (i < end) {
    const firstByte = buf[i];
    let codePoint = null;
    let bytesPerSequence = (firstByte > 0xEF)
      ? 4
      : (firstByte > 0xDF)
          ? 3
          : (firstByte > 0xBF)
              ? 2
              : 1;

    if (i + bytesPerSequence <= end) {
      let secondByte, thirdByte, fourthByte, tempCodePoint;

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte;
          }
          break
        case 2:
          secondByte = buf[i + 1];
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint;
            }
          }
          break
        case 3:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 2];
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint;
            }
          }
          break
        case 4:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 2];
          fourthByte = buf[i + 3];
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint;
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD;
      bytesPerSequence = 1;
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000;
      res.push(codePoint >>> 10 & 0x3FF | 0xD800);
      codePoint = 0xDC00 | codePoint & 0x3FF;
    }

    res.push(codePoint);
    i += bytesPerSequence;
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000;

function decodeCodePointsArray (codePoints) {
  const len = codePoints.length;
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  let res = '';
  let i = 0;
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    );
  }
  return res
}

function asciiSlice (buf, start, end) {
  let ret = '';
  end = Math.min(buf.length, end);

  for (let i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F);
  }
  return ret
}

function latin1Slice (buf, start, end) {
  let ret = '';
  end = Math.min(buf.length, end);

  for (let i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i]);
  }
  return ret
}

function hexSlice (buf, start, end) {
  const len = buf.length;

  if (!start || start < 0) start = 0;
  if (!end || end < 0 || end > len) end = len;

  let out = '';
  for (let i = start; i < end; ++i) {
    out += hexSliceLookupTable[buf[i]];
  }
  return out
}

function utf16leSlice (buf, start, end) {
  const bytes = buf.slice(start, end);
  let res = '';
  // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
  for (let i = 0; i < bytes.length - 1; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  const len = this.length;
  start = ~~start;
  end = end === undefined ? len : ~~end;

  if (start < 0) {
    start += len;
    if (start < 0) start = 0;
  } else if (start > len) {
    start = len;
  }

  if (end < 0) {
    end += len;
    if (end < 0) end = 0;
  } else if (end > len) {
    end = len;
  }

  if (end < start) end = start;

  const newBuf = this.subarray(start, end);
  // Return an augmented `Uint8Array` instance
  Object.setPrototypeOf(newBuf, Buffer.prototype);

  return newBuf
};

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUintLE =
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0;
  byteLength = byteLength >>> 0;
  if (!noAssert) checkOffset(offset, byteLength, this.length);

  let val = this[offset];
  let mul = 1;
  let i = 0;
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul;
  }

  return val
};

Buffer.prototype.readUintBE =
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0;
  byteLength = byteLength >>> 0;
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length);
  }

  let val = this[offset + --byteLength];
  let mul = 1;
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul;
  }

  return val
};

Buffer.prototype.readUint8 =
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 1, this.length);
  return this[offset]
};

Buffer.prototype.readUint16LE =
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 2, this.length);
  return this[offset] | (this[offset + 1] << 8)
};

Buffer.prototype.readUint16BE =
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 2, this.length);
  return (this[offset] << 8) | this[offset + 1]
};

Buffer.prototype.readUint32LE =
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 4, this.length);

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
};

Buffer.prototype.readUint32BE =
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 4, this.length);

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
};

Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {
  offset = offset >>> 0;
  validateNumber(offset, 'offset');
  const first = this[offset];
  const last = this[offset + 7];
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8);
  }

  const lo = first +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 24;

  const hi = this[++offset] +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    last * 2 ** 24;

  return BigInt(lo) + (BigInt(hi) << BigInt(32))
});

Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {
  offset = offset >>> 0;
  validateNumber(offset, 'offset');
  const first = this[offset];
  const last = this[offset + 7];
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8);
  }

  const hi = first * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    this[++offset];

  const lo = this[++offset] * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    last;

  return (BigInt(hi) << BigInt(32)) + BigInt(lo)
});

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0;
  byteLength = byteLength >>> 0;
  if (!noAssert) checkOffset(offset, byteLength, this.length);

  let val = this[offset];
  let mul = 1;
  let i = 0;
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul;
  }
  mul *= 0x80;

  if (val >= mul) val -= Math.pow(2, 8 * byteLength);

  return val
};

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0;
  byteLength = byteLength >>> 0;
  if (!noAssert) checkOffset(offset, byteLength, this.length);

  let i = byteLength;
  let mul = 1;
  let val = this[offset + --i];
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul;
  }
  mul *= 0x80;

  if (val >= mul) val -= Math.pow(2, 8 * byteLength);

  return val
};

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 1, this.length);
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
};

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 2, this.length);
  const val = this[offset] | (this[offset + 1] << 8);
  return (val & 0x8000) ? val | 0xFFFF0000 : val
};

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 2, this.length);
  const val = this[offset + 1] | (this[offset] << 8);
  return (val & 0x8000) ? val | 0xFFFF0000 : val
};

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 4, this.length);

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
};

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 4, this.length);

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
};

Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {
  offset = offset >>> 0;
  validateNumber(offset, 'offset');
  const first = this[offset];
  const last = this[offset + 7];
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8);
  }

  const val = this[offset + 4] +
    this[offset + 5] * 2 ** 8 +
    this[offset + 6] * 2 ** 16 +
    (last << 24); // Overflow

  return (BigInt(val) << BigInt(32)) +
    BigInt(first +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 24)
});

Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {
  offset = offset >>> 0;
  validateNumber(offset, 'offset');
  const first = this[offset];
  const last = this[offset + 7];
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8);
  }

  const val = (first << 24) + // Overflow
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    this[++offset];

  return (BigInt(val) << BigInt(32)) +
    BigInt(this[++offset] * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    last)
});

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 4, this.length);
  return ieee754$1.read(this, offset, true, 23, 4)
};

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 4, this.length);
  return ieee754$1.read(this, offset, false, 23, 4)
};

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 8, this.length);
  return ieee754$1.read(this, offset, true, 52, 8)
};

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0;
  if (!noAssert) checkOffset(offset, 8, this.length);
  return ieee754$1.read(this, offset, false, 52, 8)
};

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUintLE =
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value;
  offset = offset >>> 0;
  byteLength = byteLength >>> 0;
  if (!noAssert) {
    const maxBytes = Math.pow(2, 8 * byteLength) - 1;
    checkInt(this, value, offset, byteLength, maxBytes, 0);
  }

  let mul = 1;
  let i = 0;
  this[offset] = value & 0xFF;
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF;
  }

  return offset + byteLength
};

Buffer.prototype.writeUintBE =
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value;
  offset = offset >>> 0;
  byteLength = byteLength >>> 0;
  if (!noAssert) {
    const maxBytes = Math.pow(2, 8 * byteLength) - 1;
    checkInt(this, value, offset, byteLength, maxBytes, 0);
  }

  let i = byteLength - 1;
  let mul = 1;
  this[offset + i] = value & 0xFF;
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF;
  }

  return offset + byteLength
};

Buffer.prototype.writeUint8 =
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  this[offset] = (value & 0xff);
  return offset + 1
};

Buffer.prototype.writeUint16LE =
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  this[offset] = (value & 0xff);
  this[offset + 1] = (value >>> 8);
  return offset + 2
};

Buffer.prototype.writeUint16BE =
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  this[offset] = (value >>> 8);
  this[offset + 1] = (value & 0xff);
  return offset + 2
};

Buffer.prototype.writeUint32LE =
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  this[offset + 3] = (value >>> 24);
  this[offset + 2] = (value >>> 16);
  this[offset + 1] = (value >>> 8);
  this[offset] = (value & 0xff);
  return offset + 4
};

Buffer.prototype.writeUint32BE =
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  this[offset] = (value >>> 24);
  this[offset + 1] = (value >>> 16);
  this[offset + 2] = (value >>> 8);
  this[offset + 3] = (value & 0xff);
  return offset + 4
};

function wrtBigUInt64LE (buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7);

  let lo = Number(value & BigInt(0xffffffff));
  buf[offset++] = lo;
  lo = lo >> 8;
  buf[offset++] = lo;
  lo = lo >> 8;
  buf[offset++] = lo;
  lo = lo >> 8;
  buf[offset++] = lo;
  let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));
  buf[offset++] = hi;
  hi = hi >> 8;
  buf[offset++] = hi;
  hi = hi >> 8;
  buf[offset++] = hi;
  hi = hi >> 8;
  buf[offset++] = hi;
  return offset
}

function wrtBigUInt64BE (buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7);

  let lo = Number(value & BigInt(0xffffffff));
  buf[offset + 7] = lo;
  lo = lo >> 8;
  buf[offset + 6] = lo;
  lo = lo >> 8;
  buf[offset + 5] = lo;
  lo = lo >> 8;
  buf[offset + 4] = lo;
  let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));
  buf[offset + 3] = hi;
  hi = hi >> 8;
  buf[offset + 2] = hi;
  hi = hi >> 8;
  buf[offset + 1] = hi;
  hi = hi >> 8;
  buf[offset] = hi;
  return offset + 8
}

Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {
  return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
});

Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {
  return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
});

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) {
    const limit = Math.pow(2, (8 * byteLength) - 1);

    checkInt(this, value, offset, byteLength, limit - 1, -limit);
  }

  let i = 0;
  let mul = 1;
  let sub = 0;
  this[offset] = value & 0xFF;
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  }

  return offset + byteLength
};

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) {
    const limit = Math.pow(2, (8 * byteLength) - 1);

    checkInt(this, value, offset, byteLength, limit - 1, -limit);
  }

  let i = byteLength - 1;
  let mul = 1;
  let sub = 0;
  this[offset + i] = value & 0xFF;
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  }

  return offset + byteLength
};

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  if (value < 0) value = 0xff + value + 1;
  this[offset] = (value & 0xff);
  return offset + 1
};

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  this[offset] = (value & 0xff);
  this[offset + 1] = (value >>> 8);
  return offset + 2
};

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  this[offset] = (value >>> 8);
  this[offset + 1] = (value & 0xff);
  return offset + 2
};

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  this[offset] = (value & 0xff);
  this[offset + 1] = (value >>> 8);
  this[offset + 2] = (value >>> 16);
  this[offset + 3] = (value >>> 24);
  return offset + 4
};

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  if (value < 0) value = 0xffffffff + value + 1;
  this[offset] = (value >>> 24);
  this[offset + 1] = (value >>> 16);
  this[offset + 2] = (value >>> 8);
  this[offset + 3] = (value & 0xff);
  return offset + 4
};

Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {
  return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
});

Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {
  return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
});

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4);
  }
  ieee754$1.write(buf, value, offset, littleEndian, 23, 4);
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
};

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
};

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value;
  offset = offset >>> 0;
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8);
  }
  ieee754$1.write(buf, value, offset, littleEndian, 52, 8);
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
};

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
};

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0;
  if (!end && end !== 0) end = this.length;
  if (targetStart >= target.length) targetStart = target.length;
  if (!targetStart) targetStart = 0;
  if (end > 0 && end < start) end = start;

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length;
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start;
  }

  const len = end - start;

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end);
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    );
  }

  return len
};

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start;
      start = 0;
      end = this.length;
    } else if (typeof end === 'string') {
      encoding = end;
      end = this.length;
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      const code = val.charCodeAt(0);
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code;
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255;
  } else if (typeof val === 'boolean') {
    val = Number(val);
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0;
  end = end === undefined ? this.length : end >>> 0;

  if (!val) val = 0;

  let i;
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val;
    }
  } else {
    const bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding);
    const len = bytes.length;
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len];
    }
  }

  return this
};

// CUSTOM ERRORS
// =============

// Simplified versions from Node, changed for Buffer-only usage
const errors = {};
function E (sym, getMessage, Base) {
  errors[sym] = class NodeError extends Base {
    constructor () {
      super();

      Object.defineProperty(this, 'message', {
        value: getMessage.apply(this, arguments),
        writable: true,
        configurable: true
      });

      // Add the error code to the name to include it in the stack trace.
      this.name = `${this.name} [${sym}]`;
      // Access the stack to generate the error message including the error code
      // from the name.
      this.stack; // eslint-disable-line no-unused-expressions
      // Reset the name to the actual name.
      delete this.name;
    }

    get code () {
      return sym
    }

    set code (value) {
      Object.defineProperty(this, 'code', {
        configurable: true,
        enumerable: true,
        value,
        writable: true
      });
    }

    toString () {
      return `${this.name} [${sym}]: ${this.message}`
    }
  };
}

E('ERR_BUFFER_OUT_OF_BOUNDS',
  function (name) {
    if (name) {
      return `${name} is outside of buffer bounds`
    }

    return 'Attempt to access memory outside buffer bounds'
  }, RangeError);
E('ERR_INVALID_ARG_TYPE',
  function (name, actual) {
    return `The "${name}" argument must be of type number. Received type ${typeof actual}`
  }, TypeError);
E('ERR_OUT_OF_RANGE',
  function (str, range, input) {
    let msg = `The value of "${str}" is out of range.`;
    let received = input;
    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
      received = addNumericalSeparator(String(input));
    } else if (typeof input === 'bigint') {
      received = String(input);
      if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
        received = addNumericalSeparator(received);
      }
      received += 'n';
    }
    msg += ` It must be ${range}. Received ${received}`;
    return msg
  }, RangeError);

function addNumericalSeparator (val) {
  let res = '';
  let i = val.length;
  const start = val[0] === '-' ? 1 : 0;
  for (; i >= start + 4; i -= 3) {
    res = `_${val.slice(i - 3, i)}${res}`;
  }
  return `${val.slice(0, i)}${res}`
}

// CHECK FUNCTIONS
// ===============

function checkBounds (buf, offset, byteLength) {
  validateNumber(offset, 'offset');
  if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
    boundsError(offset, buf.length - (byteLength + 1));
  }
}

function checkIntBI (value, min, max, buf, offset, byteLength) {
  if (value > max || value < min) {
    const n = typeof min === 'bigint' ? 'n' : '';
    let range;
    if (byteLength > 3) {
      if (min === 0 || min === BigInt(0)) {
        range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;
      } else {
        range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
                `${(byteLength + 1) * 8 - 1}${n}`;
      }
    } else {
      range = `>= ${min}${n} and <= ${max}${n}`;
    }
    throw new errors.ERR_OUT_OF_RANGE('value', range, value)
  }
  checkBounds(buf, offset, byteLength);
}

function validateNumber (value, name) {
  if (typeof value !== 'number') {
    throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
  }
}

function boundsError (value, length, type) {
  if (Math.floor(value) !== value) {
    validateNumber(value, type);
    throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)
  }

  if (length < 0) {
    throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
  }

  throw new errors.ERR_OUT_OF_RANGE(type || 'offset',
                                    `>= ${type ? 1 : 0} and <= ${length}`,
                                    value)
}

// HELPER FUNCTIONS
// ================

const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0];
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '');
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '=';
  }
  return str
}

function utf8ToBytes (string, units) {
  units = units || Infinity;
  let codePoint;
  const length = string.length;
  let leadSurrogate = null;
  const bytes = [];

  for (let i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i);

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
          continue
        }

        // valid lead
        leadSurrogate = codePoint;

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
        leadSurrogate = codePoint;
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
    }

    leadSurrogate = null;

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint);
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      );
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      );
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      );
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  const byteArray = [];
  for (let i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF);
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  let c, hi, lo;
  const byteArray = [];
  for (let i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i);
    hi = c >> 8;
    lo = c % 256;
    byteArray.push(lo);
    byteArray.push(hi);
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  let i;
  for (i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i];
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
const hexSliceLookupTable = (function () {
  const alphabet = '0123456789abcdef';
  const table = new Array(256);
  for (let i = 0; i < 16; ++i) {
    const i16 = i * 16;
    for (let j = 0; j < 16; ++j) {
      table[i16 + j] = alphabet[i] + alphabet[j];
    }
  }
  return table
})();

// Return not function with Error if BigInt not supported
function defineBigIntMethod (fn) {
  return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
}

function BufferBigIntNotDefined () {
  throw new Error('BigInt not supported')
}
}(buffer));

var buf = {};

var baseBuf = {};

/**
 * 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$u = (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 __());
    };
})();
Object.defineProperty(baseBuf, "__esModule", { value: true });
/**
 * 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 = /** @class */ (function () {
    /**
     * Create a instance with the injected size.
     * @constructor
     * @param {Integer} size
     */
    function BaseBuffer(size) {
        this.position = 0;
        this.length = size;
    }
    BaseBuffer.prototype.getUInt8 = function (position) {
        throw new Error('Not implemented');
    };
    BaseBuffer.prototype.getInt8 = function (position) {
        throw new Error('Not implemented');
    };
    BaseBuffer.prototype.getFloat64 = function (position) {
        throw new Error('Not implemented');
    };
    BaseBuffer.prototype.getVarInt = function (position) {
        throw new Error('Not implemented');
    };
    BaseBuffer.prototype.putUInt8 = function (position, val) {
        throw new Error('Not implemented');
    };
    BaseBuffer.prototype.putInt8 = function (position, val) {
        throw new Error('Not implemented');
    };
    BaseBuffer.prototype.putFloat64 = function (position, val) {
        throw new Error('Not implemented');
    };
    /**
     * @param p
     */
    BaseBuffer.prototype.getInt16 = function (p) {
        return (this.getInt8(p) << 8) | this.getUInt8(p + 1);
    };
    /**
     * @param p
     */
    BaseBuffer.prototype.getUInt16 = function (p) {
        return (this.getUInt8(p) << 8) | this.getUInt8(p + 1);
    };
    /**
     * @param p
     */
    BaseBuffer.prototype.getInt32 = function (p) {
        return ((this.getInt8(p) << 24) |
            (this.getUInt8(p + 1) << 16) |
            (this.getUInt8(p + 2) << 8) |
            this.getUInt8(p + 3));
    };
    /**
     * @param p
     */
    BaseBuffer.prototype.getUInt32 = function (p) {
        return ((this.getUInt8(p) << 24) |
            (this.getUInt8(p + 1) << 16) |
            (this.getUInt8(p + 2) << 8) |
            this.getUInt8(p + 3));
    };
    /**
     * @param p
     */
    BaseBuffer.prototype.getInt64 = function (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
     */
    BaseBuffer.prototype.getSlice = function (start, length) {
        return new SliceBuffer(start, length, this);
    };
    /**
     * @param p
     * @param val
     */
    BaseBuffer.prototype.putInt16 = function (p, val) {
        this.putInt8(p, val >> 8);
        this.putUInt8(p + 1, val & 0xff);
    };
    /**
     * @param p
     * @param val
     */
    BaseBuffer.prototype.putUInt16 = function (p, val) {
        this.putUInt8(p, (val >> 8) & 0xff);
        this.putUInt8(p + 1, val & 0xff);
    };
    /**
     * @param p
     * @param val
     */
    BaseBuffer.prototype.putInt32 = function (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
     */
    BaseBuffer.prototype.putUInt32 = function (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
     */
    BaseBuffer.prototype.putInt64 = function (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);
    };
    BaseBuffer.prototype.putVarInt = function (p, val) {
        var length = 0;
        while (val > 1) {
            var int = val % 128;
            if (val >= 128) {
                int += 128;
            }
            val = val / 128;
            this.putUInt8(p + length, int);
            length += 1;
        }
        return length;
    };
    /**
     * @param position
     * @param other
     */
    BaseBuffer.prototype.putBytes = function (position, other) {
        for (var i = 0, end = other.remaining(); i < end; i++) {
            this.putUInt8(position + i, other.readUInt8());
        }
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readUInt8 = function () {
        return this.getUInt8(this._updatePos(1));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readInt8 = function () {
        return this.getInt8(this._updatePos(1));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readUInt16 = function () {
        return this.getUInt16(this._updatePos(2));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readUInt32 = function () {
        return this.getUInt32(this._updatePos(4));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readInt16 = function () {
        return this.getInt16(this._updatePos(2));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readInt32 = function () {
        return this.getInt32(this._updatePos(4));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readInt64 = function () {
        return this.getInt32(this._updatePos(8));
    };
    /**
     * Read from state position.
     */
    BaseBuffer.prototype.readFloat64 = function () {
        return this.getFloat64(this._updatePos(8));
    };
    /**
     * Read from state position
     */
    BaseBuffer.prototype.readVarInt = function () {
        var int = this.getVarInt(this.position);
        this._updatePos(int.length);
        return int.value;
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeUInt8 = function (val) {
        this.putUInt8(this._updatePos(1), val);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeInt8 = function (val) {
        this.putInt8(this._updatePos(1), val);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeInt16 = function (val) {
        this.putInt16(this._updatePos(2), val);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeInt32 = function (val) {
        this.putInt32(this._updatePos(4), val);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeUInt32 = function (val) {
        this.putUInt32(this._updatePos(4), val);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeInt64 = function (val) {
        this.putInt64(this._updatePos(8), val);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeFloat64 = function (val) {
        this.putFloat64(this._updatePos(8), val);
    };
    BaseBuffer.prototype.writeVarInt = function (val) {
        var length = this.putVarInt(this.position, val);
        this._updatePos(length);
    };
    /**
     * Write to state position.
     * @param val
     */
    BaseBuffer.prototype.writeBytes = function (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
     */
    BaseBuffer.prototype.readSlice = function (length) {
        return this.getSlice(this._updatePos(length), length);
    };
    BaseBuffer.prototype._updatePos = function (length) {
        var p = this.position;
        this.position += length;
        return p;
    };
    /**
     * Get remaining
     */
    BaseBuffer.prototype.remaining = function () {
        return this.length - this.position;
    };
    /**
     * Has remaining
     */
    BaseBuffer.prototype.hasRemaining = function () {
        return this.remaining() > 0;
    };
    /**
     * Reset position state
     */
    BaseBuffer.prototype.reset = function () {
        this.position = 0;
    };
    /**
     * Get string representation of buffer and it's state.
     * @return {string} Buffer as a string
     */
    BaseBuffer.prototype.toString = function () {
        return (this.constructor.name +
            '( position=' +
            this.position +
            ' )\n  ' +
            this.toHex());
    };
    /**
     * Get string representation of buffer.
     * @return {string} Buffer as a string
     */
    BaseBuffer.prototype.toHex = function () {
        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;
            if (i !== this.length - 1) {
                out += ' ';
            }
        }
        return out;
    };
    return BaseBuffer;
}());
baseBuf.default = BaseBuffer;
/**
 * Represents a view as slice of another buffer.
 * @access private
 */
var SliceBuffer = /** @class */ (function (_super) {
    __extends$u(SliceBuffer, _super);
    function SliceBuffer(start, length, inner) {
        var _this = _super.call(this, length) || this;
        _this._start = start;
        _this._inner = inner;
        return _this;
    }
    SliceBuffer.prototype.putUInt8 = function (position, val) {
        this._inner.putUInt8(this._start + position, val);
    };
    SliceBuffer.prototype.getUInt8 = function (position) {
        return this._inner.getUInt8(this._start + position);
    };
    SliceBuffer.prototype.putInt8 = function (position, val) {
        this._inner.putInt8(this._start + position, val);
    };
    SliceBuffer.prototype.putFloat64 = function (position, val) {
        this._inner.putFloat64(this._start + position, val);
    };
    SliceBuffer.prototype.getInt8 = function (position) {
        return this._inner.getInt8(this._start + position);
    };
    SliceBuffer.prototype.getFloat64 = function (position) {
        return this._inner.getFloat64(this._start + position);
    };
    return SliceBuffer;
}(BaseBuffer));

/**
 * 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 __importDefault$N = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(buf, "__esModule", { value: true });
buf.BaseBuffer = void 0;
var base_buf_1$1 = __importDefault$N(baseBuf);
buf.BaseBuffer = base_buf_1$1.default;
buf.default = base_buf_1$1.default;

/**
 * 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$t = (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 __importDefault$M = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(channelBuf, "__esModule", { value: true });
channelBuf.alloc = alloc;
var buffer_1$1 = __importDefault$M(buffer);
var buf_1$1 = __importDefault$M(buf);
var ChannelBuffer = /** @class */ (function (_super) {
    __extends$t(ChannelBuffer, _super);
    function ChannelBuffer(arg) {
        var _this = this;
        var buffer = newChannelJSBuffer(arg);
        _this = _super.call(this, buffer.length) || this;
        _this._buffer = buffer;
        return _this;
    }
    ChannelBuffer.prototype.getUInt8 = function (position) {
        return this._buffer.readUInt8(position);
    };
    ChannelBuffer.prototype.getInt8 = function (position) {
        return this._buffer.readInt8(position);
    };
    ChannelBuffer.prototype.getFloat64 = function (position) {
        return this._buffer.readDoubleBE(position);
    };
    ChannelBuffer.prototype.getVarInt = function (position) {
        var i = 0;
        var currentValue = this._buffer.readInt8(position + i);
        var total = currentValue % 128;
        while (currentValue / 128 >= 1) {
            i += 1;
            currentValue = this._buffer.readInt8(position + i);
            total += currentValue % 128;
        }
        return { length: i + 1, value: total };
    };
    ChannelBuffer.prototype.putUInt8 = function (position, val) {
        this._buffer.writeUInt8(val, position);
    };
    ChannelBuffer.prototype.putInt8 = function (position, val) {
        this._buffer.writeInt8(val, position);
    };
    ChannelBuffer.prototype.putFloat64 = function (position, val) {
        this._buffer.writeDoubleBE(val, position);
    };
    ChannelBuffer.prototype.putBytes = function (position, val) {
        if (val instanceof ChannelBuffer) {
            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 {
            _super.prototype.putBytes.call(this, position, val);
        }
    };
    ChannelBuffer.prototype.getSlice = function (start, length) {
        return new ChannelBuffer(this._buffer.slice(start, start + length));
    };
    return ChannelBuffer;
}(buf_1$1.default));
channelBuf.default = ChannelBuffer;
/**
 * Allocate a buffer
 *
 * @param {number} size The buffer sizzer
 * @returns {BaseBuffer} The buffer
 */
function alloc(size) {
    return new ChannelBuffer(size);
}
function newChannelJSBuffer(arg) {
    if (arg instanceof buffer_1$1.default.Buffer) {
        return arg;
    }
    else if (typeof arg === 'number' &&
        typeof buffer_1$1.default.Buffer.alloc === 'function') {
        // use static factory function present in newer NodeJS versions to allocate new buffer with specified size
        return buffer_1$1.default.Buffer.alloc(arg);
    }
    else {
        // fallback to the old, potentially deprecated constructor
        // eslint-disable-next-line n/no-deprecated-api
        return new buffer_1$1.default.Buffer(arg);
    }
}

var __importDefault$L = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(browserChannel, "__esModule", { value: true });
/**
 * 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-env browser */
var channel_buf_1$3 = __importDefault$L(channelBuf);
var neo4j_driver_core_1$I = lib$1;
var _a$e = neo4j_driver_core_1$I.internal.util, ENCRYPTION_OFF$1 = _a$e.ENCRYPTION_OFF, ENCRYPTION_ON$1 = _a$e.ENCRYPTION_ON;
var WS_OPEN = 1;
var WS_CLOSED = 3;
/**
 * Create a new WebSocketChannel to be used in web browsers.
 * @access private
 */
var WebSocketChannel = /** @class */ (function () {
    /**
     * Create new instance
     * @param {ChannelConfig} config - configuration for this channel.
     * @param {function(): string} protocolSupplier - function that detects protocol of the web page. Should only be used in tests.
     */
    function WebSocketChannel(config, protocolSupplier, socketFactory) {
        if (protocolSupplier === void 0) { protocolSupplier = detectWebPageProtocol; }
        if (socketFactory === void 0) { socketFactory = function (url) { return new WebSocket(url); }; }
        var _this = this;
        this._open = true;
        this._pending = [];
        this._error = null;
        this._handleConnectionError = this._handleConnectionError.bind(this);
        this._config = config;
        this._receiveTimeout = null;
        this._receiveTimeoutStarted = false;
        this._receiveTimeoutId = null;
        this._closingPromise = null;
        var _a = determineWebSocketScheme(config, protocolSupplier), scheme = _a.scheme, error = _a.error;
        if (error) {
            this._error = error;
            return;
        }
        this._ws = createWebSocket(scheme, config.address, socketFactory);
        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 && !e.wasClean) {
                self._handleConnectionError();
            }
            self._open = false;
        };
        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) {
            _this._resetTimeout();
            if (self.onmessage) {
                var b = new channel_buf_1$3.default(event.data);
                self.onmessage(b);
            }
        };
        this._ws.onerror = this._handleConnectionError;
        this._connectionTimeoutFired = false;
        this._connectionTimeoutId = this._setupConnectionTimeout();
    }
    WebSocketChannel.prototype._handleConnectionError = function () {
        if (this._connectionTimeoutFired) {
            // timeout fired - not connected within configured time
            this._error = (0, neo4j_driver_core_1$I.newError)("Failed to establish connection in ".concat(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 && !this._timedout) {
            // http://stackoverflow.com/questions/25779831/how-to-catch-websocket-connection-to-ws-xxxnn-failed-connection-closed-be
            this._error = (0, neo4j_driver_core_1$I.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);
            }
        }
    };
    /**
     * Write the passed in buffer to connection
     * @param {ChannelBuffer} buffer - Buffer to write
     */
    WebSocketChannel.prototype.write = function (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 channel_buf_1$3.default) {
            try {
                this._ws.send(buffer._buffer);
            }
            catch (error) {
                if (this._ws.readyState !== WS_OPEN) {
                    // Websocket has been closed
                    this._handleConnectionError();
                }
                else {
                    // Some other error occured
                    throw (0, neo4j_driver_core_1$I.newError)('unexpected failure to write.', undefined, error);
                }
            }
        }
        else {
            throw (0, neo4j_driver_core_1$I.newError)("Don't know how to send buffer: " + buffer);
        }
    };
    /**
     * Close the connection
     * @returns {Promise} A promise that will be resolved after channel is closed
     */
    WebSocketChannel.prototype.close = function () {
        var _this = this;
        if (this._closingPromise === null) {
            this._closingPromise = new Promise(function (resolve, reject) {
                _this._clearConnectionTimeout();
                if (_this._ws && _this._ws.readyState !== WS_CLOSED) {
                    _this._open = false;
                    _this.stopReceiveTimeout();
                    _this._ws.onclose = function () {
                        resolve();
                    };
                    _this._ws.close();
                }
                else {
                    resolve();
                }
            });
        }
        return this._closingPromise;
    };
    /**
     * Setup the receive timeout for the channel.
     *
     * Not supported for the browser channel.
     *
     * @param {number} receiveTimeout The amount of time the channel will keep without receive any data before timeout (ms)
     * @returns {void}
     */
    WebSocketChannel.prototype.setupReceiveTimeout = function (receiveTimeout) {
        this._receiveTimeout = receiveTimeout;
    };
    /**
     * Stops the receive timeout for the channel.
     */
    WebSocketChannel.prototype.stopReceiveTimeout = function () {
        if (this._receiveTimeout !== null && this._receiveTimeoutStarted) {
            this._receiveTimeoutStarted = false;
            if (this._receiveTimeoutId != null) {
                clearTimeout(this._receiveTimeoutId);
            }
            this._receiveTimeoutId = null;
        }
    };
    /**
     * Start the receive timeout for the channel.
     */
    WebSocketChannel.prototype.startReceiveTimeout = function () {
        if (this._open && this._receiveTimeout !== null && !this._receiveTimeoutStarted) {
            this._receiveTimeoutStarted = true;
            this._resetTimeout();
        }
    };
    WebSocketChannel.prototype._resetTimeout = function () {
        var _this = this;
        if (!this._receiveTimeoutStarted) {
            return;
        }
        if (this._receiveTimeoutId !== null) {
            clearTimeout(this._receiveTimeoutId);
        }
        this._receiveTimeoutId = setTimeout(function () {
            _this._receiveTimeoutId = null;
            _this._timedout = true;
            _this.stopReceiveTimeout();
            _this._error = (0, neo4j_driver_core_1$I.newError)("Connection lost. Server didn't respond in ".concat(_this._receiveTimeout, "ms"), _this._config.connectionErrorCode);
            _this.close();
            if (_this.onerror) {
                _this.onerror(_this._error);
            }
        }, this._receiveTimeout);
    };
    /**
     * Set connection timeout on the given WebSocket, if configured.
     * @return {number} the timeout id or null.
     * @private
     */
    WebSocketChannel.prototype._setupConnectionTimeout = function () {
        var _this = this;
        var timeout = this._config.connectionTimeout;
        if (timeout) {
            var webSocket_1 = this._ws;
            return setTimeout(function () {
                if (webSocket_1.readyState !== WS_OPEN) {
                    _this._connectionTimeoutFired = true;
                    webSocket_1.close();
                }
            }, timeout);
        }
        return null;
    };
    /**
     * Remove active connection timeout, if any.
     * @private
     */
    WebSocketChannel.prototype._clearConnectionTimeout = function () {
        var timeoutId = this._connectionTimeoutId;
        if (timeoutId || timeoutId === 0) {
            this._connectionTimeoutFired = false;
            this._connectionTimeoutId = null;
            clearTimeout(timeoutId);
        }
    };
    return WebSocketChannel;
}());
browserChannel.default = WebSocketChannel;
function createWebSocket(scheme, address, socketFactory) {
    var url = scheme + '://' + address.asHostPort();
    try {
        return socketFactory(url);
    }
    catch (error) {
        if (isIPv6AddressIssueOnWindows(error, address)) {
            // 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, address);
            return socketFactory(windowsFriendlyUrl);
        }
        else {
            throw error;
        }
    }
}
function isIPv6AddressIssueOnWindows(error, address) {
    return error.name === 'SyntaxError' && isIPv6Address(address.asHostPort());
}
function isIPv6Address(hostAndPort) {
    return hostAndPort.charAt(0) === '[' && hostAndPort.indexOf(']') !== -1;
}
function asWindowsFriendlyIPv6Address(scheme, address) {
    // replace all ':' with '-'
    var hostWithoutColons = address.host().replace(/:/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 "".concat(scheme, "://").concat(ipv6Host, ":").concat(address.port());
}
/**
 * @param {ChannelConfig} config - configuration for the channel.
 * @param {function(): string} protocolSupplier - function that detects protocol of the web page.
 * @return {{scheme: string|null, error: Neo4jError|null}} object containing either scheme or error.
 */
function determineWebSocketScheme(config, protocolSupplier) {
    var encryptionOn = isEncryptionExplicitlyTurnedOn(config);
    var encryptionOff = isEncryptionExplicitlyTurnedOff(config);
    var trust = config.trust;
    var secureProtocol = isProtocolSecure(protocolSupplier);
    verifyEncryptionSettings(encryptionOn, encryptionOff, secureProtocol);
    if (encryptionOff) {
        // encryption explicitly turned off in the config
        return { scheme: 'ws', error: null };
    }
    if (secureProtocol) {
        // driver is used in a secure https web page, use 'wss'
        return { scheme: 'wss', error: null };
    }
    if (encryptionOn) {
        // encryption explicitly requested in the config
        if (!trust || trust === 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES') {
            // trust strategy not specified or the only supported strategy is specified
            return { scheme: 'wss', error: null };
        }
        else {
            var error = (0, neo4j_driver_core_1$I.newError)('The browser version of this driver only supports one trust ' +
                "strategy, 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'. " +
                trust +
                ' is not supported. Please ' +
                'either use TRUST_SYSTEM_CA_SIGNED_CERTIFICATES or disable encryption by setting ' +
                '`encrypted:"' +
                ENCRYPTION_OFF$1 +
                '"` in the driver configuration.');
            return { scheme: null, error: error };
        }
    }
    // default to unencrypted web socket
    return { scheme: 'ws', error: null };
}
/**
 * @param {ChannelConfig} config - configuration for the channel.
 * @return {boolean} `true` if encryption enabled in the config, `false` otherwise.
 */
function isEncryptionExplicitlyTurnedOn(config) {
    return config.encrypted === true || config.encrypted === ENCRYPTION_ON$1;
}
/**
 * @param {ChannelConfig} config - configuration for the channel.
 * @return {boolean} `true` if encryption disabled in the config, `false` otherwise.
 */
function isEncryptionExplicitlyTurnedOff(config) {
    return config.encrypted === false || config.encrypted === ENCRYPTION_OFF$1;
}
/**
 * @param {function(): string} protocolSupplier - function that detects protocol of the web page.
 * @return {boolean} `true` if protocol returned by the given function is secure, `false` otherwise.
 */
function isProtocolSecure(protocolSupplier) {
    var protocol = typeof protocolSupplier === 'function' ? protocolSupplier() : '';
    return protocol && protocol.toLowerCase().indexOf('https') >= 0;
}
function verifyEncryptionSettings(encryptionOn, encryptionOff, secureProtocol) {
    if (secureProtocol === null) ;
    else if (encryptionOn && !secureProtocol) {
        // encryption explicitly turned on for a driver used on a HTTP web page
        console.warn('Neo4j driver is configured to use secure WebSocket on a HTTP web page. ' +
            'WebSockets might not work in a mixed content environment. ' +
            'Please consider configuring driver to not use encryption.');
    }
    else if (encryptionOff && secureProtocol) {
        // encryption explicitly turned off for a driver used on a HTTPS web page
        console.warn('Neo4j driver is configured to use insecure WebSocket on a HTTPS web page. ' +
            'WebSockets might not work in a mixed content environment. ' +
            'Please consider configuring driver to use encryption.');
    }
}
function detectWebPageProtocol() {
    return typeof window !== 'undefined' && window.location
        ? window.location.protocol
        : null;
}

var browserHostNameResolver = {};

/**
 * 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$s = (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 __());
    };
})();
Object.defineProperty(browserHostNameResolver, "__esModule", { value: true });
var neo4j_driver_core_1$H = lib$1;
var BaseHostNameResolver = neo4j_driver_core_1$H.internal.resolver.BaseHostNameResolver;
var BrowserHostNameResolver = /** @class */ (function (_super) {
    __extends$s(BrowserHostNameResolver, _super);
    function BrowserHostNameResolver() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BrowserHostNameResolver.prototype.resolve = function (address) {
        return this._resolveToItself(address);
    };
    return BrowserHostNameResolver;
}(BaseHostNameResolver));
browserHostNameResolver.default = BrowserHostNameResolver;

var browserClientCertificatesLoader = {};

var __awaiter$7 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$7 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(browserClientCertificatesLoader, "__esModule", { value: true });
/**
 * 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.
 */
browserClientCertificatesLoader.default = {
    load: function (clientCertificate) {
        return __awaiter$7(this, void 0, void 0, function () {
            return __generator$7(this, function (_a) {
                return [2 /*return*/, clientCertificate];
            });
        });
    }
};

/**
 * 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 __importDefault$K = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(browser, "__esModule", { value: true });
browser.ClientCertificatesLoader = browser.HostNameResolver = browser.Channel = void 0;
var browser_channel_1 = __importDefault$K(browserChannel);
var browser_host_name_resolver_1 = __importDefault$K(browserHostNameResolver);
var browser_client_certificates_loader_1 = __importDefault$K(browserClientCertificatesLoader);
/*

This module exports a set of components to be used in browser environment.
They are not compatible with NodeJS environment.
All files import/require APIs from `node/index.js` by default.
Such imports are replaced at build time with `browser/index.js` when building a browser bundle.

NOTE: exports in this module should have exactly the same names/structure as exports in `node/index.js`.

 */
browser.Channel = browser_channel_1.default;
browser.HostNameResolver = browser_host_name_resolver_1.default;
browser.ClientCertificatesLoader = browser_client_certificates_loader_1.default;

var chunking = {};

var combinedBuf = {};

/**
 * 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 __());
    };
})();
Object.defineProperty(combinedBuf, "__esModule", { value: true });
var buf_1 = buf;
var channel_buf_1$2 = channelBuf;
/**
 * Buffer that combines multiple buffers, exposing them as one single buffer.
 */
var CombinedBuffer = /** @class */ (function (_super) {
    __extends$r(CombinedBuffer, _super);
    function CombinedBuffer(buffers) {
        var _this = this;
        var length = 0;
        for (var i = 0; i < buffers.length; i++) {
            length += buffers[i].length;
        }
        _this = _super.call(this, length) || this;
        _this._buffers = buffers;
        return _this;
    }
    CombinedBuffer.prototype.getUInt8 = function (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);
            }
        }
    };
    CombinedBuffer.prototype.getInt8 = function (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);
            }
        }
    };
    CombinedBuffer.prototype.getFloat64 = function (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 = (0, channel_buf_1$2.alloc)(8);
        for (var i = 0; i < 8; i++) {
            b.putUInt8(i, this.getUInt8(position + i));
        }
        return b.getFloat64(0);
    };
    return CombinedBuffer;
}(buf_1.BaseBuffer));
combinedBuf.default = CombinedBuffer;

/**
 * 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$q = (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 __importDefault$J = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(chunking, "__esModule", { value: true });
chunking.Dechunker = chunking.Chunker = void 0;
var base_buf_1 = __importDefault$J(baseBuf);
var channel_buf_1$1 = channelBuf;
var combined_buf_1 = __importDefault$J(combinedBuf);
var _CHUNK_HEADER_SIZE = 2;
var _MESSAGE_BOUNDARY = 0x00;
var _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
 */
var Chunker = /** @class */ (function (_super) {
    __extends$q(Chunker, _super);
    function Chunker(channel, bufferSize) {
        var _this = _super.call(this, 0) || this;
        _this._bufferSize = bufferSize || _DEFAULT_BUFFER_SIZE;
        _this._ch = channel;
        _this._buffer = (0, channel_buf_1$1.alloc)(_this._bufferSize);
        _this._currentChunkStart = 0;
        _this._chunkOpen = false;
        return _this;
    }
    Chunker.prototype.putUInt8 = function (position, val) {
        this._ensure(1);
        this._buffer.writeUInt8(val);
    };
    Chunker.prototype.putInt8 = function (position, val) {
        this._ensure(1);
        this._buffer.writeInt8(val);
    };
    Chunker.prototype.putFloat64 = function (position, val) {
        this._ensure(8);
        this._buffer.writeFloat64(val);
    };
    Chunker.prototype.putBytes = function (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;
    };
    Chunker.prototype.flush = function () {
        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, channel_buf_1$1.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
     */
    Chunker.prototype.messageBoundary = function () {
        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 */
    Chunker.prototype._ensure = function (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;
        }
    };
    Chunker.prototype._closeChunkIfOpen = function () {
        if (this._chunkOpen) {
            var chunkSize = this._buffer.position - (this._currentChunkStart + _CHUNK_HEADER_SIZE);
            this._buffer.putUInt16(this._currentChunkStart, chunkSize);
            this._chunkOpen = false;
        }
    };
    return Chunker;
}(base_buf_1.default));
chunking.Chunker = Chunker;
/**
 * Combines chunks until a complete message is gathered up, and then forwards that
 * message to an 'onmessage' listener.
 * @access private
 */
var Dechunker = /** @class */ (function () {
    function Dechunker() {
        this._currentMessage = [];
        this._partialChunkHeader = 0;
        this._state = this.AWAITING_CHUNK;
    }
    Dechunker.prototype.AWAITING_CHUNK = function (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;
        }
    };
    Dechunker.prototype.IN_HEADER = function (buf) {
        // First header byte read, now we read the next one
        return this._onHeader((this._partialChunkHeader | buf.readUInt8()) & 0xffff);
    };
    Dechunker.prototype.IN_CHUNK = function (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;
        }
    };
    Dechunker.prototype.CLOSED = function (buf) {
        // no-op
    };
    /** Called when a complete chunk header has been received */
    Dechunker.prototype._onHeader = function (header) {
        if (header === 0) {
            // Message boundary
            var message = void 0;
            switch (this._currentMessage.length) {
                case 0:
                    // Keep alive chunk, sent by server to keep network alive.
                    return this.AWAITING_CHUNK;
                case 1:
                    // All data in one chunk, this signals the end of that chunk.
                    message = this._currentMessage[0];
                    break;
                default:
                    // A large chunk of data received, this signals that the last chunk has been received.
                    message = new combined_buf_1.default(this._currentMessage);
                    break;
            }
            this._currentMessage = [];
            this.onmessage(message);
            return this.AWAITING_CHUNK;
        }
        else {
            this._chunkSize = header;
            return this.IN_CHUNK;
        }
    };
    Dechunker.prototype.write = function (buf) {
        while (buf.hasRemaining()) {
            this._state = this._state(buf);
        }
    };
    return Dechunker;
}());
chunking.Dechunker = Dechunker;

var channelConfig = {};

/**
 * 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(channelConfig, "__esModule", { value: true });
var neo4j_driver_core_1$G = lib$1;
var _a$d = neo4j_driver_core_1$G.internal.util, ENCRYPTION_OFF = _a$d.ENCRYPTION_OFF, ENCRYPTION_ON = _a$d.ENCRYPTION_ON;
var SERVICE_UNAVAILABLE$4 = neo4j_driver_core_1$G.error.SERVICE_UNAVAILABLE;
var ALLOWED_VALUES_ENCRYPTED = [
    null,
    undefined,
    true,
    false,
    ENCRYPTION_ON,
    ENCRYPTION_OFF
];
var ALLOWED_VALUES_TRUST = [
    null,
    undefined,
    'TRUST_ALL_CERTIFICATES',
    'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES',
    'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'
];
var ChannelConfig = /** @class */ (function () {
    /**
     * @constructor
     * @param {ServerAddress} address the address 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.
     * @param {object} clientCertificate the client certificate
     */
    function ChannelConfig(address, driverConfig, connectionErrorCode, clientCertificate) {
        this.address = address;
        this.encrypted = extractEncrypted(driverConfig);
        this.trust = extractTrust(driverConfig);
        this.trustedCertificates = extractTrustedCertificates(driverConfig);
        this.knownHostsPath = extractKnownHostsPath(driverConfig);
        this.connectionErrorCode = connectionErrorCode || SERVICE_UNAVAILABLE$4;
        this.connectionTimeout = driverConfig.connectionTimeout;
        this.clientCertificate = clientCertificate;
    }
    return ChannelConfig;
}());
channelConfig.default = ChannelConfig;
function extractEncrypted(driverConfig) {
    var value = driverConfig.encrypted;
    if (ALLOWED_VALUES_ENCRYPTED.indexOf(value) === -1) {
        throw (0, neo4j_driver_core_1$G.newError)("Illegal value of the encrypted setting ".concat(value, ". Expected one of ").concat(ALLOWED_VALUES_ENCRYPTED));
    }
    return value;
}
function extractTrust(driverConfig) {
    var value = driverConfig.trust;
    if (ALLOWED_VALUES_TRUST.indexOf(value) === -1) {
        throw (0, neo4j_driver_core_1$G.newError)("Illegal value of the trust setting ".concat(value, ". Expected one of ").concat(ALLOWED_VALUES_TRUST));
    }
    return value;
}
function extractTrustedCertificates(driverConfig) {
    return driverConfig.trustedCertificates || [];
}
function extractKnownHostsPath(driverConfig) {
    return driverConfig.knownHosts || null;
}

var utf8 = {};

var string_decoder = {};

var safeBuffer = {exports: {}};

/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */

(function (module, exports) {
/* eslint-disable node/no-deprecated-api */
var buffer$1 = buffer;
var Buffer = buffer$1.Buffer;

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key];
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer$1;
} else {
  // Copy properties from require('buffer')
  copyProps(buffer$1, exports);
  exports.Buffer = SafeBuffer;
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.prototype = Object.create(Buffer.prototype);

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer);

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
};

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size);
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding);
    } else {
      buf.fill(fill);
    }
  } else {
    buf.fill(0);
  }
  return buf
};

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
};

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer$1.SlowBuffer(size)
};
}(safeBuffer, safeBuffer.exports));

/*<replacement>*/

var Buffer = safeBuffer.exports.Buffer;
/*</replacement>*/

var isEncoding = Buffer.isEncoding || function (encoding) {
  encoding = '' + encoding;
  switch (encoding && encoding.toLowerCase()) {
    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
      return true;
    default:
      return false;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return 'utf8';
  var retried;
  while (true) {
    switch (enc) {
      case 'utf8':
      case 'utf-8':
        return 'utf8';
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return 'utf16le';
      case 'latin1':
      case 'binary':
        return 'latin1';
      case 'base64':
      case 'ascii':
      case 'hex':
        return enc;
      default:
        if (retried) return; // undefined
        enc = ('' + enc).toLowerCase();
        retried = true;
    }
  }
}
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
string_decoder.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
    case 'utf16le':
      this.text = utf16Text;
      this.end = utf16End;
      nb = 4;
      break;
    case 'utf8':
      this.fillLast = utf8FillLast;
      nb = 4;
      break;
    case 'base64':
      this.text = base64Text;
      this.end = base64End;
      nb = 3;
      break;
    default:
      this.write = simpleWrite;
      this.end = simpleEnd;
      return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
  if (buf.length === 0) return '';
  var r;
  var i;
  if (this.lastNeed) {
    r = this.fillLast(buf);
    if (r === undefined) return '';
    i = this.lastNeed;
    this.lastNeed = 0;
  } else {
    i = 0;
  }
  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  return r || '';
};

StringDecoder.prototype.end = utf8End;

// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;

// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  return byte >> 6 === 0x02 ? -1 : -2;
}

// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}

// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
  if ((buf[0] & 0xC0) !== 0x80) {
    self.lastNeed = 0;
    return '\ufffd';
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if ((buf[1] & 0xC0) !== 0x80) {
      self.lastNeed = 1;
      return '\ufffd';
    }
    if (self.lastNeed > 2 && buf.length > 2) {
      if ((buf[2] & 0xC0) !== 0x80) {
        self.lastNeed = 2;
        return '\ufffd';
      }
    }
  }
}

// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed;
  var r = utf8CheckExtraBytes(this, buf);
  if (r !== undefined) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString('utf8', i);
  this.lastTotal = total;
  var end = buf.length - (total - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString('utf8', i, end);
}

// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString('utf16le', i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 0xD800 && c <= 0xDBFF) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString('utf16le', i, buf.length - 1);
}

// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) {
    var end = this.lastTotal - this.lastNeed;
    return r + this.lastChar.toString('utf16le', 0, end);
  }
  return r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (n === 0) return buf.toString('base64', i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (n === 1) {
    this.lastChar[0] = buf[buf.length - 1];
  } else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString('base64', i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  return r;
}

// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : '';
}

/**
 * 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 __importDefault$I = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(utf8, "__esModule", { value: true });
var channel_buf_1 = __importDefault$I(channelBuf);
var neo4j_driver_core_1$F = lib$1;
var buffer_1 = __importDefault$I(buffer);
var string_decoder_1 = string_decoder;
var decoder = new string_decoder_1.StringDecoder('utf8');
function encode(str) {
    return new channel_buf_1.default(newBuffer(str));
}
function decode(buffer, length) {
    if (Object.prototype.hasOwnProperty.call(buffer, '_buffer')) {
        return decodeChannelBuffer(buffer, length);
    }
    else if (Object.prototype.hasOwnProperty.call(buffer, '_buffers')) {
        return decodeCombinedBuffer(buffer, length);
    }
    else {
        throw (0, neo4j_driver_core_1$F.newError)("Don't know how to decode strings from '".concat(buffer, "'"));
    }
}
function decodeChannelBuffer(buffer, length) {
    var start = buffer.position;
    var end = start + length;
    buffer.position = Math.min(end, buffer.length);
    return buffer._buffer.toString('utf8', start, end);
}
function decodeCombinedBuffer(buffer, length) {
    return streamDecodeCombinedBuffer(buffer, length, function (partBuffer) { return decoder.write(partBuffer._buffer); }, function () { return decoder.end(); });
}
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();
}
function newBuffer(str) {
    // 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
    if (typeof buffer_1.default.Buffer.from === 'function') {
        return buffer_1.default.Buffer.from(str, 'utf8');
    }
    else {
        // eslint-disable-next-line n/no-deprecated-api
        return new buffer_1.default.Buffer(str, 'utf8');
    }
}
utf8.default = {
    encode: encode,
    decode: decode
};

(function (exports) {
/**
 * 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 __createBinding = (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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.utf8 = exports.alloc = exports.ChannelConfig = void 0;
__exportStar(browser, exports);
__exportStar(chunking, exports);
var channel_config_1 = channelConfig;
Object.defineProperty(exports, "ChannelConfig", { enumerable: true, get: function () { return __importDefault(channel_config_1).default; } });
var channel_buf_1 = channelBuf;
Object.defineProperty(exports, "alloc", { enumerable: true, get: function () { return channel_buf_1.alloc; } });
var utf8_1 = utf8;
Object.defineProperty(exports, "utf8", { enumerable: true, get: function () { return __importDefault(utf8_1).default; } });
}(channel));

/**
 * 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(handshake$1, "__esModule", { value: true });
handshake$1.default = handshake;
var channel_1$4 = channel;
var neo4j_driver_core_1$E = lib$1;
var BOLT_MAGIC_PREAMBLE = 0x6060b017;
var AVAILABLE_BOLT_PROTOCOLS = ['5.8', '5.7', '5.6', '5.4', '5.3', '5.2', '5.1', '5.0', '4.4', '4.3', '4.2', '3.0']; // bolt protocols the client will accept, ordered by preference
var DESIRED_CAPABILITES = 0;
function version(major, minor) {
    return {
        major: major,
        minor: minor
    };
}
function createHandshakeMessage(versions) {
    if (versions.length > 4) {
        throw (0, neo4j_driver_core_1$E.newError)('It should not have more than 4 versions of the protocol');
    }
    var handshakeBuffer = (0, channel_1$4.alloc)(5 * 4);
    handshakeBuffer.writeInt32(BOLT_MAGIC_PREAMBLE);
    versions.forEach(function (version) {
        if (version instanceof Array) {
            var _a = version[0], major = _a.major, minor = _a.minor;
            var minMinor = version[1].minor;
            var range = minor - minMinor;
            handshakeBuffer.writeInt32((range << 16) | (minor << 8) | major);
        }
        else {
            var major = version.major, minor = version.minor;
            handshakeBuffer.writeInt32((minor << 8) | major);
        }
    });
    handshakeBuffer.reset();
    return handshakeBuffer;
}
function parseNegotiatedResponse(buffer, log) {
    var h = [
        buffer.readUInt8(),
        buffer.readUInt8(),
        buffer.readUInt8(),
        buffer.readUInt8()
    ];
    if (h[0] === 0x48 && h[1] === 0x54 && h[2] === 0x54 && h[3] === 0x50) {
        log.error('Handshake failed since server responded with HTTP.');
        throw (0, neo4j_driver_core_1$E.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)');
    }
    return Number(h[3] + '.' + h[2]);
}
function handshakeNegotiationV2(channel, buffer, log) {
    var numVersions = buffer.readVarInt();
    var versions = [];
    for (var i = 0; i < numVersions; i++) {
        var versionRange = [
            buffer.readUInt8(),
            buffer.readUInt8(),
            buffer.readUInt8(),
            buffer.readUInt8()
        ];
        versions = versions.concat(getVersions(versionRange));
    }
    buffer.readVarInt();
    var capabilites = selectCapabilites();
    var major = 0;
    var minor = 0;
    versions.sort(function (a, b) {
        if (Number(a.major) !== Number(b.major)) {
            return Number(b.major) - Number(a.major);
        }
        else {
            return Number(b.minor) - Number(a.minor);
        }
    });
    for (var i = 0; i < versions.length; i++) {
        var version_1 = versions[i];
        if (AVAILABLE_BOLT_PROTOCOLS.includes(version_1.major + '.' + version_1.minor)) {
            major = version_1.major;
            minor = version_1.minor;
            break;
        }
    }
    return new Promise(function (resolve, reject) {
        try {
            var selectionBuffer = (0, channel_1$4.alloc)(5);
            selectionBuffer.writeInt32((minor << 8) | major);
            selectionBuffer.writeVarInt(capabilites);
            channel.write(selectionBuffer);
            resolve({
                protocolVersion: Number(major + '.' + minor),
                capabilites: capabilites,
                consumeRemainingBuffer: function (consumer) {
                    if (buffer.hasRemaining()) {
                        consumer(buffer.readSlice(buffer.remaining()));
                    }
                }
            });
        }
        catch (e) {
            reject(e);
        }
    });
}
/**
 * @return {BaseBuffer}
 * @private
 */
function newHandshakeBuffer() {
    return createHandshakeMessage([
        version(255, 1),
        [version(5, 8), version(5, 0)],
        [version(4, 4), version(4, 2)],
        version(3, 0)
    ]);
}
/**
 * This callback is displayed as a global member.
 * @callback BufferConsumerCallback
 * @param {buffer} buffer the remaining buffer
 */
/**
 * @typedef HandshakeResult
 * @property {number} protocolVersion The protocol version negotiated in the handshake
 * @property {number} capabilites A bitmask representing the capabilities negotiated in the handshake
 * @property {function(BufferConsumerCallback)} consumeRemainingBuffer A function to consume the remaining buffer if it exists
 */
/**
 * Shake hands using the channel and return the protocol version
 *
 * @param {Channel} channel the channel use to shake hands
 * @param {Logger} log the log object
 * @returns {Promise<HandshakeResult>} Promise of protocol version and consumeRemainingBuffer
 */
function handshake(channel, log) {
    return initialHandshake(channel, log).then(function (result) {
        if (result.protocolVersion === 255.1) {
            return handshakeNegotiationV2(channel, result.buffer);
        }
        else {
            return result;
        }
    });
}
/**
 * Shake hands using the channel and return the protocol version, or the improved handshake protocol if communicating with a newer server.
 *
 * @param {Channel} channel the channel use to shake hands
 * @param {Logger} log the log object
 * @returns {Promise<HandshakeResult>} Promise of protocol version and consumeRemainingBuffer
 */
function initialHandshake(channel, log) {
    var _this = this;
    return new Promise(function (resolve, reject) {
        var handshakeErrorHandler = function (error) {
            reject(error);
        };
        channel.onerror = handshakeErrorHandler.bind(_this);
        if (channel._error) {
            handshakeErrorHandler(channel._error);
        }
        channel.onmessage = function (buffer) {
            try {
                // read the response buffer and initialize the protocol
                var protocolVersion = parseNegotiatedResponse(buffer, log);
                resolve({
                    protocolVersion: protocolVersion,
                    capabilites: 0,
                    buffer: buffer,
                    consumeRemainingBuffer: function (consumer) {
                        if (buffer.hasRemaining()) {
                            consumer(buffer.readSlice(buffer.remaining()));
                        }
                    }
                });
            }
            catch (e) {
                reject(e);
            }
        };
        channel.write(newHandshakeBuffer());
    });
}
function getVersions(versionArray) {
    var resultArr = [];
    var major = versionArray[3];
    var minor = versionArray[2];
    for (var i = 0; i <= versionArray[1]; i++) {
        resultArr.push({ major: major, minor: minor - i });
    }
    return resultArr;
}
function selectCapabilites(capabilityBitMask) {
    return DESIRED_CAPABILITES; // capabilites are currently unused and will always be 0.
}

var create$1 = {};

var boltProtocolV1 = {};

var boltProtocolUtil = {};

var streamObservers = {};

var routingTableRaw = {};

var __extends$p = (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 __importDefault$H = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(routingTableRaw, "__esModule", { value: true });
/**
 * 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 no-unused-vars
__importDefault$H(lib$1);
/**
 * Represente the raw version of the routing table
 */
var RawRoutingTable = /** @class */ (function () {
    function RawRoutingTable() {
    }
    /**
     * Constructs the raw routing table for Record based result
     * @param {Record} record The record which will be used get the raw routing table
     * @returns {RawRoutingTable} The raw routing table
     */
    RawRoutingTable.ofRecord = function (record) {
        if (record === null) {
            return RawRoutingTable.ofNull();
        }
        return new RecordRawRoutingTable(record);
    };
    /**
     * Constructs the raw routing table for Success result for a Routing Message
     * @param {object} response The result
     * @returns {RawRoutingTable} The raw routing table
     */
    RawRoutingTable.ofMessageResponse = function (response) {
        if (response === null) {
            return RawRoutingTable.ofNull();
        }
        return new ResponseRawRoutingTable(response);
    };
    /**
     * Construct the raw routing table of a null response
     *
     * @returns {RawRoutingTable} the raw routing table
     */
    RawRoutingTable.ofNull = function () {
        return new NullRawRoutingTable();
    };
    Object.defineProperty(RawRoutingTable.prototype, "ttl", {
        /**
         * Get raw ttl
         *
         * @returns {number|string} ttl Time to live
         */
        get: function () {
            throw new Error('Not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawRoutingTable.prototype, "db", {
        /**
         * Get raw db
         *
         * @returns {string?} The database name
         */
        get: function () {
            throw new Error('Not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawRoutingTable.prototype, "servers", {
        /**
         *
         * @typedef {Object} ServerRole
         * @property {string} role the role of the address on the cluster
         * @property {string[]} addresses the address within the role
         *
         * @return {ServerRole[]} list of servers addresses
         */
        get: function () {
            throw new Error('Not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawRoutingTable.prototype, "isNull", {
        /**
         * Indicates the result is null
         *
         * @returns {boolean} Is null
         */
        get: function () {
            throw new Error('Not implemented');
        },
        enumerable: false,
        configurable: true
    });
    return RawRoutingTable;
}());
routingTableRaw.default = RawRoutingTable;
/**
 * Get the raw routing table information from route message response
 */
var ResponseRawRoutingTable = /** @class */ (function (_super) {
    __extends$p(ResponseRawRoutingTable, _super);
    function ResponseRawRoutingTable(response) {
        var _this = _super.call(this) || this;
        _this._response = response;
        return _this;
    }
    Object.defineProperty(ResponseRawRoutingTable.prototype, "ttl", {
        get: function () {
            return this._response.rt.ttl;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ResponseRawRoutingTable.prototype, "servers", {
        get: function () {
            return this._response.rt.servers;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ResponseRawRoutingTable.prototype, "db", {
        get: function () {
            return this._response.rt.db;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ResponseRawRoutingTable.prototype, "isNull", {
        get: function () {
            return this._response === null;
        },
        enumerable: false,
        configurable: true
    });
    return ResponseRawRoutingTable;
}(RawRoutingTable));
/**
 * Null routing table
 */
var NullRawRoutingTable = /** @class */ (function (_super) {
    __extends$p(NullRawRoutingTable, _super);
    function NullRawRoutingTable() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(NullRawRoutingTable.prototype, "isNull", {
        get: function () {
            return true;
        },
        enumerable: false,
        configurable: true
    });
    return NullRawRoutingTable;
}(RawRoutingTable));
/**
 * Get the raw routing table information from the record
 */
var RecordRawRoutingTable = /** @class */ (function (_super) {
    __extends$p(RecordRawRoutingTable, _super);
    function RecordRawRoutingTable(record) {
        var _this = _super.call(this) || this;
        _this._record = record;
        return _this;
    }
    Object.defineProperty(RecordRawRoutingTable.prototype, "ttl", {
        get: function () {
            return this._record.get('ttl');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecordRawRoutingTable.prototype, "servers", {
        get: function () {
            return this._record.get('servers');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecordRawRoutingTable.prototype, "db", {
        get: function () {
            return this._record.has('db') ? this._record.get('db') : null;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecordRawRoutingTable.prototype, "isNull", {
        get: function () {
            return this._record === null;
        },
        enumerable: false,
        configurable: true
    });
    return RecordRawRoutingTable;
}(RawRoutingTable));

var lang = {};

var functional = {};

/**
 * 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(functional, "__esModule", { value: true });
functional.identity = identity;
functional.reuseOngoingRequest = reuseOngoingRequest;
var neo4j_driver_core_1$D = lib$1;
/**
 * Identity function.
 *
 * Identity functions are function which returns the input as output.
 *
 * @param {any} x
 * @returns {any} the x
 */
function identity(x) {
    return x;
}
/**
 * Makes the function able to share ongoing requests
 *
 * @param {function(...args): Promise} func The function to be decorated
 * @param {any} thisArg The `this` which should be used in the function call
 * @return {function(...args): Promise} The decorated function
 */
function reuseOngoingRequest(func, thisArg) {
    if (thisArg === void 0) { thisArg = null; }
    var ongoingRequests = new Map();
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var key = neo4j_driver_core_1$D.json.stringify(args);
        if (ongoingRequests.has(key)) {
            return ongoingRequests.get(key);
        }
        var promise = func.apply(thisArg, args);
        ongoingRequests.set(key, promise);
        return promise.finally(function () {
            ongoingRequests.delete(key);
        });
    };
}

var object = {};

/**
 * 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 __values$1 = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(object, "__esModule", { value: true });
object.equals = equals;
function equals(a, b) {
    var e_1, _a;
    if (a === b) {
        return true;
    }
    if (a === null || b === null) {
        return false;
    }
    if (typeof a === 'object' && typeof b === 'object') {
        var keysA = Object.keys(a);
        var keysB = Object.keys(b);
        if (keysA.length !== keysB.length) {
            return false;
        }
        try {
            for (var keysA_1 = __values$1(keysA), keysA_1_1 = keysA_1.next(); !keysA_1_1.done; keysA_1_1 = keysA_1.next()) {
                var key = keysA_1_1.value;
                if (a[key] !== b[key]) {
                    return false;
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (keysA_1_1 && !keysA_1_1.done && (_a = keysA_1.return)) _a.call(keysA_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return true;
    }
    return false;
}

/**
 * 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 __createBinding$4 = (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$4 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$4 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$4(result, mod, k[i]);
        __setModuleDefault$4(result, mod);
        return result;
    };
})();
Object.defineProperty(lang, "__esModule", { value: true });
lang.object = lang.functional = void 0;
lang.functional = __importStar$4(functional);
lang.object = __importStar$4(object);

var __extends$o = (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 __importDefault$G = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(streamObservers, "__esModule", { value: true });
streamObservers.TelemetryObserver = streamObservers.ProcedureRouteObserver = streamObservers.RouteObserver = streamObservers.CompletedObserver = streamObservers.FailedObserver = streamObservers.ResetObserver = streamObservers.LogoffObserver = streamObservers.LoginObserver = streamObservers.ResultStreamObserver = streamObservers.StreamObserver = 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.
 */
var neo4j_driver_core_1$C = lib$1;
var routing_table_raw_1 = __importDefault$G(routingTableRaw);
var lang_1$4 = lang;
var FETCH_ALL$6 = neo4j_driver_core_1$C.internal.constants.FETCH_ALL;
var PROTOCOL_ERROR$5 = neo4j_driver_core_1$C.error.PROTOCOL_ERROR;
var StreamObserver = /** @class */ (function () {
    function StreamObserver() {
    }
    StreamObserver.prototype.onNext = function (rawRecord) { };
    StreamObserver.prototype.onError = function (_error) { };
    StreamObserver.prototype.onCompleted = function (meta) { };
    return StreamObserver;
}());
streamObservers.StreamObserver = StreamObserver;
/**
 * 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 ResultStreamObserver = /** @class */ (function (_super) {
    __extends$o(ResultStreamObserver, _super);
    /**
     *
     * @param {Object} param
     * @param {Object} param.server
     * @param {boolean} param.reactive
     * @param {function(stmtId: number|Integer, n: number|Integer, observer: StreamObserver)} param.moreFunction -
     * @param {function(stmtId: number|Integer, observer: StreamObserver)} param.discardFunction -
     * @param {number|Integer} param.fetchSize -
     * @param {function(err: Error): Promise|void} param.beforeError -
     * @param {function(err: Error): Promise|void} param.afterError -
     * @param {function(keys: string[]): Promise|void} param.beforeKeys -
     * @param {function(keys: string[]): Promise|void} param.afterKeys -
     * @param {function(metadata: Object): Promise|void} param.beforeComplete -
     * @param {function(metadata: Object): Promise|void} param.afterComplete -
     * @param {function(metadata: Object): Promise|void} param.enrichMetadata -
     */
    function ResultStreamObserver(_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.reactive, reactive = _c === void 0 ? false : _c, moreFunction = _b.moreFunction, discardFunction = _b.discardFunction, _d = _b.fetchSize, fetchSize = _d === void 0 ? FETCH_ALL$6 : _d, beforeError = _b.beforeError, afterError = _b.afterError, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, server = _b.server, _e = _b.highRecordWatermark, highRecordWatermark = _e === void 0 ? Number.MAX_VALUE : _e, _f = _b.lowRecordWatermark, lowRecordWatermark = _f === void 0 ? Number.MAX_VALUE : _f, enrichMetadata = _b.enrichMetadata, onDb = _b.onDb;
        var _this = _super.call(this) || this;
        _this._fieldKeys = null;
        _this._fieldLookup = null;
        _this._head = null;
        _this._queuedRecords = [];
        _this._tail = null;
        _this._error = null;
        _this._observers = [];
        _this._meta = {};
        _this._server = server;
        _this._beforeError = beforeError;
        _this._afterError = afterError;
        _this._beforeKeys = beforeKeys;
        _this._afterKeys = afterKeys;
        _this._beforeComplete = beforeComplete;
        _this._afterComplete = afterComplete;
        _this._enrichMetadata = enrichMetadata || lang_1$4.functional.identity;
        _this._queryId = null;
        _this._moreFunction = moreFunction;
        _this._discardFunction = discardFunction;
        _this._discard = false;
        _this._fetchSize = fetchSize;
        _this._lowRecordWatermark = lowRecordWatermark;
        _this._highRecordWatermark = highRecordWatermark;
        _this._setState(reactive ? _states.READY : _states.READY_STREAMING);
        _this._setupAutoPull();
        _this._paused = false;
        _this._pulled = !reactive;
        _this._haveRecordStreamed = false;
        _this._onDb = onDb;
        return _this;
    }
    /**
     * Pause the record consuming
     *
     * This function will supend the record consuming. It will not cancel the stream and the already
     * requested records will be sent to the subscriber.
     */
    ResultStreamObserver.prototype.pause = function () {
        this._paused = true;
    };
    /**
     * Resume the record consuming
     *
     * This function will resume the record consuming fetching more records from the server.
     */
    ResultStreamObserver.prototype.resume = function () {
        this._paused = false;
        this._setupAutoPull(true);
        this._state.pull(this);
    };
    /**
     * 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
     */
    ResultStreamObserver.prototype.onNext = function (rawRecord) {
        this._haveRecordStreamed = true;
        var record = new neo4j_driver_core_1$C.Record(this._fieldKeys, rawRecord, this._fieldLookup);
        if (this._observers.some(function (o) { return o.onNext; })) {
            this._observers.forEach(function (o) {
                if (o.onNext) {
                    o.onNext(record);
                }
            });
        }
        else {
            this._queuedRecords.push(record);
            if (this._queuedRecords.length > this._highRecordWatermark) {
                this._autoPull = false;
            }
        }
    };
    ResultStreamObserver.prototype.onCompleted = function (meta) {
        this._state.onSuccess(this, meta);
    };
    /**
     * 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
     */
    ResultStreamObserver.prototype.onError = function (error) {
        this._state.onError(this, error);
    };
    /**
     * Cancel pending record stream
     */
    ResultStreamObserver.prototype.cancel = function () {
        this._discard = true;
    };
    /**
     * Stream observer defaults to handling responses for two messages: RUN + PULL_ALL or RUN + DISCARD_ALL.
     * Response for RUN initializes query keys. Response for PULL_ALL / DISCARD_ALL exposes the result stream.
     *
     * However, some operations can be represented as a single message which receives full metadata in a single response.
     * For example, operations to begin, commit and rollback an explicit transaction use two messages in Bolt V1 but a single message in Bolt V3.
     * Messages are `RUN "BEGIN" {}` + `PULL_ALL` in Bolt V1 and `BEGIN` in Bolt V3.
     *
     * This function prepares the observer to only handle a single response message.
     */
    ResultStreamObserver.prototype.prepareToHandleSingleResponse = function () {
        this._head = [];
        this._fieldKeys = [];
        this._setState(_states.STREAMING);
    };
    /**
     * Mark this observer as if it has completed with no metadata.
     */
    ResultStreamObserver.prototype.markCompleted = function () {
        this._head = [];
        this._fieldKeys = [];
        this._tail = {};
        this._setState(_states.SUCCEEDED);
    };
    /**
     * Subscribe to events with provided observer.
     * @param {Object} observer - Observer object
     * @param {function(keys: String[])} observer.onKeys - Handle stream header, field keys.
     * @param {function(record: Object)} observer.onNext - Handle records, one by one.
     * @param {function(metadata: Object)} observer.onCompleted - Handle stream tail, the metadata.
     * @param {function(error: Object)} observer.onError - Handle errors, should always be provided.
     */
    ResultStreamObserver.prototype.subscribe = function (observer) {
        if (this._head && observer.onKeys) {
            observer.onKeys(this._head);
        }
        if (this._queuedRecords.length > 0 && observer.onNext) {
            for (var i = 0; i < this._queuedRecords.length; i++) {
                observer.onNext(this._queuedRecords[i]);
                if (this._queuedRecords.length - i - 1 <= this._lowRecordWatermark) {
                    this._autoPull = true;
                    if (this._state === _states.READY) {
                        this._handleStreaming();
                    }
                }
            }
        }
        if (this._tail && observer.onCompleted) {
            observer.onCompleted(this._tail);
        }
        if (this._error) {
            observer.onError(this._error);
        }
        this._observers.push(observer);
        if (this._state === _states.READY) {
            this._handleStreaming();
        }
    };
    ResultStreamObserver.prototype._handleHasMore = function (meta) {
        // We've consumed current batch and server notified us that there're more
        // records to stream. Let's invoke more or discard function based on whether
        // the user wants to discard streaming or not
        this._setState(_states.READY); // we've done streaming
        this._handleStreaming();
        delete meta.has_more;
    };
    ResultStreamObserver.prototype._handlePullSuccess = function (meta) {
        var _this = this;
        var completionMetadata = this._enrichMetadata(Object.assign(this._server ? { server: this._server } : {}, this._meta, {
            stream_summary: {
                have_records_streamed: this._haveRecordStreamed,
                pulled: this._pulled,
                has_keys: this._fieldKeys.length > 0
            }
        }, meta));
        if (![undefined, null, 'r', 'w', 'rw', 's'].includes(completionMetadata.type)) {
            this.onError((0, neo4j_driver_core_1$C.newError)("Server returned invalid query type. Expected one of [undefined, null, \"r\", \"w\", \"rw\", \"s\"] but got '".concat(completionMetadata.type, "'"), PROTOCOL_ERROR$5));
            return;
        }
        this._setState(_states.SUCCEEDED);
        var beforeHandlerResult = null;
        if (this._beforeComplete) {
            beforeHandlerResult = this._beforeComplete(completionMetadata);
        }
        var continuation = function () {
            // End of stream
            _this._tail = completionMetadata;
            if (_this._observers.some(function (o) { return o.onCompleted; })) {
                _this._observers.forEach(function (o) {
                    if (o.onCompleted) {
                        o.onCompleted(completionMetadata);
                    }
                });
            }
            if (_this._afterComplete) {
                _this._afterComplete(completionMetadata);
            }
        };
        if (beforeHandlerResult) {
            Promise.resolve(beforeHandlerResult).then(function () { return continuation(); });
        }
        else {
            continuation();
        }
    };
    ResultStreamObserver.prototype._handleRunSuccess = function (meta, afterSuccess) {
        var _this = this;
        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;
                }
            }
            if (meta.db !== null && this._onDb !== undefined) {
                this._onDb(meta.db);
            }
            if (meta.fields != null) {
                // remove fields key from metadata object
                delete meta.fields;
            }
            // Extract server generated query id for use in requestMore and discard
            // functions
            if (meta.qid !== null && meta.qid !== undefined) {
                this._queryId = meta.qid;
                // remove qid from metadata object
                delete meta.qid;
            }
            this._storeMetadataForCompletion(meta);
            var beforeHandlerResult = null;
            if (this._beforeKeys) {
                beforeHandlerResult = this._beforeKeys(this._fieldKeys);
            }
            var continuation_1 = function () {
                _this._head = _this._fieldKeys;
                if (_this._observers.some(function (o) { return o.onKeys; })) {
                    _this._observers.forEach(function (o) {
                        if (o.onKeys) {
                            o.onKeys(_this._fieldKeys);
                        }
                    });
                }
                if (_this._afterKeys) {
                    _this._afterKeys(_this._fieldKeys);
                }
                afterSuccess();
            };
            if (beforeHandlerResult) {
                Promise.resolve(beforeHandlerResult).then(function () { return continuation_1(); });
            }
            else {
                continuation_1();
            }
        }
    };
    ResultStreamObserver.prototype._handleError = function (error) {
        var _this = this;
        this._setState(_states.FAILED);
        this._error = error;
        var beforeHandlerResult = null;
        if (this._beforeError) {
            beforeHandlerResult = this._beforeError(error);
        }
        var continuation = function () {
            if (_this._observers.some(function (o) { return o.onError; })) {
                _this._observers.forEach(function (o) {
                    if (o.onError) {
                        o.onError(error);
                    }
                });
            }
            if (_this._afterError) {
                _this._afterError(error);
            }
        };
        if (beforeHandlerResult) {
            Promise.resolve(beforeHandlerResult).then(function () { return continuation(); });
        }
        else {
            continuation();
        }
    };
    ResultStreamObserver.prototype._handleStreaming = function () {
        if (this._head && this._observers.some(function (o) { return o.onNext || o.onCompleted; })) {
            if (!this._paused && (this._discard || this._autoPull)) {
                this._more();
            }
        }
    };
    ResultStreamObserver.prototype._more = function () {
        if (this._discard) {
            this._discardFunction(this._queryId, this);
        }
        else {
            this._pulled = true;
            this._moreFunction(this._queryId, this._fetchSize, this);
        }
        this._setState(_states.STREAMING);
    };
    ResultStreamObserver.prototype._storeMetadataForCompletion = function (meta) {
        var keys = Object.keys(meta);
        var index = keys.length;
        var key = '';
        while (index--) {
            key = keys[index];
            this._meta[key] = meta[key];
        }
    };
    ResultStreamObserver.prototype._setState = function (state) {
        this._state = state;
    };
    ResultStreamObserver.prototype._setupAutoPull = function () {
        this._autoPull = true;
    };
    return ResultStreamObserver;
}(StreamObserver));
streamObservers.ResultStreamObserver = ResultStreamObserver;
var LoginObserver = /** @class */ (function (_super) {
    __extends$o(LoginObserver, _super);
    /**
     *
     * @param {Object} param -
     * @param {function(err: Error)} param.onError
     * @param {function(metadata)} param.onCompleted
     */
    function LoginObserver(_a) {
        var _b = _a === void 0 ? {} : _a, onError = _b.onError, onCompleted = _b.onCompleted;
        var _this = _super.call(this) || this;
        _this._onError = onError;
        _this._onCompleted = onCompleted;
        return _this;
    }
    LoginObserver.prototype.onNext = function (record) {
        this.onError((0, neo4j_driver_core_1$C.newError)('Received RECORD when initializing ' + neo4j_driver_core_1$C.json.stringify(record)));
    };
    LoginObserver.prototype.onError = function (error) {
        if (this._onError) {
            this._onError(error);
        }
    };
    LoginObserver.prototype.onCompleted = function (metadata) {
        if (this._onCompleted) {
            this._onCompleted(metadata);
        }
    };
    return LoginObserver;
}(StreamObserver));
streamObservers.LoginObserver = LoginObserver;
var LogoffObserver = /** @class */ (function (_super) {
    __extends$o(LogoffObserver, _super);
    /**
     *
     * @param {Object} param -
     * @param {function(err: Error)} param.onError
     * @param {function(metadata)} param.onCompleted
     */
    function LogoffObserver(_a) {
        var _b = _a === void 0 ? {} : _a, onError = _b.onError, onCompleted = _b.onCompleted;
        var _this = _super.call(this) || this;
        _this._onError = onError;
        _this._onCompleted = onCompleted;
        return _this;
    }
    LogoffObserver.prototype.onNext = function (record) {
        this.onError((0, neo4j_driver_core_1$C.newError)('Received RECORD when logging off ' + neo4j_driver_core_1$C.json.stringify(record)));
    };
    LogoffObserver.prototype.onError = function (error) {
        if (this._onError) {
            this._onError(error);
        }
    };
    LogoffObserver.prototype.onCompleted = function (metadata) {
        if (this._onCompleted) {
            this._onCompleted(metadata);
        }
    };
    return LogoffObserver;
}(StreamObserver));
streamObservers.LogoffObserver = LogoffObserver;
var ResetObserver = /** @class */ (function (_super) {
    __extends$o(ResetObserver, _super);
    /**
     *
     * @param {Object} param -
     * @param {function(err: String)} param.onProtocolError
     * @param {function(err: Error)} param.onError
     * @param {function(metadata)} param.onComplete
     */
    function ResetObserver(_a) {
        var _b = _a === void 0 ? {} : _a, onProtocolError = _b.onProtocolError, onError = _b.onError, onComplete = _b.onComplete;
        var _this = _super.call(this) || this;
        _this._onProtocolError = onProtocolError;
        _this._onError = onError;
        _this._onComplete = onComplete;
        return _this;
    }
    ResetObserver.prototype.onNext = function (record) {
        this.onError((0, neo4j_driver_core_1$C.newError)('Received RECORD when resetting: received record is: ' +
            neo4j_driver_core_1$C.json.stringify(record), PROTOCOL_ERROR$5));
    };
    ResetObserver.prototype.onError = function (error) {
        if (error.code === PROTOCOL_ERROR$5 && this._onProtocolError) {
            this._onProtocolError(error.message);
        }
        if (this._onError) {
            this._onError(error);
        }
    };
    ResetObserver.prototype.onCompleted = function (metadata) {
        if (this._onComplete) {
            this._onComplete(metadata);
        }
    };
    return ResetObserver;
}(StreamObserver));
streamObservers.ResetObserver = ResetObserver;
var TelemetryObserver = /** @class */ (function (_super) {
    __extends$o(TelemetryObserver, _super);
    /**
     *
     * @param {Object} param -
     * @param {function(err: Error)} param.onError
     * @param {function(metadata)} param.onCompleted
     */
    function TelemetryObserver(_a) {
        var _b = _a === void 0 ? {} : _a, onError = _b.onError, onCompleted = _b.onCompleted;
        var _this = _super.call(this) || this;
        _this._onError = onError;
        _this._onCompleted = onCompleted;
        return _this;
    }
    TelemetryObserver.prototype.onNext = function (record) {
        this.onError((0, neo4j_driver_core_1$C.newError)('Received RECORD when sending telemetry ' + neo4j_driver_core_1$C.json.stringify(record), PROTOCOL_ERROR$5));
    };
    TelemetryObserver.prototype.onError = function (error) {
        if (this._onError) {
            this._onError(error);
        }
    };
    TelemetryObserver.prototype.onCompleted = function (metadata) {
        if (this._onCompleted) {
            this._onCompleted(metadata);
        }
    };
    return TelemetryObserver;
}(ResultStreamObserver));
streamObservers.TelemetryObserver = TelemetryObserver;
var FailedObserver = /** @class */ (function (_super) {
    __extends$o(FailedObserver, _super);
    function FailedObserver(_a) {
        var error = _a.error, onError = _a.onError;
        var _this = _super.call(this, { beforeError: onError }) || this;
        _this.onError(error);
        return _this;
    }
    return FailedObserver;
}(ResultStreamObserver));
streamObservers.FailedObserver = FailedObserver;
var CompletedObserver = /** @class */ (function (_super) {
    __extends$o(CompletedObserver, _super);
    function CompletedObserver() {
        var _this = _super.call(this) || this;
        _super.prototype.markCompleted.call(_this);
        return _this;
    }
    return CompletedObserver;
}(ResultStreamObserver));
streamObservers.CompletedObserver = CompletedObserver;
var ProcedureRouteObserver = /** @class */ (function (_super) {
    __extends$o(ProcedureRouteObserver, _super);
    function ProcedureRouteObserver(_a) {
        var resultObserver = _a.resultObserver, onProtocolError = _a.onProtocolError, onError = _a.onError, onCompleted = _a.onCompleted;
        var _this = _super.call(this) || this;
        _this._resultObserver = resultObserver;
        _this._onError = onError;
        _this._onCompleted = onCompleted;
        _this._records = [];
        _this._onProtocolError = onProtocolError;
        resultObserver.subscribe(_this);
        return _this;
    }
    ProcedureRouteObserver.prototype.onNext = function (record) {
        this._records.push(record);
    };
    ProcedureRouteObserver.prototype.onError = function (error) {
        if (error.code === PROTOCOL_ERROR$5 && this._onProtocolError) {
            this._onProtocolError(error.message);
        }
        if (this._onError) {
            this._onError(error);
        }
    };
    ProcedureRouteObserver.prototype.onCompleted = function () {
        if (this._records !== null && this._records.length !== 1) {
            this.onError((0, neo4j_driver_core_1$C.newError)('Illegal response from router. Received ' +
                this._records.length +
                ' records but expected only one.\n' +
                neo4j_driver_core_1$C.json.stringify(this._records), PROTOCOL_ERROR$5));
            return;
        }
        if (this._onCompleted) {
            this._onCompleted(routing_table_raw_1.default.ofRecord(this._records[0]));
        }
    };
    return ProcedureRouteObserver;
}(StreamObserver));
streamObservers.ProcedureRouteObserver = ProcedureRouteObserver;
var RouteObserver = /** @class */ (function (_super) {
    __extends$o(RouteObserver, _super);
    /**
     *
     * @param {Object} param -
     * @param {function(err: String)} param.onProtocolError
     * @param {function(err: Error)} param.onError
     * @param {function(RawRoutingTable)} param.onCompleted
     */
    function RouteObserver(_a) {
        var _b = _a === void 0 ? {} : _a, onProtocolError = _b.onProtocolError, onError = _b.onError, onCompleted = _b.onCompleted;
        var _this = _super.call(this) || this;
        _this._onProtocolError = onProtocolError;
        _this._onError = onError;
        _this._onCompleted = onCompleted;
        return _this;
    }
    RouteObserver.prototype.onNext = function (record) {
        this.onError((0, neo4j_driver_core_1$C.newError)('Received RECORD when resetting: received record is: ' +
            neo4j_driver_core_1$C.json.stringify(record), PROTOCOL_ERROR$5));
    };
    RouteObserver.prototype.onError = function (error) {
        if (error.code === PROTOCOL_ERROR$5 && this._onProtocolError) {
            this._onProtocolError(error.message);
        }
        if (this._onError) {
            this._onError(error);
        }
    };
    RouteObserver.prototype.onCompleted = function (metadata) {
        if (this._onCompleted) {
            this._onCompleted(routing_table_raw_1.default.ofMessageResponse(metadata));
        }
    };
    return RouteObserver;
}(StreamObserver));
streamObservers.RouteObserver = RouteObserver;
var _states = {
    READY_STREAMING: {
        // async start state
        onSuccess: function (streamObserver, meta) {
            streamObserver._handleRunSuccess(meta, function () {
                streamObserver._setState(_states.STREAMING);
            } // after run succeeded, async directly move to streaming
            // state
            );
        },
        onError: function (streamObserver, error) {
            streamObserver._handleError(error);
        },
        name: function () {
            return 'READY_STREAMING';
        },
        pull: function () { }
    },
    READY: {
        // reactive start state
        onSuccess: function (streamObserver, meta) {
            streamObserver._handleRunSuccess(meta, function () { return streamObserver._handleStreaming(); } // after run succeeded received, reactive shall start pulling
            );
        },
        onError: function (streamObserver, error) {
            streamObserver._handleError(error);
        },
        name: function () {
            return 'READY';
        },
        pull: function (streamObserver) { return streamObserver._more(); }
    },
    STREAMING: {
        onSuccess: function (streamObserver, meta) {
            if (meta.has_more) {
                streamObserver._handleHasMore(meta);
            }
            else {
                streamObserver._handlePullSuccess(meta);
            }
        },
        onError: function (streamObserver, error) {
            streamObserver._handleError(error);
        },
        name: function () {
            return 'STREAMING';
        },
        pull: function () { }
    },
    FAILED: {
        onError: function (_error) {
            // more errors are ignored
        },
        name: function () {
            return 'FAILED';
        },
        pull: function () { }
    },
    SUCCEEDED: {
        name: function () {
            return 'SUCCEEDED';
        },
        pull: function () { }
    }
};

Object.defineProperty(boltProtocolUtil, "__esModule", { value: true });
boltProtocolUtil.assertDatabaseIsEmpty = assertDatabaseIsEmpty;
boltProtocolUtil.assertTxConfigIsEmpty = assertTxConfigIsEmpty;
boltProtocolUtil.assertImpersonatedUserIsEmpty = assertImpersonatedUserIsEmpty;
boltProtocolUtil.assertNotificationFilterIsEmpty = assertNotificationFilterIsEmpty;
/**
 * 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 neo4j_driver_core_1$B = lib$1;
/**
 * @param {TxConfig} txConfig the auto-commit transaction configuration.
 * @param {function(error: string)} onProtocolError called when the txConfig is not empty.
 * @param {ResultStreamObserver} observer the response observer.
 */
function assertTxConfigIsEmpty(txConfig, onProtocolError, observer) {
    if (onProtocolError === void 0) { onProtocolError = function () { }; }
    if (txConfig && !txConfig.isEmpty()) {
        var error = (0, neo4j_driver_core_1$B.newError)('Driver is connected to the database that does not support transaction configuration. ' +
            'Please upgrade to neo4j 3.5.0 or later in order to use this functionality');
        // unsupported API was used, consider this a fatal error for the current connection
        onProtocolError(error.message);
        observer.onError(error);
        throw error;
    }
}
/**
 * Asserts that the passed-in database name is empty.
 * @param {string} database
 * @param {fuction(err: String)} onProtocolError Called when it doesn't have database set
 */
function assertDatabaseIsEmpty(database, onProtocolError, observer) {
    if (onProtocolError === void 0) { onProtocolError = function () { }; }
    if (database) {
        var error = (0, neo4j_driver_core_1$B.newError)('Driver is connected to the database that does not support multiple databases. ' +
            'Please upgrade to neo4j 4.0.0 or later in order to use this functionality');
        // unsupported API was used, consider this a fatal error for the current connection
        onProtocolError(error.message);
        observer.onError(error);
        throw error;
    }
}
/**
 * Asserts that the passed-in impersonated user is empty
 * @param {string} impersonatedUser
 * @param {function (err:Error)} onProtocolError Called when it does have impersonated user set
 * @param {any} observer
 */
function assertImpersonatedUserIsEmpty(impersonatedUser, onProtocolError, observer) {
    if (onProtocolError === void 0) { onProtocolError = function () { }; }
    if (impersonatedUser) {
        var error = (0, neo4j_driver_core_1$B.newError)('Driver is connected to the database that does not support user impersonation. ' +
            'Please upgrade to neo4j 4.4.0 or later in order to use this functionality. ' +
            "Trying to impersonate ".concat(impersonatedUser, "."));
        // unsupported API was used, consider this a fatal error for the current connection
        onProtocolError(error.message);
        observer.onError(error);
        throw error;
    }
}
/**
 * Asserts that the passed-in notificationFilter is empty
 * @param {NotificationFilter} notificationFilter
 * @param {function (err:Error)} onProtocolError Called when it does have notificationFilter user set
 * @param {any} observer
 */
function assertNotificationFilterIsEmpty(notificationFilter, onProtocolError, observer) {
    if (onProtocolError === void 0) { onProtocolError = function () { }; }
    if (notificationFilter !== undefined) {
        var error = (0, neo4j_driver_core_1$B.newError)('Driver is connected to a database that does not support user notification filters. ' +
            'Please upgrade to Neo4j 5.7.0 or later in order to use this functionality. ' +
            "Trying to set notifications to ".concat(neo4j_driver_core_1$B.json.stringify(notificationFilter), "."));
        // unsupported API was used, consider this a fatal error for the current connection
        onProtocolError(error.message);
        observer.onError(error);
        throw error;
    }
}

var packstream = {};

var packstreamV1 = {};

var structure$1 = {};

/**
 * 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(structure$1, "__esModule", { value: true });
structure$1.Structure = void 0;
structure$1.verifyStructSize = verifyStructSize;
var neo4j_driver_core_1$A = lib$1;
var PROTOCOL_ERROR$4 = neo4j_driver_core_1$A.error.PROTOCOL_ERROR;
/**
 * A Structure have a signature and fields.
 */
var Structure = /** @class */ (function () {
    /**
     * Create new instance
     */
    function Structure(signature, fields) {
        this.signature = signature;
        this.fields = fields;
    }
    Object.defineProperty(Structure.prototype, "size", {
        get: function () {
            return this.fields.length;
        },
        enumerable: false,
        configurable: true
    });
    Structure.prototype.toString = function () {
        var fieldStr = '';
        for (var i = 0; i < this.fields.length; i++) {
            if (i > 0) {
                fieldStr += ', ';
            }
            fieldStr += this.fields[i];
        }
        return 'Structure(' + this.signature + ', [' + fieldStr + '])';
    };
    return Structure;
}());
structure$1.Structure = Structure;
function verifyStructSize(structName, expectedSize, actualSize) {
    if (expectedSize !== actualSize) {
        throw (0, neo4j_driver_core_1$A.newError)("Wrong struct size for ".concat(structName, ", expected ").concat(expectedSize, " but was ").concat(actualSize), PROTOCOL_ERROR$4);
    }
}
structure$1.default = Structure;

Object.defineProperty(packstreamV1, "__esModule", { value: true });
packstreamV1.Unpacker = packstreamV1.Packer = 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.
 */
var channel_1$3 = channel;
var lang_1$3 = lang;
var structure_1 = structure$1;
var neo4j_driver_core_1$z = lib$1;
var PROTOCOL_ERROR$3 = neo4j_driver_core_1$z.error.PROTOCOL_ERROR;
var TINY_STRING = 0x80;
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;
/**
 * Class to pack
 * @access private
 */
var Packer$1 = /** @class */ (function () {
    /**
     * @constructor
     * @param {Chunker} channel the chunker backed by a network channel.
     */
    function Packer(channel) {
        this._ch = channel;
        this._byteArraysSupported = true;
    }
    /**
     * Creates a packable function out of the provided value
     * @param x the value to pack
     * @returns Function
     */
    Packer.prototype.packable = function (x, dehydrateStruct) {
        var _this = this;
        if (dehydrateStruct === void 0) { dehydrateStruct = lang_1$3.functional.identity; }
        try {
            x = dehydrateStruct(x);
        }
        catch (ex) {
            return function () { throw ex; };
        }
        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); };
        }
        else if (typeof x === 'bigint') {
            return function () { return _this.packInteger((0, neo4j_driver_core_1$z.int)(x)); };
        }
        else if ((0, neo4j_driver_core_1$z.isInt)(x)) {
            return function () { return _this.packInteger(x); };
        }
        else if (x instanceof Int8Array) {
            return function () { return _this.packBytes(x); };
        }
        else if (x instanceof Array) {
            return function () {
                _this.packListHeader(x.length);
                for (var i = 0; i < x.length; i++) {
                    _this.packable(x[i] === undefined ? null : x[i], dehydrateStruct)();
                }
            };
        }
        else if (isIterable(x)) {
            return this.packableIterable(x, dehydrateStruct);
        }
        else if (x instanceof structure_1.Structure) {
            var packableFields_1 = [];
            for (var i = 0; i < x.fields.length; i++) {
                packableFields_1[i] = this.packable(x.fields[i], dehydrateStruct);
            }
            return function () { return _this.packStruct(x.signature, packableFields_1); };
        }
        else if (typeof x === 'object') {
            return function () {
                var keys = Object.keys(x);
                var count = 0;
                for (var i = 0; i < keys.length; i++) {
                    if (x[keys[i]] !== undefined) {
                        count++;
                    }
                }
                _this.packMapHeader(count);
                for (var i = 0; i < keys.length; i++) {
                    var key = keys[i];
                    if (x[key] !== undefined) {
                        _this.packString(key);
                        _this.packable(x[key], dehydrateStruct)();
                    }
                }
            };
        }
        else {
            return this._nonPackableValue("Unable to pack the given value: ".concat(x));
        }
    };
    Packer.prototype.packableIterable = function (iterable, dehydrateStruct) {
        try {
            var array = Array.from(iterable);
            return this.packable(array, dehydrateStruct);
        }
        catch (e) {
            // handle errors from iterable to array conversion
            throw (0, neo4j_driver_core_1$z.newError)("Cannot pack given iterable, ".concat(e.message, ": ").concat(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`
     */
    Packer.prototype.packStruct = function (signature, packableFields) {
        packableFields = packableFields || [];
        this.packStructHeader(packableFields.length, signature);
        for (var i = 0; i < packableFields.length; i++) {
            packableFields[i]();
        }
    };
    Packer.prototype.packInteger = function (x) {
        var high = x.high;
        var 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);
        }
    };
    Packer.prototype.packFloat = function (x) {
        this._ch.writeUInt8(FLOAT_64);
        this._ch.writeFloat64(x);
    };
    Packer.prototype.packString = function (x) {
        var bytes = channel_1$3.utf8.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 {
            throw (0, neo4j_driver_core_1$z.newError)('UTF-8 strings of size ' + size + ' are not supported');
        }
    };
    Packer.prototype.packListHeader = function (size) {
        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 {
            throw (0, neo4j_driver_core_1$z.newError)('Lists of size ' + size + ' are not supported');
        }
    };
    Packer.prototype.packBytes = function (array) {
        if (this._byteArraysSupported) {
            this.packBytesHeader(array.length);
            for (var i = 0; i < array.length; i++) {
                this._ch.writeInt8(array[i]);
            }
        }
        else {
            throw (0, neo4j_driver_core_1$z.newError)('Byte arrays are not supported by the database this driver is connected to');
        }
    };
    Packer.prototype.packBytesHeader = function (size) {
        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 {
            throw (0, neo4j_driver_core_1$z.newError)('Byte arrays of size ' + size + ' are not supported');
        }
    };
    Packer.prototype.packMapHeader = function (size) {
        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 {
            throw (0, neo4j_driver_core_1$z.newError)('Maps of size ' + size + ' are not supported');
        }
    };
    Packer.prototype.packStructHeader = function (size, signature) {
        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 {
            throw (0, neo4j_driver_core_1$z.newError)('Structures of size ' + size + ' are not supported');
        }
    };
    Packer.prototype.disableByteArrays = function () {
        this._byteArraysSupported = false;
    };
    Packer.prototype._nonPackableValue = function (message) {
        return function () {
            throw (0, neo4j_driver_core_1$z.newError)(message, PROTOCOL_ERROR$3);
        };
    };
    return Packer;
}());
packstreamV1.Packer = Packer$1;
/**
 * Class to unpack
 * @access private
 */
var Unpacker$1 = /** @class */ (function () {
    /**
     * @constructor
     * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers.
     * @param {boolean} useBigInt if this unpacker should convert all received integers to Bigint
     */
    function Unpacker(disableLosslessIntegers, useBigInt) {
        if (disableLosslessIntegers === void 0) { disableLosslessIntegers = false; }
        if (useBigInt === void 0) { useBigInt = false; }
        this._disableLosslessIntegers = disableLosslessIntegers;
        this._useBigInt = useBigInt;
    }
    Unpacker.prototype.unpack = function (buffer, hydrateStructure) {
        if (hydrateStructure === void 0) { hydrateStructure = lang_1$3.functional.identity; }
        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 ((0, neo4j_driver_core_1$z.isInt)(numberOrInteger)) {
                if (this._useBigInt) {
                    return numberOrInteger.toBigInt();
                }
                else if (this._disableLosslessIntegers) {
                    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, hydrateStructure);
        if (list !== null) {
            return list;
        }
        var byteArray = this._unpackByteArray(marker, buffer);
        if (byteArray !== null) {
            return byteArray;
        }
        var map = this._unpackMap(marker, markerHigh, markerLow, buffer, hydrateStructure);
        if (map !== null) {
            return map;
        }
        var struct = this._unpackStruct(marker, markerHigh, markerLow, buffer, hydrateStructure);
        if (struct !== null) {
            return struct;
        }
        throw (0, neo4j_driver_core_1$z.newError)('Unknown packed value with marker ' + marker.toString(16));
    };
    Unpacker.prototype.unpackInteger = function (buffer) {
        var marker = buffer.readUInt8();
        var result = this._unpackInteger(marker, buffer);
        if (result == null) {
            throw (0, neo4j_driver_core_1$z.newError)('Unable to unpack integer value with marker ' + marker.toString(16));
        }
        return result;
    };
    Unpacker.prototype._unpackBoolean = function (marker) {
        if (marker === TRUE) {
            return true;
        }
        else if (marker === FALSE) {
            return false;
        }
        else {
            return null;
        }
    };
    Unpacker.prototype._unpackNumberOrInteger = function (marker, buffer) {
        if (marker === FLOAT_64) {
            return buffer.readFloat64();
        }
        else {
            return this._unpackInteger(marker, buffer);
        }
    };
    Unpacker.prototype._unpackInteger = function (marker, buffer) {
        if (marker >= 0 && marker < 128) {
            return (0, neo4j_driver_core_1$z.int)(marker);
        }
        else if (marker >= 240 && marker < 256) {
            return (0, neo4j_driver_core_1$z.int)(marker - 256);
        }
        else if (marker === INT_8) {
            return (0, neo4j_driver_core_1$z.int)(buffer.readInt8());
        }
        else if (marker === INT_16) {
            return (0, neo4j_driver_core_1$z.int)(buffer.readInt16());
        }
        else if (marker === INT_32) {
            var b = buffer.readInt32();
            return (0, neo4j_driver_core_1$z.int)(b);
        }
        else if (marker === INT_64) {
            var high = buffer.readInt32();
            var low = buffer.readInt32();
            return new neo4j_driver_core_1$z.Integer(low, high);
        }
        else {
            return null;
        }
    };
    Unpacker.prototype._unpackString = function (marker, markerHigh, markerLow, buffer) {
        if (markerHigh === TINY_STRING) {
            return channel_1$3.utf8.decode(buffer, markerLow);
        }
        else if (marker === STRING_8) {
            return channel_1$3.utf8.decode(buffer, buffer.readUInt8());
        }
        else if (marker === STRING_16) {
            return channel_1$3.utf8.decode(buffer, buffer.readUInt16());
        }
        else if (marker === STRING_32) {
            return channel_1$3.utf8.decode(buffer, buffer.readUInt32());
        }
        else {
            return null;
        }
    };
    Unpacker.prototype._unpackList = function (marker, markerHigh, markerLow, buffer, hydrateStructure) {
        if (markerHigh === TINY_LIST) {
            return this._unpackListWithSize(markerLow, buffer, hydrateStructure);
        }
        else if (marker === LIST_8) {
            return this._unpackListWithSize(buffer.readUInt8(), buffer, hydrateStructure);
        }
        else if (marker === LIST_16) {
            return this._unpackListWithSize(buffer.readUInt16(), buffer, hydrateStructure);
        }
        else if (marker === LIST_32) {
            return this._unpackListWithSize(buffer.readUInt32(), buffer, hydrateStructure);
        }
        else {
            return null;
        }
    };
    Unpacker.prototype._unpackListWithSize = function (size, buffer, hydrateStructure) {
        var value = [];
        for (var i = 0; i < size; i++) {
            value.push(this.unpack(buffer, hydrateStructure));
        }
        return value;
    };
    Unpacker.prototype._unpackByteArray = function (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;
        }
    };
    Unpacker.prototype._unpackByteArrayWithSize = function (size, buffer) {
        var value = new Int8Array(size);
        for (var i = 0; i < size; i++) {
            value[i] = buffer.readInt8();
        }
        return value;
    };
    Unpacker.prototype._unpackMap = function (marker, markerHigh, markerLow, buffer, hydrateStructure) {
        if (markerHigh === TINY_MAP) {
            return this._unpackMapWithSize(markerLow, buffer, hydrateStructure);
        }
        else if (marker === MAP_8) {
            return this._unpackMapWithSize(buffer.readUInt8(), buffer, hydrateStructure);
        }
        else if (marker === MAP_16) {
            return this._unpackMapWithSize(buffer.readUInt16(), buffer, hydrateStructure);
        }
        else if (marker === MAP_32) {
            return this._unpackMapWithSize(buffer.readUInt32(), buffer, hydrateStructure);
        }
        else {
            return null;
        }
    };
    Unpacker.prototype._unpackMapWithSize = function (size, buffer, hydrateStructure) {
        var value = {};
        for (var i = 0; i < size; i++) {
            var key = this.unpack(buffer, hydrateStructure);
            value[key] = this.unpack(buffer, hydrateStructure);
        }
        return value;
    };
    Unpacker.prototype._unpackStruct = function (marker, markerHigh, markerLow, buffer, hydrateStructure) {
        if (markerHigh === TINY_STRUCT) {
            return this._unpackStructWithSize(markerLow, buffer, hydrateStructure);
        }
        else if (marker === STRUCT_8) {
            return this._unpackStructWithSize(buffer.readUInt8(), buffer, hydrateStructure);
        }
        else if (marker === STRUCT_16) {
            return this._unpackStructWithSize(buffer.readUInt16(), buffer, hydrateStructure);
        }
        else {
            return null;
        }
    };
    Unpacker.prototype._unpackStructWithSize = function (structSize, buffer, hydrateStructure) {
        var signature = buffer.readUInt8();
        var structure = new structure_1.Structure(signature, []);
        for (var i = 0; i < structSize; i++) {
            structure.fields.push(this.unpack(buffer, hydrateStructure));
        }
        return hydrateStructure(structure);
    };
    return Unpacker;
}());
packstreamV1.Unpacker = Unpacker$1;
function isIterable(obj) {
    if (obj == null) {
        return false;
    }
    return typeof obj[Symbol.iterator] === 'function';
}

var packstreamV2 = {};

/**
 * 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$n = (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$3 = (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$3 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$3 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$3(result, mod, k[i]);
        __setModuleDefault$3(result, mod);
        return result;
    };
})();
Object.defineProperty(packstreamV2, "__esModule", { value: true });
packstreamV2.Unpacker = packstreamV2.Packer = void 0;
var v1$1 = __importStar$3(packstreamV1);
var Packer = /** @class */ (function (_super) {
    __extends$n(Packer, _super);
    function Packer() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Packer.prototype.disableByteArrays = function () {
        throw new Error('Bolt V2 should always support byte arrays');
    };
    return Packer;
}(v1$1.Packer));
packstreamV2.Packer = Packer;
var Unpacker = /** @class */ (function (_super) {
    __extends$n(Unpacker, _super);
    /**
     * @constructor
     * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers.
     * @param {boolean} useBigInt if this unpacker should convert all received integers to Bigint
     */
    function Unpacker(disableLosslessIntegers, useBigInt) {
        if (disableLosslessIntegers === void 0) { disableLosslessIntegers = false; }
        if (useBigInt === void 0) { useBigInt = false; }
        return _super.call(this, disableLosslessIntegers, useBigInt) || this;
    }
    return Unpacker;
}(v1$1.Unpacker));
packstreamV2.Unpacker = Unpacker;

/**
 * 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 __createBinding$2 = (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$2 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$2 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$2(result, mod, k[i]);
        __setModuleDefault$2(result, mod);
        return result;
    };
})();
Object.defineProperty(packstream, "__esModule", { value: true });
packstream.structure = packstream.v2 = packstream.v1 = void 0;
var v1 = __importStar$2(packstreamV1);
packstream.v1 = v1;
var v2 = __importStar$2(packstreamV2);
packstream.v2 = v2;
var structure = __importStar$2(structure$1);
packstream.structure = structure;
packstream.default = v2;

var requestMessage = {};

/**
 * 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(requestMessage, "__esModule", { value: true });
requestMessage.SIGNATURES = void 0;
var neo4j_driver_core_1$y = lib$1;
var _a$c = neo4j_driver_core_1$y.internal.constants, ACCESS_MODE_READ = _a$c.ACCESS_MODE_READ, FETCH_ALL$5 = _a$c.FETCH_ALL, assertString = neo4j_driver_core_1$y.internal.util.assertString;
/* eslint-disable no-unused-vars */
// Signature bytes for each request message type
var INIT = 0x01; // 0000 0001 // INIT <user_agent> <authentication_token>
var RESET = 0x0f; // 0000 1111 // RESET
var RUN = 0x10; // 0001 0000 // RUN <query> <parameters>
var PULL_ALL = 0x3f; // 0011 1111 // PULL_ALL
var HELLO = 0x01; // 0000 0001 // HELLO <metadata>
var GOODBYE = 0x02; // 0000 0010 // GOODBYE
var BEGIN = 0x11; // 0001 0001 // BEGIN <metadata>
var COMMIT = 0x12; // 0001 0010 // COMMIT
var ROLLBACK = 0x13; // 0001 0011 // ROLLBACK
var TELEMETRY = 0x54; // 0101 0100 // TELEMETRY <api>
var ROUTE = 0x66; // 0110 0110 // ROUTE
var LOGON = 0x6A; // LOGON
var LOGOFF = 0x6B; // LOGOFF
var DISCARD = 0x2f; // 0010 1111 // DISCARD
var PULL = 0x3f; // 0011 1111 // PULL
var READ_MODE = 'r';
/* eslint-enable no-unused-vars */
var NO_STATEMENT_ID = -1;
var SIGNATURES = Object.freeze({
    INIT: INIT,
    RESET: RESET,
    RUN: RUN,
    PULL_ALL: PULL_ALL,
    HELLO: HELLO,
    GOODBYE: GOODBYE,
    BEGIN: BEGIN,
    COMMIT: COMMIT,
    ROLLBACK: ROLLBACK,
    TELEMETRY: TELEMETRY,
    ROUTE: ROUTE,
    LOGON: LOGON,
    LOGOFF: LOGOFF,
    DISCARD: DISCARD,
    PULL: PULL
});
requestMessage.SIGNATURES = SIGNATURES;
var RequestMessage = /** @class */ (function () {
    function RequestMessage(signature, fields, toString) {
        this.signature = signature;
        this.fields = fields;
        this.toString = toString;
    }
    /**
     * Create a new INIT message.
     * @param {string} clientName the client name.
     * @param {Object} authToken the authentication token.
     * @return {RequestMessage} new INIT message.
     */
    RequestMessage.init = function (clientName, authToken) {
        return new RequestMessage(INIT, [clientName, authToken], function () { return "INIT ".concat(clientName, " {...}"); });
    };
    /**
     * Create a new RUN message.
     * @param {string} query the cypher query.
     * @param {Object} parameters the query parameters.
     * @return {RequestMessage} new RUN message.
     */
    RequestMessage.run = function (query, parameters) {
        return new RequestMessage(RUN, [query, parameters], function () { return "RUN ".concat(query, " ").concat(neo4j_driver_core_1$y.json.stringify(parameters)); });
    };
    /**
     * Get a PULL_ALL message.
     * @return {RequestMessage} the PULL_ALL message.
     */
    RequestMessage.pullAll = function () {
        return PULL_ALL_MESSAGE;
    };
    /**
     * Get a RESET message.
     * @return {RequestMessage} the RESET message.
     */
    RequestMessage.reset = function () {
        return RESET_MESSAGE;
    };
    /**
     * Create a new HELLO message.
     * @param {string} userAgent the user agent.
     * @param {Object} authToken the authentication token.
     * @param {Object} optional server side routing, set to routing context to turn on server side routing (> 4.1)
     * @return {RequestMessage} new HELLO message.
     */
    RequestMessage.hello = function (userAgent, authToken, routing, patchs) {
        if (routing === void 0) { routing = null; }
        if (patchs === void 0) { patchs = null; }
        var metadata = Object.assign({ user_agent: userAgent }, authToken);
        if (routing) {
            metadata.routing = routing;
        }
        if (patchs) {
            metadata.patch_bolt = patchs;
        }
        return new RequestMessage(HELLO, [metadata], function () { return "HELLO {user_agent: '".concat(userAgent, "', ...}"); });
    };
    /**
     * Create a new HELLO message.
     * @param {string} userAgent the user agent.
     * @param {Object} optional server side routing, set to routing context to turn on server side routing (> 4.1)
     * @return {RequestMessage} new HELLO message.
     */
    RequestMessage.hello5x1 = function (userAgent, routing) {
        if (routing === void 0) { routing = null; }
        var metadata = { user_agent: userAgent };
        if (routing) {
            metadata.routing = routing;
        }
        return new RequestMessage(HELLO, [metadata], function () { return "HELLO {user_agent: '".concat(userAgent, "', ...}"); });
    };
    /**
     * Create a new HELLO message.
     * @param {string} userAgent the user agent.
     * @param {NotificationFilter} notificationFilter the notification filter configured
     * @param {Object} routing server side routing, set to routing context to turn on server side routing (> 4.1)
     * @return {RequestMessage} new HELLO message.
     */
    RequestMessage.hello5x2 = function (userAgent, notificationFilter, routing) {
        if (notificationFilter === void 0) { notificationFilter = null; }
        if (routing === void 0) { routing = null; }
        var metadata = { user_agent: userAgent };
        appendLegacyNotificationFilterToMetadata(metadata, notificationFilter);
        if (routing) {
            metadata.routing = routing;
        }
        return new RequestMessage(HELLO, [metadata], function () { return "HELLO ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    /**
     * Create a new HELLO message.
     * @param {string} userAgent the user agent.
     * @param {string} boltAgent the bolt agent.
     * @param {NotificationFilter} notificationFilter the notification filter configured
     * @param {Object} routing server side routing, set to routing context to turn on server side routing (> 4.1)
     * @return {RequestMessage} new HELLO message.
     */
    RequestMessage.hello5x3 = function (userAgent, boltAgent, notificationFilter, routing) {
        if (notificationFilter === void 0) { notificationFilter = null; }
        if (routing === void 0) { routing = null; }
        var metadata = {};
        if (userAgent) {
            metadata.user_agent = userAgent;
        }
        if (boltAgent) {
            metadata.bolt_agent = {
                product: boltAgent.product,
                platform: boltAgent.platform,
                language: boltAgent.language,
                language_details: boltAgent.languageDetails
            };
        }
        appendLegacyNotificationFilterToMetadata(metadata, notificationFilter);
        if (routing) {
            metadata.routing = routing;
        }
        return new RequestMessage(HELLO, [metadata], function () { return "HELLO ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    /**
     * Create a new HELLO message.
     * @param {string} userAgent the user agent.
     * @param {string} boltAgent the bolt agent.
     * @param {NotificationFilter} notificationFilter the notification filter configured
     * @param {Object} routing server side routing, set to routing context to turn on server side routing (> 4.1)
     * @return {RequestMessage} new HELLO message.
     */
    RequestMessage.hello5x5 = function (userAgent, boltAgent, notificationFilter, routing) {
        if (notificationFilter === void 0) { notificationFilter = null; }
        if (routing === void 0) { routing = null; }
        var metadata = {};
        if (userAgent) {
            metadata.user_agent = userAgent;
        }
        if (boltAgent) {
            metadata.bolt_agent = {
                product: boltAgent.product,
                platform: boltAgent.platform,
                language: boltAgent.language,
                language_details: boltAgent.languageDetails
            };
        }
        appendGqlNotificationFilterToMetadata(metadata, notificationFilter);
        if (routing) {
            metadata.routing = routing;
        }
        return new RequestMessage(HELLO, [metadata], function () { return "HELLO ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    /**
     * Create a new LOGON message.
     *
     * @param {object} authToken The auth token
     * @returns {RequestMessage} new LOGON message
     */
    RequestMessage.logon = function (authToken) {
        return new RequestMessage(LOGON, [authToken], function () { return 'LOGON { ... }'; });
    };
    /**
     * Create a new LOGOFF message.
     *
     * @returns {RequestMessage} new LOGOFF message
     */
    RequestMessage.logoff = function () {
        return new RequestMessage(LOGOFF, [], function () { return 'LOGOFF'; });
    };
    /**
     * Create a new BEGIN message.
     * @param {Bookmarks} bookmarks the bookmarks.
     * @param {TxConfig} txConfig the configuration.
     * @param {string} database the database name.
     * @param {string} mode the access mode.
     * @param {string} impersonatedUser the impersonated user.
     * @param {NotificationFilter} notificationFilter the notification filter
     * @return {RequestMessage} new BEGIN message.
     */
    RequestMessage.begin = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter;
        var metadata = buildTxMetadata(bookmarks, txConfig, database, mode, impersonatedUser, notificationFilter);
        return new RequestMessage(BEGIN, [metadata], function () { return "BEGIN ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    /**
     * Create a new BEGIN message.
     * @param {Bookmarks} bookmarks the bookmarks.
     * @param {TxConfig} txConfig the configuration.
     * @param {string} database the database name.
     * @param {string} mode the access mode.
     * @param {string} impersonatedUser the impersonated user.
     * @param {NotificationFilter} notificationFilter the notification filter
     * @return {RequestMessage} new BEGIN message.
     */
    RequestMessage.begin5x5 = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter;
        var metadata = buildTxMetadata(bookmarks, txConfig, database, mode, impersonatedUser, notificationFilter, {
            appendNotificationFilter: appendGqlNotificationFilterToMetadata
        });
        return new RequestMessage(BEGIN, [metadata], function () { return "BEGIN ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    /**
     * Get a COMMIT message.
     * @return {RequestMessage} the COMMIT message.
     */
    RequestMessage.commit = function () {
        return COMMIT_MESSAGE;
    };
    /**
     * Get a ROLLBACK message.
     * @return {RequestMessage} the ROLLBACK message.
     */
    RequestMessage.rollback = function () {
        return ROLLBACK_MESSAGE;
    };
    /**
     * Create a new RUN message with additional metadata.
     * @param {string} query the cypher query.
     * @param {Object} parameters the query parameters.
     * @param {Object} extra - extra params
     * @param {Bookmarks} extra.bookmarks the bookmarks.
     * @param {TxConfig} extra.txConfig the configuration.
     * @param {string} extra.database the database name.
     * @param {string} extra.mode the access mode.
     * @param {string} extra.impersonatedUser the impersonated user.
     * @param {notificationFilter} extra.notificationFilter the notification filter
     * @return {RequestMessage} new RUN message with additional metadata.
     */
    RequestMessage.runWithMetadata = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter;
        var metadata = buildTxMetadata(bookmarks, txConfig, database, mode, impersonatedUser, notificationFilter);
        return new RequestMessage(RUN, [query, parameters, metadata], function () {
            return "RUN ".concat(query, " ").concat(neo4j_driver_core_1$y.json.stringify(parameters), " ").concat(neo4j_driver_core_1$y.json.stringify(metadata));
        });
    };
    /**
     * Create a new RUN message with additional metadata.
     * @param {string} query the cypher query.
     * @param {Object} parameters the query parameters.
     * @param {Object} extra - extra params
     * @param {Bookmarks} extra.bookmarks the bookmarks.
     * @param {TxConfig} extra.txConfig the configuration.
     * @param {string} extra.database the database name.
     * @param {string} extra.mode the access mode.
     * @param {string} extra.impersonatedUser the impersonated user.
     * @param {notificationFilter} extra.notificationFilter the notification filter
     * @return {RequestMessage} new RUN message with additional metadata.
     */
    RequestMessage.runWithMetadata5x5 = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter;
        var metadata = buildTxMetadata(bookmarks, txConfig, database, mode, impersonatedUser, notificationFilter, {
            appendNotificationFilter: appendGqlNotificationFilterToMetadata
        });
        return new RequestMessage(RUN, [query, parameters, metadata], function () {
            return "RUN ".concat(query, " ").concat(neo4j_driver_core_1$y.json.stringify(parameters), " ").concat(neo4j_driver_core_1$y.json.stringify(metadata));
        });
    };
    /**
     * Get a GOODBYE message.
     * @return {RequestMessage} the GOODBYE message.
     */
    RequestMessage.goodbye = function () {
        return GOODBYE_MESSAGE;
    };
    /**
     * Generates a new PULL message with additional metadata.
     * @param {Integer|number} stmtId
     * @param {Integer|number} n
     * @return {RequestMessage} the PULL message.
     */
    RequestMessage.pull = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.stmtId, stmtId = _c === void 0 ? NO_STATEMENT_ID : _c, _d = _b.n, n = _d === void 0 ? FETCH_ALL$5 : _d;
        var metadata = buildStreamMetadata(stmtId === null || stmtId === undefined ? NO_STATEMENT_ID : stmtId, n || FETCH_ALL$5);
        return new RequestMessage(PULL, [metadata], function () { return "PULL ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    /**
     * Generates a new DISCARD message with additional metadata.
     * @param {Integer|number} stmtId
     * @param {Integer|number} n
     * @return {RequestMessage} the PULL message.
     */
    RequestMessage.discard = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.stmtId, stmtId = _c === void 0 ? NO_STATEMENT_ID : _c, _d = _b.n, n = _d === void 0 ? FETCH_ALL$5 : _d;
        var metadata = buildStreamMetadata(stmtId === null || stmtId === undefined ? NO_STATEMENT_ID : stmtId, n || FETCH_ALL$5);
        return new RequestMessage(DISCARD, [metadata], function () { return "DISCARD ".concat(neo4j_driver_core_1$y.json.stringify(metadata)); });
    };
    RequestMessage.telemetry = function (_a) {
        var api = _a.api;
        var parsedApi = (0, neo4j_driver_core_1$y.int)(api);
        return new RequestMessage(TELEMETRY, [parsedApi], function () { return "TELEMETRY ".concat(parsedApi.toString()); });
    };
    /**
     * Generate the ROUTE message, this message is used to fetch the routing table from the server
     *
     * @param {object} routingContext The routing context used to define the routing table. Multi-datacenter deployments is one of its use cases
     * @param {string[]} bookmarks The list of the bookmarks should be used
     * @param {string} databaseName The name of the database to get the routing table for.
     * @return {RequestMessage} the ROUTE message.
     */
    RequestMessage.route = function (routingContext, bookmarks, databaseName) {
        if (routingContext === void 0) { routingContext = {}; }
        if (bookmarks === void 0) { bookmarks = []; }
        if (databaseName === void 0) { databaseName = null; }
        return new RequestMessage(ROUTE, [routingContext, bookmarks, databaseName], function () {
            return "ROUTE ".concat(neo4j_driver_core_1$y.json.stringify(routingContext), " ").concat(neo4j_driver_core_1$y.json.stringify(bookmarks), " ").concat(databaseName);
        });
    };
    /**
     * Generate the ROUTE message, this message is used to fetch the routing table from the server
     *
     * @param {object} routingContext The routing context used to define the routing table. Multi-datacenter deployments is one of its use cases
     * @param {string[]} bookmarks The list of the bookmarks should be used
     * @param {object} databaseContext The context inforamtion of the database to get the routing table for.
     * @param {string} databaseContext.databaseName The name of the database to get the routing table.
     * @param {string} databaseContext.impersonatedUser The name of the user to impersonation when getting the routing table.
     * @return {RequestMessage} the ROUTE message.
     */
    RequestMessage.routeV4x4 = function (routingContext, bookmarks, databaseContext) {
        if (routingContext === void 0) { routingContext = {}; }
        if (bookmarks === void 0) { bookmarks = []; }
        if (databaseContext === void 0) { databaseContext = {}; }
        var dbContext = {};
        if (databaseContext.databaseName) {
            dbContext.db = databaseContext.databaseName;
        }
        if (databaseContext.impersonatedUser) {
            dbContext.imp_user = databaseContext.impersonatedUser;
        }
        return new RequestMessage(ROUTE, [routingContext, bookmarks, dbContext], function () {
            return "ROUTE ".concat(neo4j_driver_core_1$y.json.stringify(routingContext), " ").concat(neo4j_driver_core_1$y.json.stringify(bookmarks), " ").concat(neo4j_driver_core_1$y.json.stringify(dbContext));
        });
    };
    return RequestMessage;
}());
requestMessage.default = RequestMessage;
/**
 * Create an object that represent transaction metadata.
 * @param {Bookmarks} bookmarks the bookmarks.
 * @param {TxConfig} txConfig the configuration.
 * @param {string} database the database name.
 * @param {string} mode the access mode.
 * @param {string} impersonatedUser the impersonated user mode.
 * @param {notificationFilter} notificationFilter the notification filter
 * @param {Object} functions Transformation functions applied to metadata
 * @param {function(metadata,notificationFilter):void} functions.appendNotificationFilter Changes metadata by appending the Notification Filter to it.
 * @return {Object} a metadata object.
 */
function buildTxMetadata(bookmarks, txConfig, database, mode, impersonatedUser, notificationFilter, functions) {
    var _a;
    if (functions === void 0) { functions = {}; }
    var metadata = {};
    if (!bookmarks.isEmpty()) {
        metadata.bookmarks = bookmarks.values();
    }
    if (txConfig.timeout !== null) {
        metadata.tx_timeout = txConfig.timeout;
    }
    if (txConfig.metadata) {
        metadata.tx_metadata = txConfig.metadata;
    }
    if (database) {
        metadata.db = assertString(database, 'database');
    }
    if (impersonatedUser) {
        metadata.imp_user = assertString(impersonatedUser, 'impersonatedUser');
    }
    if (mode === ACCESS_MODE_READ) {
        metadata.mode = READ_MODE;
    }
    var appendNotificationFilter = (_a = functions.appendNotificationFilter) !== null && _a !== void 0 ? _a : appendLegacyNotificationFilterToMetadata;
    appendNotificationFilter(metadata, notificationFilter);
    return metadata;
}
/**
 * Create an object that represents streaming metadata.
 * @param {Integer|number} stmtId The query id to stream its results.
 * @param {Integer|number} n The number of records to stream.
 * @returns {Object} a metadata object.
 */
function buildStreamMetadata(stmtId, n) {
    var metadata = { n: (0, neo4j_driver_core_1$y.int)(n) };
    if (stmtId !== NO_STATEMENT_ID) {
        metadata.qid = (0, neo4j_driver_core_1$y.int)(stmtId);
    }
    return metadata;
}
function appendLegacyNotificationFilterToMetadata(metadata, notificationFilter) {
    if (notificationFilter) {
        if (notificationFilter.minimumSeverityLevel) {
            metadata.notifications_minimum_severity = notificationFilter.minimumSeverityLevel;
        }
        if (notificationFilter.disabledCategories) {
            metadata.notifications_disabled_categories = notificationFilter.disabledCategories;
        }
        if (notificationFilter.disabledClassifications) {
            metadata.notifications_disabled_categories = notificationFilter.disabledClassifications;
        }
    }
}
function appendGqlNotificationFilterToMetadata(metadata, notificationFilter) {
    if (notificationFilter) {
        if (notificationFilter.minimumSeverityLevel) {
            metadata.notifications_minimum_severity = notificationFilter.minimumSeverityLevel;
        }
        if (notificationFilter.disabledCategories) {
            metadata.notifications_disabled_classifications = notificationFilter.disabledCategories;
        }
        if (notificationFilter.disabledClassifications) {
            metadata.notifications_disabled_classifications = notificationFilter.disabledClassifications;
        }
    }
}
// constants for messages that never change
var PULL_ALL_MESSAGE = new RequestMessage(PULL_ALL, [], function () { return 'PULL_ALL'; });
var RESET_MESSAGE = new RequestMessage(RESET, [], function () { return 'RESET'; });
var COMMIT_MESSAGE = new RequestMessage(COMMIT, [], function () { return 'COMMIT'; });
var ROLLBACK_MESSAGE = new RequestMessage(ROLLBACK, [], function () { return 'ROLLBACK'; });
var GOODBYE_MESSAGE = new RequestMessage(GOODBYE, [], function () { return 'GOODBYE'; });

var boltProtocolV1_transformer = {};

var transformer = {};

/**
 * 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(transformer, "__esModule", { value: true });
transformer.TypeTransformer = void 0;
var packstream_1$6 = packstream;
var neo4j_driver_core_1$x = lib$1;
var objectUtil = neo4j_driver_core_1$x.internal.objectUtil;
/**
 * Class responsible for applying the expected {@link TypeTransformer} to
 * transform the driver types from and to {@link struct.Structure}
 */
var Transformer = /** @class */ (function () {
    /**
     * Constructor
     * @param {TypeTransformer[]} transformers The type transformers
     */
    function Transformer(transformers) {
        this._transformers = transformers;
        this._transformersPerSignature = new Map(transformers.map(function (typeTransformer) { return [typeTransformer.signature, typeTransformer]; }));
        this.fromStructure = this.fromStructure.bind(this);
        this.toStructure = this.toStructure.bind(this);
        Object.freeze(this);
    }
    /**
     * Transform from structure to specific object
     *
     * @param {struct.Structure} struct The structure
     * @returns {<T>|structure.Structure} The driver object or the structure if the transformer was not found.
     */
    Transformer.prototype.fromStructure = function (struct) {
        try {
            if (struct instanceof packstream_1$6.structure.Structure && this._transformersPerSignature.has(struct.signature)) {
                var fromStructure = this._transformersPerSignature.get(struct.signature).fromStructure;
                return fromStructure(struct);
            }
            return struct;
        }
        catch (error) {
            return objectUtil.createBrokenObject(error);
        }
    };
    /**
     * Transform from object to structure
     * @param {<T>} type The object to be transoformed in structure
     * @returns {<T>|structure.Structure} The structure or the object, if any transformer was found
     */
    Transformer.prototype.toStructure = function (type) {
        var transformer = this._transformers.find(function (_a) {
            var isTypeInstance = _a.isTypeInstance;
            return isTypeInstance(type);
        });
        if (transformer !== undefined) {
            return transformer.toStructure(type);
        }
        return type;
    };
    return Transformer;
}());
transformer.default = Transformer;
/**
 * @callback isTypeInstanceFunction
 * @param {any} object The object
 * @return {boolean} is instance of
 */
/**
 * @callback toStructureFunction
 * @param {any} object The object
 * @return {structure.Structure} The structure
 */
/**
 * @callback fromStructureFunction
 * @param {structure.Structure} struct The structure
 * @return {any} The object
 */
/**
 * Class responsible for grouping the properties of a TypeTransformer
 */
var TypeTransformer = /** @class */ (function () {
    /**
     * @param {Object} param
     * @param {number} param.signature The signature of the structure
     * @param {isTypeInstanceFunction} param.isTypeInstance The function which checks if object is
     *                instance of the type described by the TypeTransformer
     * @param {toStructureFunction} param.toStructure The function which gets the object and converts to structure
     * @param {fromStructureFunction} param.fromStructure The function which get the structure and covnverts to object
     */
    function TypeTransformer(_a) {
        var signature = _a.signature, fromStructure = _a.fromStructure, toStructure = _a.toStructure, isTypeInstance = _a.isTypeInstance;
        this.signature = signature;
        this.isTypeInstance = isTypeInstance;
        this.fromStructure = fromStructure;
        this.toStructure = toStructure;
        Object.freeze(this);
    }
    /**
     * @param {Object} param
     * @param {number} [param.signature] The signature of the structure
     * @param {isTypeInstanceFunction} [param.isTypeInstance] The function which checks if object is
     *                instance of the type described by the TypeTransformer
     * @param {toStructureFunction} [param.toStructure] The function which gets the object and converts to structure
     * @param {fromStructureFunction} pparam.fromStructure] The function which get the structure and covnverts to object
     * @returns {TypeTransformer} A new type transform extends with new methods
     */
    TypeTransformer.prototype.extendsWith = function (_a) {
        var signature = _a.signature, fromStructure = _a.fromStructure, toStructure = _a.toStructure, isTypeInstance = _a.isTypeInstance;
        return new TypeTransformer({
            signature: signature || this.signature,
            fromStructure: fromStructure || this.fromStructure,
            toStructure: toStructure || this.toStructure,
            isTypeInstance: isTypeInstance || this.isTypeInstance
        });
    };
    return TypeTransformer;
}());
transformer.TypeTransformer = TypeTransformer;

/**
 * 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 __read$6 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(boltProtocolV1_transformer, "__esModule", { value: true });
var neo4j_driver_core_1$w = lib$1;
var packstream_1$5 = packstream;
var transformer_1$i = transformer;
var PROTOCOL_ERROR$2 = neo4j_driver_core_1$w.error.PROTOCOL_ERROR;
var NODE = 0x4e;
var NODE_STRUCT_SIZE$1 = 3;
var RELATIONSHIP = 0x52;
var RELATIONSHIP_STRUCT_SIZE$1 = 5;
var UNBOUND_RELATIONSHIP = 0x72;
var UNBOUND_RELATIONSHIP_STRUCT_SIZE$1 = 3;
var PATH = 0x50;
var PATH_STRUCT_SIZE = 3;
/**
 * Creates the Node Transformer
 * @returns {TypeTransformer}
 */
function createNodeTransformer$1() {
    return new transformer_1$i.TypeTransformer({
        signature: NODE,
        isTypeInstance: function (object) { return object instanceof neo4j_driver_core_1$w.Node; },
        toStructure: function (object) {
            throw (0, neo4j_driver_core_1$w.newError)("It is not allowed to pass nodes in query parameters, given: ".concat(object), PROTOCOL_ERROR$2);
        },
        fromStructure: function (struct) {
            packstream_1$5.structure.verifyStructSize('Node', NODE_STRUCT_SIZE$1, struct.size);
            var _a = __read$6(struct.fields, 3), identity = _a[0], labels = _a[1], properties = _a[2];
            return new neo4j_driver_core_1$w.Node(identity, labels, properties);
        }
    });
}
/**
 * Creates the Relationship Transformer
 * @returns {TypeTransformer}
 */
function createRelationshipTransformer$1() {
    return new transformer_1$i.TypeTransformer({
        signature: RELATIONSHIP,
        isTypeInstance: function (object) { return object instanceof neo4j_driver_core_1$w.Relationship; },
        toStructure: function (object) {
            throw (0, neo4j_driver_core_1$w.newError)("It is not allowed to pass relationships in query parameters, given: ".concat(object), PROTOCOL_ERROR$2);
        },
        fromStructure: function (struct) {
            packstream_1$5.structure.verifyStructSize('Relationship', RELATIONSHIP_STRUCT_SIZE$1, struct.size);
            var _a = __read$6(struct.fields, 5), identity = _a[0], startNodeIdentity = _a[1], endNodeIdentity = _a[2], type = _a[3], properties = _a[4];
            return new neo4j_driver_core_1$w.Relationship(identity, startNodeIdentity, endNodeIdentity, type, properties);
        }
    });
}
/**
 * Creates the Unbound Relationship Transformer
 * @returns {TypeTransformer}
 */
function createUnboundRelationshipTransformer$1() {
    return new transformer_1$i.TypeTransformer({
        signature: UNBOUND_RELATIONSHIP,
        isTypeInstance: function (object) { return object instanceof neo4j_driver_core_1$w.UnboundRelationship; },
        toStructure: function (object) {
            throw (0, neo4j_driver_core_1$w.newError)("It is not allowed to pass unbound relationships in query parameters, given: ".concat(object), PROTOCOL_ERROR$2);
        },
        fromStructure: function (struct) {
            packstream_1$5.structure.verifyStructSize('UnboundRelationship', UNBOUND_RELATIONSHIP_STRUCT_SIZE$1, struct.size);
            var _a = __read$6(struct.fields, 3), identity = _a[0], type = _a[1], properties = _a[2];
            return new neo4j_driver_core_1$w.UnboundRelationship(identity, type, properties);
        }
    });
}
/**
 * Creates the Path Transformer
 * @returns {TypeTransformer}
 */
function createPathTransformer() {
    return new transformer_1$i.TypeTransformer({
        signature: PATH,
        isTypeInstance: function (object) { return object instanceof neo4j_driver_core_1$w.Path; },
        toStructure: function (object) {
            throw (0, neo4j_driver_core_1$w.newError)("It is not allowed to pass paths in query parameters, given: ".concat(object), PROTOCOL_ERROR$2);
        },
        fromStructure: function (struct) {
            packstream_1$5.structure.verifyStructSize('Path', PATH_STRUCT_SIZE, struct.size);
            var _a = __read$6(struct.fields, 3), nodes = _a[0], rels = _a[1], sequence = _a[2];
            var segments = [];
            var prevNode = nodes[0];
            for (var i = 0; i < sequence.length; i += 2) {
                var nextNode = nodes[sequence[i + 1]];
                var relIndex = (0, neo4j_driver_core_1$w.toNumber)(sequence[i]);
                var rel = void 0;
                if (relIndex > 0) {
                    rel = rels[relIndex - 1];
                    if (rel instanceof neo4j_driver_core_1$w.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.bindTo(prevNode, nextNode);
                    }
                }
                else {
                    rel = rels[-relIndex - 1];
                    if (rel instanceof neo4j_driver_core_1$w.UnboundRelationship) {
                        // See above
                        rels[-relIndex - 1] = rel = rel.bindTo(nextNode, prevNode);
                    }
                }
                // Done hydrating one path segment.
                segments.push(new neo4j_driver_core_1$w.PathSegment(prevNode, rel, nextNode));
                prevNode = nextNode;
            }
            return new neo4j_driver_core_1$w.Path(nodes[0], nodes[nodes.length - 1], segments);
        }
    });
}
boltProtocolV1_transformer.default = {
    createNodeTransformer: createNodeTransformer$1,
    createRelationshipTransformer: createRelationshipTransformer$1,
    createUnboundRelationshipTransformer: createUnboundRelationshipTransformer$1,
    createPathTransformer: createPathTransformer
};

var __assign$r = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$r = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$r.apply(this, arguments);
};
var __createBinding$1 = (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$1 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar$1 = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding$1(result, mod, k[i]);
        __setModuleDefault$1(result, mod);
        return result;
    };
})();
var __importDefault$F = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV1, "__esModule", { value: true });
/**
 * 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 bolt_protocol_util_1$7 = boltProtocolUtil;
var packstream_1$4 = packstream;
var request_message_1$c = __importStar$1(requestMessage);
var stream_observers_1$c = streamObservers;
var neo4j_driver_core_1$v = lib$1;
var bolt_protocol_v1_transformer_1$1 = __importDefault$F(boltProtocolV1_transformer);
var transformer_1$h = __importDefault$F(transformer);
var Bookmarks$3 = neo4j_driver_core_1$v.internal.bookmarks.Bookmarks, _a$b = neo4j_driver_core_1$v.internal.constants, ACCESS_MODE_WRITE = _a$b.ACCESS_MODE_WRITE, BOLT_PROTOCOL_V1 = _a$b.BOLT_PROTOCOL_V1; neo4j_driver_core_1$v.internal.logger.Logger; var TxConfig$2 = neo4j_driver_core_1$v.internal.txConfig.TxConfig;
var DEFAULT_DIAGNOSTIC_RECORD$3 = Object.freeze({
    OPERATION: '',
    OPERATION_CODE: '0',
    CURRENT_SCHEMA: '/'
});
var BoltProtocol$g = /** @class */ (function () {
    /**
     * @callback CreateResponseHandler Creates the response handler
     * @param {BoltProtocol} protocol The bolt protocol
     * @returns {ResponseHandler} The response handler
     */
    /**
     * @callback OnProtocolError Handles protocol error
     * @param {string} error The description
     */
    /**
     * @constructor
     * @param {Object} server the server informatio.
     * @param {Chunker} chunker the chunker.
     * @param {Object} packstreamConfig Packstream configuration
     * @param {boolean} packstreamConfig.disableLosslessIntegers if this connection should convert all received integers to native JS numbers.
     * @param {boolean} packstreamConfig.useBigInt if this connection should convert all received integers to native BigInt numbers.
     * @param {CreateResponseHandler} createResponseHandler Function which creates the response handler
     * @param {Logger} log the logger
     * @param {OnProtocolError} onProtocolError handles protocol errors
     */
    function BoltProtocol(server, chunker, _a, createResponseHandler, log, onProtocolError) {
        var _b = _a === void 0 ? {} : _a, disableLosslessIntegers = _b.disableLosslessIntegers, useBigInt = _b.useBigInt;
        if (createResponseHandler === void 0) { createResponseHandler = function () { return null; }; }
        this._server = server || {};
        this._chunker = chunker;
        this._packer = this._createPacker(chunker);
        this._unpacker = this._createUnpacker(disableLosslessIntegers, useBigInt);
        this._responseHandler = createResponseHandler(this);
        this._log = log;
        this._onProtocolError = onProtocolError;
        this._fatalError = null;
        this._lastMessageSignature = null;
        this._config = { disableLosslessIntegers: disableLosslessIntegers, useBigInt: useBigInt };
    }
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$h.default(Object.values(bolt_protocol_v1_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "version", {
        /**
         * Returns the numerical version identifier for this protocol
         */
        get: function () {
            return BOLT_PROTOCOL_V1;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "supportsReAuth", {
        /**
         * @property {boolean} supportsReAuth Either if the protocol version supports re-auth or not.
         */
        get: function () {
            return false;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "initialized", {
        /**
         * @property {boolean} initialized Either if the protocol was initialized or not
         */
        get: function () {
            return !!this._initialized;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "authToken", {
        /**
         * @property {object} authToken The token used in the last login
         */
        get: function () {
            return this._authToken;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get the packer.
     * @return {Packer} the protocol's packer.
     */
    BoltProtocol.prototype.packer = function () {
        return this._packer;
    };
    /**
     * Creates a packable function out of the provided value
     * @param x the value to pack
     * @returns Function
     */
    BoltProtocol.prototype.packable = function (x) {
        return this._packer.packable(x, this.transformer.toStructure);
    };
    /**
     * Get the unpacker.
     * @return {Unpacker} the protocol's unpacker.
     */
    BoltProtocol.prototype.unpacker = function () {
        return this._unpacker;
    };
    /**
     * Unpack a buffer
     * @param {Buffer} buf
     * @returns {any|null} The unpacked value
     */
    BoltProtocol.prototype.unpack = function (buf) {
        return this._unpacker.unpack(buf, this.transformer.fromStructure);
    };
    /**
     * Transform metadata received in SUCCESS message before it is passed to the handler.
     * @param {Object} metadata the received metadata.
     * @return {Object} transformed metadata.
     */
    BoltProtocol.prototype.transformMetadata = function (metadata) {
        return metadata;
    };
    BoltProtocol.prototype.enrichErrorMetadata = function (metadata) {
        return __assign$r(__assign$r({}, metadata), { diagnostic_record: metadata.diagnostic_record !== null ? __assign$r(__assign$r({}, DEFAULT_DIAGNOSTIC_RECORD$3), metadata.diagnostic_record) : null });
    };
    /**
     * Perform initialization and authentication of the underlying connection.
     * @param {Object} param
     * @param {string} param.userAgent the user agent.
     * @param {Object} param.authToken the authentication token.
     * @param {NotificationFilter} param.notificationFilter the notification filter.
     * @param {function(err: Error)} param.onError the callback to invoke on error.
     * @param {function()} param.onComplete the callback to invoke on completion.
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var observer = new stream_observers_1$c.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) { return _this._onLoginCompleted(metadata, onComplete); }
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$7.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$c.default.init(userAgent, authToken), observer, true);
        return observer;
    };
    /**
     * Performs logoff of the underlying connection
     *
     * @param {Object} param
     * @param {function(err: Error)} param.onError the callback to invoke on error.
     * @param {function()} param.onComplete the callback to invoke on completion.
     * @param {boolean} param.flush whether to flush the buffered messages.
     *
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.logoff = function (_a) {
        var _b = _a === void 0 ? {} : _a, onComplete = _b.onComplete, onError = _b.onError; _b.flush;
        var observer = new stream_observers_1$c.LogoffObserver({
            onCompleted: onComplete,
            onError: onError
        });
        // TODO: Verify the Neo4j version in the message
        var error = (0, neo4j_driver_core_1$v.newError)('Driver is connected to a database that does not support logoff. ' +
            'Please upgrade to Neo4j 5.5.0 or later in order to use this functionality.');
        // unsupported API was used, consider this a fatal error for the current connection
        this._onProtocolError(error.message);
        observer.onError(error);
        throw error;
    };
    /**
     * Performs login of the underlying connection
     *
     * @param {Object} args
     * @param {Object} args.authToken the authentication token.
     * @param {function(err: Error)} args.onError the callback to invoke on error.
     * @param {function()} args.onComplete the callback to invoke on completion.
     * @param {boolean} args.flush whether to flush the buffered messages.
     *
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.logon = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, authToken = _b.authToken, onComplete = _b.onComplete, onError = _b.onError; _b.flush;
        var observer = new stream_observers_1$c.LoginObserver({
            onCompleted: function () { return _this._onLoginCompleted({}, authToken, onComplete); },
            onError: function (error) { return _this._onLoginError(error, onError); }
        });
        // TODO: Verify the Neo4j version in the message
        var error = (0, neo4j_driver_core_1$v.newError)('Driver is connected to a database that does not support logon. ' +
            'Please upgrade to Neo4j 5.5.0 or later in order to use this functionality.');
        // unsupported API was used, consider this a fatal error for the current connection
        this._onProtocolError(error.message);
        observer.onError(error);
        throw error;
    };
    /**
     * Perform protocol related operations for closing this connection
     */
    BoltProtocol.prototype.prepareToClose = function () {
        // no need to notify the database in this protocol version
    };
    /**
     * Begin an explicit transaction.
     * @param {Object} param
     * @param {Bookmarks} param.bookmarks the bookmarks.
     * @param {TxConfig} param.txConfig the configuration.
     * @param {string} param.database the target database name.
     * @param {string} param.mode the access mode.
     * @param {string} param.impersonatedUser the impersonated user
     * @param {NotificationFilter} param.notificationFilter the notification filter.
     * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error.
     * @param {function(err: Error)} param.afterError the callback to invoke after handling the error.
     * @param {function()} param.beforeComplete the callback to invoke before handling the completion.
     * @param {function()} param.afterComplete the callback to invoke after handling the completion.
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.beginTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        return this.run('BEGIN', bookmarks ? bookmarks.asBeginTransactionParameters() : {}, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            database: database,
            mode: mode,
            impersonatedUser: impersonatedUser,
            notificationFilter: notificationFilter,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            flush: false
        });
    };
    /**
     * Commit the explicit transaction.
     * @param {Object} param
     * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error.
     * @param {function(err: Error)} param.afterError the callback to invoke after handling the error.
     * @param {function()} param.beforeComplete the callback to invoke before handling the completion.
     * @param {function()} param.afterComplete the callback to invoke after handling the completion.
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.commitTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        // WRITE access mode is used as a place holder here, it has
        // no effect on behaviour for Bolt V1 & V2
        return this.run('COMMIT', {}, {
            bookmarks: Bookmarks$3.empty(),
            txConfig: TxConfig$2.empty(),
            mode: ACCESS_MODE_WRITE,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
    };
    /**
     * Rollback the explicit transaction.
     * @param {Object} param
     * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error.
     * @param {function(err: Error)} param.afterError the callback to invoke after handling the error.
     * @param {function()} param.beforeComplete the callback to invoke before handling the completion.
     * @param {function()} param.afterComplete the callback to invoke after handling the completion.
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.rollbackTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        // WRITE access mode is used as a place holder here, it has
        // no effect on behaviour for Bolt V1 & V2
        return this.run('ROLLBACK', {}, {
            bookmarks: Bookmarks$3.empty(),
            txConfig: TxConfig$2.empty(),
            mode: ACCESS_MODE_WRITE,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
    };
    /**
     * Send a Cypher query through the underlying connection.
     * @param {string} query the cypher query.
     * @param {Object} parameters the query parameters.
     * @param {Object} param
     * @param {Bookmarks} param.bookmarks the bookmarks.
     * @param {TxConfig} param.txConfig the transaction configuration.
     * @param {string} param.database the target database name.
     * @param {string} param.impersonatedUser the impersonated user
     * @param {NotificationFilter} param.notificationFilter the notification filter.
     * @param {string} param.mode the access mode.
     * @param {function(keys: string[])} param.beforeKeys the callback to invoke before handling the keys.
     * @param {function(keys: string[])} param.afterKeys the callback to invoke after handling the keys.
     * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error.
     * @param {function(err: Error)} param.afterError the callback to invoke after handling the error.
     * @param {function()} param.beforeComplete the callback to invoke before handling the completion.
     * @param {function()} param.afterComplete the callback to invoke after handling the completion.
     * @param {boolean} param.flush whether to flush the buffered messages.
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a; _b.bookmarks; var txConfig = _b.txConfig, database = _b.database; _b.mode; var impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.highRecordWatermark, highRecordWatermark = _d === void 0 ? Number.MAX_VALUE : _d, _e = _b.lowRecordWatermark, lowRecordWatermark = _e === void 0 ? Number.MAX_VALUE : _e;
        var observer = new stream_observers_1$c.ResultStreamObserver({
            server: this._server,
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark
        });
        // bookmarks and mode are ignored in this version of the protocol
        (0, bolt_protocol_util_1$7.assertTxConfigIsEmpty)(txConfig, this._onProtocolError, observer);
        // passing in a database name on this protocol version throws an error
        (0, bolt_protocol_util_1$7.assertDatabaseIsEmpty)(database, this._onProtocolError, observer);
        // passing impersonated user on this protocol version throws an error
        (0, bolt_protocol_util_1$7.assertImpersonatedUserIsEmpty)(impersonatedUser, this._onProtocolError, observer);
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$7.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$c.default.run(query, parameters), observer, false);
        this.write(request_message_1$c.default.pullAll(), observer, flush);
        return observer;
    };
    Object.defineProperty(BoltProtocol.prototype, "currentFailure", {
        get: function () {
            return this._responseHandler.currentFailure;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Send a RESET through the underlying connection.
     * @param {Object} param
     * @param {function(err: Error)} param.onError the callback to invoke on error.
     * @param {function()} param.onComplete the callback to invoke on completion.
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.reset = function (_a) {
        var _b = _a === void 0 ? {} : _a, onError = _b.onError, onComplete = _b.onComplete;
        var observer = new stream_observers_1$c.ResetObserver({
            onProtocolError: this._onProtocolError,
            onError: onError,
            onComplete: onComplete
        });
        this.write(request_message_1$c.default.reset(), observer, true);
        return observer;
    };
    /**
     * Send a TELEMETRY through the underlying connection.
     *
     * @param {object} param0 Message params
     * @param {number} param0.api The API called
     * @param {object} param1 Configuration and callbacks
     * @param {function()} param1.onCompleted Called when completed
     * @param {function()} param1.onError Called when error
     * @return {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.telemetry = function (_a, _b) {
        _a.api;
        var _c = _b === void 0 ? {} : _b; _c.onError; var onCompleted = _c.onCompleted;
        var observer = new stream_observers_1$c.CompletedObserver();
        if (onCompleted) {
            onCompleted();
        }
        return observer;
    };
    BoltProtocol.prototype._createPacker = function (chunker) {
        return new packstream_1$4.v1.Packer(chunker);
    };
    BoltProtocol.prototype._createUnpacker = function (disableLosslessIntegers, useBigInt) {
        return new packstream_1$4.v1.Unpacker(disableLosslessIntegers, useBigInt);
    };
    /**
     * Write a message to the network channel.
     * @param {RequestMessage} message the message to write.
     * @param {StreamObserver} observer the response observer.
     * @param {boolean} flush `true` if flush should happen after the message is written to the buffer.
     */
    BoltProtocol.prototype.write = function (message, observer, flush) {
        var queued = this.queueObserverIfProtocolIsNotBroken(observer);
        if (queued) {
            if (this._log.isDebugEnabled()) {
                this._log.debug("C: ".concat(message));
            }
            this._lastMessageSignature = message.signature;
            var messageStruct = new packstream_1$4.structure.Structure(message.signature, message.fields);
            this.packable(messageStruct)();
            this._chunker.messageBoundary();
            if (flush) {
                this._chunker.flush();
            }
        }
    };
    BoltProtocol.prototype.isLastMessageLogon = function () {
        return this._lastMessageSignature === request_message_1$c.SIGNATURES.HELLO ||
            this._lastMessageSignature === request_message_1$c.SIGNATURES.LOGON;
    };
    BoltProtocol.prototype.isLastMessageReset = function () {
        return this._lastMessageSignature === request_message_1$c.SIGNATURES.RESET;
    };
    /**
     * Notifies faltal erros to the observers and mark the protocol in the fatal error state.
     * @param {Error} error The error
     */
    BoltProtocol.prototype.notifyFatalError = function (error) {
        this._fatalError = error;
        return this._responseHandler._notifyErrorToObservers(error);
    };
    /**
     * Updates the the current observer with the next one on the queue.
     */
    BoltProtocol.prototype.updateCurrentObserver = function () {
        return this._responseHandler._updateCurrentObserver();
    };
    /**
     * Checks if exist an ongoing observable requests
     * @return {boolean}
     */
    BoltProtocol.prototype.hasOngoingObservableRequests = function () {
        return this._responseHandler.hasOngoingObservableRequests();
    };
    /**
     * Enqueue the observer if the protocol is not broken.
     * In case it's broken, the observer will be notified about the error.
     *
     * @param {StreamObserver} observer The observer
     * @returns {boolean} if it was queued
     */
    BoltProtocol.prototype.queueObserverIfProtocolIsNotBroken = function (observer) {
        if (this.isBroken()) {
            this.notifyFatalErrorToObserver(observer);
            return false;
        }
        return this._responseHandler._queueObserver(observer);
    };
    /**
     * Veritfy the protocol is not broken.
     * @returns {boolean}
     */
    BoltProtocol.prototype.isBroken = function () {
        return !!this._fatalError;
    };
    /**
     * Notifies the current fatal error to the observer
     *
     * @param {StreamObserver} observer The observer
     */
    BoltProtocol.prototype.notifyFatalErrorToObserver = function (observer) {
        if (observer && observer.onError) {
            observer.onError(this._fatalError);
        }
    };
    /**
     * Reset current failure on the observable response handler to null.
     */
    BoltProtocol.prototype.resetFailure = function () {
        this._responseHandler._resetFailure();
    };
    BoltProtocol.prototype._onLoginCompleted = function (metadata, authToken, onCompleted) {
        this._initialized = true;
        this._authToken = authToken;
        if (metadata) {
            var serverVersion = metadata.server;
            if (!this._server.version) {
                this._server.version = serverVersion;
            }
        }
        if (onCompleted) {
            onCompleted(metadata);
        }
    };
    BoltProtocol.prototype._onLoginError = function (error, onError) {
        this._onProtocolError(error.message);
        if (onError) {
            onError(error);
        }
    };
    return BoltProtocol;
}());
boltProtocolV1.default = BoltProtocol$g;

var boltProtocolV2 = {};

var boltProtocolV2_transformer = {};

var temporalFactory = {};

Object.defineProperty(temporalFactory, "__esModule", { value: true });
temporalFactory.epochDayToDate = epochDayToDate;
temporalFactory.nanoOfDayToLocalTime = nanoOfDayToLocalTime;
temporalFactory.epochSecondAndNanoToLocalDateTime = epochSecondAndNanoToLocalDateTime;
/**
 * 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 neo4j_driver_core_1$u = lib$1;
var _a$a = neo4j_driver_core_1$u.internal.temporalUtil, DAYS_0000_TO_1970 = _a$a.DAYS_0000_TO_1970, DAYS_PER_400_YEAR_CYCLE = _a$a.DAYS_PER_400_YEAR_CYCLE, NANOS_PER_HOUR = _a$a.NANOS_PER_HOUR, NANOS_PER_MINUTE = _a$a.NANOS_PER_MINUTE, NANOS_PER_SECOND = _a$a.NANOS_PER_SECOND, SECONDS_PER_DAY = _a$a.SECONDS_PER_DAY, floorDiv = _a$a.floorDiv, floorMod = _a$a.floorMod;
/**
 * 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, neo4j_driver_core_1$u.int)(epochDay);
    var zeroDay = epochDay.add(DAYS_0000_TO_1970).subtract(60);
    var adjust = (0, neo4j_driver_core_1$u.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 neo4j_driver_core_1$u.Date(year, month, day);
}
/**
 * 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, neo4j_driver_core_1$u.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 neo4j_driver_core_1$u.LocalTime(hour, minute, second, nanosecond);
}
/**
 * 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 neo4j_driver_core_1$u.LocalDateTime(localDate.year, localDate.month, localDate.day, localTime.hour, localTime.minute, localTime.second, localTime.nanosecond);
}

/**
 * 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 __assign$q = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$q = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$q.apply(this, arguments);
};
var __read$5 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __importDefault$E = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV2_transformer, "__esModule", { value: true });
var neo4j_driver_core_1$t = lib$1;
var packstream_1$3 = packstream;
var transformer_1$g = transformer;
var temporal_factory_1$1 = temporalFactory;
var bolt_protocol_v1_transformer_1 = __importDefault$E(boltProtocolV1_transformer);
var _a$9 = neo4j_driver_core_1$t.internal.temporalUtil, dateToEpochDay = _a$9.dateToEpochDay, localDateTimeToEpochSecond$1 = _a$9.localDateTimeToEpochSecond, localTimeToNanoOfDay = _a$9.localTimeToNanoOfDay;
var POINT_2D = 0x58;
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$1 = 0x46;
var DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE$1 = 3;
var DATE_TIME_WITH_ZONE_ID$1 = 0x66;
var DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE$1 = 3;
/**
 * Creates the Point2D Transformer
 * @returns {TypeTransformer}
 */
function createPoint2DTransformer() {
    return new transformer_1$g.TypeTransformer({
        signature: POINT_2D,
        isTypeInstance: function (point) { return (0, neo4j_driver_core_1$t.isPoint)(point) && (point.z === null || point.z === undefined); },
        toStructure: function (point) { return new packstream_1$3.structure.Structure(POINT_2D, [
            (0, neo4j_driver_core_1$t.int)(point.srid),
            point.x,
            point.y
        ]); },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('Point2D', POINT_2D_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 3), srid = _a[0], x = _a[1], y = _a[2];
            return new neo4j_driver_core_1$t.Point(srid, x, y, undefined // z
            );
        }
    });
}
/**
 * Creates the Point3D Transformer
 * @returns {TypeTransformer}
 */
function createPoint3DTransformer() {
    return new transformer_1$g.TypeTransformer({
        signature: POINT_3D,
        isTypeInstance: function (point) { return (0, neo4j_driver_core_1$t.isPoint)(point) && point.z !== null && point.z !== undefined; },
        toStructure: function (point) { return new packstream_1$3.structure.Structure(POINT_3D, [
            (0, neo4j_driver_core_1$t.int)(point.srid),
            point.x,
            point.y,
            point.z
        ]); },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('Point3D', POINT_3D_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 4), srid = _a[0], x = _a[1], y = _a[2], z = _a[3];
            return new neo4j_driver_core_1$t.Point(srid, x, y, z);
        }
    });
}
/**
 * Creates the Duration Transformer
 * @returns {TypeTransformer}
 */
function createDurationTransformer() {
    return new transformer_1$g.TypeTransformer({
        signature: DURATION,
        isTypeInstance: neo4j_driver_core_1$t.isDuration,
        toStructure: function (value) {
            var months = (0, neo4j_driver_core_1$t.int)(value.months);
            var days = (0, neo4j_driver_core_1$t.int)(value.days);
            var seconds = (0, neo4j_driver_core_1$t.int)(value.seconds);
            var nanoseconds = (0, neo4j_driver_core_1$t.int)(value.nanoseconds);
            return new packstream_1$3.structure.Structure(DURATION, [months, days, seconds, nanoseconds]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('Duration', DURATION_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 4), months = _a[0], days = _a[1], seconds = _a[2], nanoseconds = _a[3];
            return new neo4j_driver_core_1$t.Duration(months, days, seconds, nanoseconds);
        }
    });
}
/**
 * Creates the LocalTime Transformer
 * @param {Object} param
 * @param {boolean} param.disableLosslessIntegers Disables lossless integers
 * @param {boolean} param.useBigInt Uses BigInt instead of number or Integer
 * @returns {TypeTransformer}
 */
function createLocalTimeTransformer(_a) {
    var disableLosslessIntegers = _a.disableLosslessIntegers, useBigInt = _a.useBigInt;
    return new transformer_1$g.TypeTransformer({
        signature: LOCAL_TIME,
        isTypeInstance: neo4j_driver_core_1$t.isLocalTime,
        toStructure: function (value) {
            var nanoOfDay = localTimeToNanoOfDay(value.hour, value.minute, value.second, value.nanosecond);
            return new packstream_1$3.structure.Structure(LOCAL_TIME, [nanoOfDay]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('LocalTime', LOCAL_TIME_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 1), nanoOfDay = _a[0];
            var result = (0, temporal_factory_1$1.nanoOfDayToLocalTime)(nanoOfDay);
            return convertIntegerPropsIfNeeded$1(result, disableLosslessIntegers, useBigInt);
        }
    });
}
/**
 * Creates the Time Transformer
 * @param {Object} param
 * @param {boolean} param.disableLosslessIntegers Disables lossless integers
 * @param {boolean} param.useBigInt Uses BigInt instead of number or Integer
 * @returns {TypeTransformer}
 */
function createTimeTransformer(_a) {
    var disableLosslessIntegers = _a.disableLosslessIntegers, useBigInt = _a.useBigInt;
    return new transformer_1$g.TypeTransformer({
        signature: TIME,
        isTypeInstance: neo4j_driver_core_1$t.isTime,
        toStructure: function (value) {
            var nanoOfDay = localTimeToNanoOfDay(value.hour, value.minute, value.second, value.nanosecond);
            var offsetSeconds = (0, neo4j_driver_core_1$t.int)(value.timeZoneOffsetSeconds);
            return new packstream_1$3.structure.Structure(TIME, [nanoOfDay, offsetSeconds]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('Time', TIME_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 2), nanoOfDay = _a[0], offsetSeconds = _a[1];
            var localTime = (0, temporal_factory_1$1.nanoOfDayToLocalTime)(nanoOfDay);
            var result = new neo4j_driver_core_1$t.Time(localTime.hour, localTime.minute, localTime.second, localTime.nanosecond, offsetSeconds);
            return convertIntegerPropsIfNeeded$1(result, disableLosslessIntegers, useBigInt);
        }
    });
}
/**
 * Creates the Date Transformer
 * @param {Object} param
 * @param {boolean} param.disableLosslessIntegers Disables lossless integers
 * @param {boolean} param.useBigInt Uses BigInt instead of number or Integer
 * @returns {TypeTransformer}
 */
function createDateTransformer(_a) {
    var disableLosslessIntegers = _a.disableLosslessIntegers, useBigInt = _a.useBigInt;
    return new transformer_1$g.TypeTransformer({
        signature: DATE,
        isTypeInstance: neo4j_driver_core_1$t.isDate,
        toStructure: function (value) {
            var epochDay = dateToEpochDay(value.year, value.month, value.day);
            return new packstream_1$3.structure.Structure(DATE, [epochDay]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('Date', DATE_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 1), epochDay = _a[0];
            var result = (0, temporal_factory_1$1.epochDayToDate)(epochDay);
            return convertIntegerPropsIfNeeded$1(result, disableLosslessIntegers, useBigInt);
        }
    });
}
/**
 * Creates the LocalDateTime Transformer
 * @param {Object} param
 * @param {boolean} param.disableLosslessIntegers Disables lossless integers
 * @param {boolean} param.useBigInt Uses BigInt instead of number or Integer
 * @returns {TypeTransformer}
 */
function createLocalDateTimeTransformer(_a) {
    var disableLosslessIntegers = _a.disableLosslessIntegers, useBigInt = _a.useBigInt;
    return new transformer_1$g.TypeTransformer({
        signature: LOCAL_DATE_TIME,
        isTypeInstance: neo4j_driver_core_1$t.isLocalDateTime,
        toStructure: function (value) {
            var epochSecond = localDateTimeToEpochSecond$1(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
            var nano = (0, neo4j_driver_core_1$t.int)(value.nanosecond);
            return new packstream_1$3.structure.Structure(LOCAL_DATE_TIME, [epochSecond, nano]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('LocalDateTime', LOCAL_DATE_TIME_STRUCT_SIZE, struct.size);
            var _a = __read$5(struct.fields, 2), epochSecond = _a[0], nano = _a[1];
            var result = (0, temporal_factory_1$1.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
            return convertIntegerPropsIfNeeded$1(result, disableLosslessIntegers, useBigInt);
        }
    });
}
/**
 * Creates the DateTime with ZoneId Transformer
 * @param {Object} param
 * @param {boolean} param.disableLosslessIntegers Disables lossless integers
 * @param {boolean} param.useBigInt Uses BigInt instead of number or Integer
 * @returns {TypeTransformer}
 */
function createDateTimeWithZoneIdTransformer$1(_a) {
    var disableLosslessIntegers = _a.disableLosslessIntegers, useBigInt = _a.useBigInt;
    return new transformer_1$g.TypeTransformer({
        signature: DATE_TIME_WITH_ZONE_ID$1,
        isTypeInstance: function (object) { return (0, neo4j_driver_core_1$t.isDateTime)(object) && object.timeZoneId != null; },
        toStructure: function (value) {
            var epochSecond = localDateTimeToEpochSecond$1(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
            var nano = (0, neo4j_driver_core_1$t.int)(value.nanosecond);
            var timeZoneId = value.timeZoneId;
            return new packstream_1$3.structure.Structure(DATE_TIME_WITH_ZONE_ID$1, [epochSecond, nano, timeZoneId]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('DateTimeWithZoneId', DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE$1, struct.size);
            var _a = __read$5(struct.fields, 3), epochSecond = _a[0], nano = _a[1], timeZoneId = _a[2];
            var localDateTime = (0, temporal_factory_1$1.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
            var result = new neo4j_driver_core_1$t.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, null, timeZoneId);
            return convertIntegerPropsIfNeeded$1(result, disableLosslessIntegers, useBigInt);
        }
    });
}
/**
 * Creates the DateTime with Offset Transformer
 * @param {Object} param
 * @param {boolean} param.disableLosslessIntegers Disables lossless integers
 * @param {boolean} param.useBigInt Uses BigInt instead of number or Integer
 * @returns {TypeTransformer}
 */
function createDateTimeWithOffsetTransformer$1(_a) {
    var disableLosslessIntegers = _a.disableLosslessIntegers, useBigInt = _a.useBigInt;
    return new transformer_1$g.TypeTransformer({
        signature: DATE_TIME_WITH_ZONE_OFFSET$1,
        isTypeInstance: function (object) { return (0, neo4j_driver_core_1$t.isDateTime)(object) && object.timeZoneId == null; },
        toStructure: function (value) {
            var epochSecond = localDateTimeToEpochSecond$1(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
            var nano = (0, neo4j_driver_core_1$t.int)(value.nanosecond);
            var timeZoneOffsetSeconds = (0, neo4j_driver_core_1$t.int)(value.timeZoneOffsetSeconds);
            return new packstream_1$3.structure.Structure(DATE_TIME_WITH_ZONE_OFFSET$1, [epochSecond, nano, timeZoneOffsetSeconds]);
        },
        fromStructure: function (struct) {
            packstream_1$3.structure.verifyStructSize('DateTimeWithZoneOffset', DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE$1, struct.size);
            var _a = __read$5(struct.fields, 3), epochSecond = _a[0], nano = _a[1], timeZoneOffsetSeconds = _a[2];
            var localDateTime = (0, temporal_factory_1$1.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
            var result = new neo4j_driver_core_1$t.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, timeZoneOffsetSeconds, null);
            return convertIntegerPropsIfNeeded$1(result, disableLosslessIntegers, useBigInt);
        }
    });
}
function convertIntegerPropsIfNeeded$1(obj, disableLosslessIntegers, useBigInt) {
    if (!disableLosslessIntegers && !useBigInt) {
        return obj;
    }
    var convert = function (value) {
        return useBigInt ? value.toBigInt() : value.toNumberOrInfinity();
    };
    var clone = Object.create(Object.getPrototypeOf(obj));
    for (var prop in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, prop) === true) {
            var value = obj[prop];
            clone[prop] = (0, neo4j_driver_core_1$t.isInt)(value) ? convert(value) : value;
        }
    }
    Object.freeze(clone);
    return clone;
}
boltProtocolV2_transformer.default = __assign$q(__assign$q({}, bolt_protocol_v1_transformer_1.default), { createPoint2DTransformer: createPoint2DTransformer, createPoint3DTransformer: createPoint3DTransformer, createDurationTransformer: createDurationTransformer, createLocalTimeTransformer: createLocalTimeTransformer, createTimeTransformer: createTimeTransformer, createDateTransformer: createDateTransformer, createLocalDateTimeTransformer: createLocalDateTimeTransformer, createDateTimeWithZoneIdTransformer: createDateTimeWithZoneIdTransformer$1, createDateTimeWithOffsetTransformer: createDateTimeWithOffsetTransformer$1 });

var __extends$m = (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 __importDefault$D = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV2, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v1_1$1 = __importDefault$D(boltProtocolV1);
var packstream_1$2 = __importDefault$D(packstream);
var neo4j_driver_core_1$s = lib$1;
var bolt_protocol_v2_transformer_1$1 = __importDefault$D(boltProtocolV2_transformer);
var transformer_1$f = __importDefault$D(transformer);
var BOLT_PROTOCOL_V2 = neo4j_driver_core_1$s.internal.constants.BOLT_PROTOCOL_V2;
var BoltProtocol$f = /** @class */ (function (_super) {
    __extends$m(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BoltProtocol.prototype._createPacker = function (chunker) {
        return new packstream_1$2.default.Packer(chunker);
    };
    BoltProtocol.prototype._createUnpacker = function (disableLosslessIntegers, useBigInt) {
        return new packstream_1$2.default.Unpacker(disableLosslessIntegers, useBigInt);
    };
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$f.default(Object.values(bolt_protocol_v2_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V2;
        },
        enumerable: false,
        configurable: true
    });
    return BoltProtocol;
}(bolt_protocol_v1_1$1.default));
boltProtocolV2.default = BoltProtocol$f;

var boltProtocolV3 = {};

var boltProtocolV3_transformer = {};

/**
 * 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 __assign$p = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$p = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$p.apply(this, arguments);
};
var __importDefault$C = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV3_transformer, "__esModule", { value: true });
var bolt_protocol_v2_transformer_1 = __importDefault$C(boltProtocolV2_transformer);
boltProtocolV3_transformer.default = __assign$p({}, bolt_protocol_v2_transformer_1.default);

var __extends$l = (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 __assign$o = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$o = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$o.apply(this, arguments);
};
var __importDefault$B = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV3, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v2_1$1 = __importDefault$B(boltProtocolV2);
var request_message_1$b = __importDefault$B(requestMessage);
var bolt_protocol_util_1$6 = boltProtocolUtil;
var stream_observers_1$b = streamObservers;
var bolt_protocol_v3_transformer_1$1 = __importDefault$B(boltProtocolV3_transformer);
var transformer_1$e = __importDefault$B(transformer);
var neo4j_driver_core_1$r = lib$1;
neo4j_driver_core_1$r.internal.bookmarks.Bookmarks; var BOLT_PROTOCOL_V3$2 = neo4j_driver_core_1$r.internal.constants.BOLT_PROTOCOL_V3, TxConfig$1 = neo4j_driver_core_1$r.internal.txConfig.TxConfig;
var CONTEXT$1 = 'context';
var CALL_GET_ROUTING_TABLE = "CALL dbms.cluster.routing.getRoutingTable($".concat(CONTEXT$1, ")");
var noOpObserver = new stream_observers_1$b.StreamObserver();
var BoltProtocol$e = /** @class */ (function (_super) {
    __extends$l(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V3$2;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$e.default(Object.values(bolt_protocol_v3_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    BoltProtocol.prototype.transformMetadata = function (metadata) {
        if ('t_first' in metadata) {
            // Bolt V3 uses shorter key 't_first' to represent 'result_available_after'
            // adjust the key to be the same as in Bolt V1 so that ResultSummary can retrieve the value
            metadata.result_available_after = metadata.t_first;
            delete metadata.t_first;
        }
        if ('t_last' in metadata) {
            // Bolt V3 uses shorter key 't_last' to represent 'result_consumed_after'
            // adjust the key to be the same as in Bolt V1 so that ResultSummary can retrieve the value
            metadata.result_consumed_after = metadata.t_last;
            delete metadata.t_last;
        }
        return metadata;
    };
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var observer = new stream_observers_1$b.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) { return _this._onLoginCompleted(metadata, authToken, onComplete); }
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$b.default.hello(userAgent, authToken), observer, true);
        return observer;
    };
    BoltProtocol.prototype.prepareToClose = function () {
        this.write(request_message_1$b.default.goodbye(), noOpObserver, true);
    };
    BoltProtocol.prototype.beginTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, mode = _b.mode, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$b.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        // passing in a database name on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertDatabaseIsEmpty)(database, this._onProtocolError, observer);
        // passing impersonated user on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertImpersonatedUserIsEmpty)(impersonatedUser, this._onProtocolError, observer);
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$b.default.begin({ bookmarks: bookmarks, txConfig: txConfig, mode: mode }), observer, true);
        return observer;
    };
    BoltProtocol.prototype.commitTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$b.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        this.write(request_message_1$b.default.commit(), observer, true);
        return observer;
    };
    BoltProtocol.prototype.rollbackTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$b.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        this.write(request_message_1$b.default.rollback(), observer, true);
        return observer;
    };
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, mode = _b.mode, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.highRecordWatermark, highRecordWatermark = _d === void 0 ? Number.MAX_VALUE : _d, _e = _b.lowRecordWatermark, lowRecordWatermark = _e === void 0 ? Number.MAX_VALUE : _e;
        var observer = new stream_observers_1$b.ResultStreamObserver({
            server: this._server,
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark
        });
        // passing in a database name on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertDatabaseIsEmpty)(database, this._onProtocolError, observer);
        // passing impersonated user on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertImpersonatedUserIsEmpty)(impersonatedUser, this._onProtocolError, observer);
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$6.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$b.default.runWithMetadata(query, parameters, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            mode: mode
        }), observer, false);
        this.write(request_message_1$b.default.pullAll(), observer, flush);
        return observer;
    };
    /**
     * Request routing information
     *
     * @param {Object} param -
     * @param {object} param.routingContext The routing context used to define the routing table.
     *  Multi-datacenter deployments is one of its use cases
     * @param {string} param.databaseName The database name
     * @param {Bookmarks} params.sessionContext.bookmarks The bookmarks used for requesting the routing table
     * @param {string} params.sessionContext.mode The session mode
     * @param {string} params.sessionContext.database The database name used on the session
     * @param {function()} params.sessionContext.afterComplete The session param used after the session closed
     * @param {function(err: Error)} param.onError
     * @param {function(RawRoutingTable)} param.onCompleted
     * @returns {RouteObserver} the route observer
     */
    BoltProtocol.prototype.requestRoutingInformation = function (_a) {
        var _b;
        var _c = _a.routingContext, routingContext = _c === void 0 ? {} : _c, _d = _a.sessionContext, sessionContext = _d === void 0 ? {} : _d, onError = _a.onError, onCompleted = _a.onCompleted;
        var resultObserver = this.run(CALL_GET_ROUTING_TABLE, (_b = {}, _b[CONTEXT$1] = routingContext, _b), __assign$o(__assign$o({}, sessionContext), { txConfig: TxConfig$1.empty() }));
        return new stream_observers_1$b.ProcedureRouteObserver({
            resultObserver: resultObserver,
            onProtocolError: this._onProtocolError,
            onError: onError,
            onCompleted: onCompleted
        });
    };
    return BoltProtocol;
}(bolt_protocol_v2_1$1.default));
boltProtocolV3.default = BoltProtocol$e;

var boltProtocolV4x0 = {};

var boltProtocolV4x0_transformer = {};

/**
 * 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 __assign$n = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$n = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$n.apply(this, arguments);
};
var __importDefault$A = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x0_transformer, "__esModule", { value: true });
var bolt_protocol_v3_transformer_1 = __importDefault$A(boltProtocolV3_transformer);
boltProtocolV4x0_transformer.default = __assign$n({}, bolt_protocol_v3_transformer_1.default);

var __extends$k = (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 __assign$m = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$m = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$m.apply(this, arguments);
};
var __importDefault$z = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x0, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v3_1$1 = __importDefault$z(boltProtocolV3);
var request_message_1$a = __importDefault$z(requestMessage);
var bolt_protocol_util_1$5 = boltProtocolUtil;
var stream_observers_1$a = streamObservers;
var bolt_protocol_v4x0_transformer_1$1 = __importDefault$z(boltProtocolV4x0_transformer);
var transformer_1$d = __importDefault$z(transformer);
var neo4j_driver_core_1$q = lib$1;
neo4j_driver_core_1$q.internal.bookmarks.Bookmarks; var _a$8 = neo4j_driver_core_1$q.internal.constants, BOLT_PROTOCOL_V4_0$2 = _a$8.BOLT_PROTOCOL_V4_0, FETCH_ALL$4 = _a$8.FETCH_ALL, TxConfig = neo4j_driver_core_1$q.internal.txConfig.TxConfig;
var CONTEXT = 'context';
var DATABASE = 'database';
var CALL_GET_ROUTING_TABLE_MULTI_DB = "CALL dbms.routing.getRoutingTable($".concat(CONTEXT, ", $").concat(DATABASE, ")");
var BoltProtocol$d = /** @class */ (function (_super) {
    __extends$k(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V4_0$2;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$d.default(Object.values(bolt_protocol_v4x0_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    BoltProtocol.prototype.beginTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, mode = _b.mode, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$a.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        // passing impersonated user on this protocol version throws an error
        (0, bolt_protocol_util_1$5.assertImpersonatedUserIsEmpty)(impersonatedUser, this._onProtocolError, observer);
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$5.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$a.default.begin({ bookmarks: bookmarks, txConfig: txConfig, database: database, mode: mode }), observer, true);
        return observer;
    };
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, mode = _b.mode, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.reactive, reactive = _d === void 0 ? false : _d, _e = _b.fetchSize, fetchSize = _e === void 0 ? FETCH_ALL$4 : _e, _f = _b.highRecordWatermark, highRecordWatermark = _f === void 0 ? Number.MAX_VALUE : _f, _g = _b.lowRecordWatermark, lowRecordWatermark = _g === void 0 ? Number.MAX_VALUE : _g;
        var observer = new stream_observers_1$a.ResultStreamObserver({
            server: this._server,
            reactive: reactive,
            fetchSize: fetchSize,
            moreFunction: this._requestMore.bind(this),
            discardFunction: this._requestDiscard.bind(this),
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark
        });
        // passing impersonated user on this protocol version throws an error
        (0, bolt_protocol_util_1$5.assertImpersonatedUserIsEmpty)(impersonatedUser, this._onProtocolError, observer);
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$5.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        var flushRun = reactive;
        this.write(request_message_1$a.default.runWithMetadata(query, parameters, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            database: database,
            mode: mode
        }), observer, flushRun && flush);
        if (!reactive) {
            this.write(request_message_1$a.default.pull({ n: fetchSize }), observer, flush);
        }
        return observer;
    };
    BoltProtocol.prototype._requestMore = function (stmtId, n, observer) {
        this.write(request_message_1$a.default.pull({ stmtId: stmtId, n: n }), observer, true);
    };
    BoltProtocol.prototype._requestDiscard = function (stmtId, observer) {
        this.write(request_message_1$a.default.discard({ stmtId: stmtId }), observer, true);
    };
    BoltProtocol.prototype._noOp = function () { };
    /**
     * Request routing information
     *
     * @param {Object} param -
     * @param {object} param.routingContext The routing context used to define the routing table.
     *  Multi-datacenter deployments is one of its use cases
     * @param {string} param.databaseName The database name
     * @param {Bookmarks} params.sessionContext.bookmarks The bookmarks used for requesting the routing table
     * @param {string} params.sessionContext.mode The session mode
     * @param {string} params.sessionContext.database The database name used on the session
     * @param {function()} params.sessionContext.afterComplete The session param used after the session closed
     * @param {function(err: Error)} param.onError
     * @param {function(RawRoutingTable)} param.onCompleted
     * @returns {RouteObserver} the route observer
     */
    BoltProtocol.prototype.requestRoutingInformation = function (_a) {
        var _b;
        var _c = _a.routingContext, routingContext = _c === void 0 ? {} : _c, _d = _a.databaseName, databaseName = _d === void 0 ? null : _d, _e = _a.sessionContext, sessionContext = _e === void 0 ? {} : _e, onError = _a.onError, onCompleted = _a.onCompleted;
        var resultObserver = this.run(CALL_GET_ROUTING_TABLE_MULTI_DB, (_b = {},
            _b[CONTEXT] = routingContext,
            _b[DATABASE] = databaseName,
            _b), __assign$m(__assign$m({}, sessionContext), { txConfig: TxConfig.empty() }));
        return new stream_observers_1$a.ProcedureRouteObserver({
            resultObserver: resultObserver,
            onProtocolError: this._onProtocolError,
            onError: onError,
            onCompleted: onCompleted
        });
    };
    return BoltProtocol;
}(bolt_protocol_v3_1$1.default));
boltProtocolV4x0.default = BoltProtocol$d;

var boltProtocolV4x1 = {};

var boltProtocolV4x1_transformer = {};

/**
 * 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 __assign$l = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$l = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$l.apply(this, arguments);
};
var __importDefault$y = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x1_transformer, "__esModule", { value: true });
var bolt_protocol_v4x0_transformer_1 = __importDefault$y(boltProtocolV4x0_transformer);
boltProtocolV4x1_transformer.default = __assign$l({}, bolt_protocol_v4x0_transformer_1.default);

var __extends$j = (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 __importDefault$x = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x1, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v4x0_1$1 = __importDefault$x(boltProtocolV4x0);
var request_message_1$9 = __importDefault$x(requestMessage);
var stream_observers_1$9 = streamObservers;
var neo4j_driver_core_1$p = lib$1;
var bolt_protocol_util_1$4 = boltProtocolUtil;
var bolt_protocol_v4x1_transformer_1$1 = __importDefault$x(boltProtocolV4x1_transformer);
var transformer_1$c = __importDefault$x(transformer);
var BOLT_PROTOCOL_V4_1 = neo4j_driver_core_1$p.internal.constants.BOLT_PROTOCOL_V4_1;
var BoltProtocol$c = /** @class */ (function (_super) {
    __extends$j(BoltProtocol, _super);
    /**
     * @constructor
     * @param {Object} server the server informatio.
     * @param {Chunker} chunker the chunker.
     * @param {Object} packstreamConfig Packstream configuration
     * @param {boolean} packstreamConfig.disableLosslessIntegers if this connection should convert all received integers to native JS numbers.
     * @param {boolean} packstreamConfig.useBigInt if this connection should convert all received integers to native BigInt numbers.
     * @param {CreateResponseHandler} createResponseHandler Function which creates the response handler
     * @param {Logger} log the logger
     * @param {Object} serversideRouting
     *
     */
    function BoltProtocol(server, chunker, packstreamConfig, createResponseHandler, log, onProtocolError, serversideRouting) {
        if (createResponseHandler === void 0) { createResponseHandler = function () { return null; }; }
        var _this = _super.call(this, server, chunker, packstreamConfig, createResponseHandler, log, onProtocolError) || this;
        _this._serversideRouting = serversideRouting;
        return _this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V4_1;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$c.default(Object.values(bolt_protocol_v4x1_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var observer = new stream_observers_1$9.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) { return _this._onLoginCompleted(metadata, authToken, onComplete); }
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$4.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$9.default.hello(userAgent, authToken, this._serversideRouting), observer, true);
        return observer;
    };
    return BoltProtocol;
}(bolt_protocol_v4x0_1$1.default));
boltProtocolV4x1.default = BoltProtocol$c;

var boltProtocolV4x2 = {};

var boltProtocolV4x2_transformer = {};

/**
 * 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 __assign$k = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$k = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$k.apply(this, arguments);
};
var __importDefault$w = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x2_transformer, "__esModule", { value: true });
var bolt_protocol_v4x1_transformer_1 = __importDefault$w(boltProtocolV4x1_transformer);
boltProtocolV4x2_transformer.default = __assign$k({}, bolt_protocol_v4x1_transformer_1.default);

var __extends$i = (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 __importDefault$v = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x2, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v4x1_1$1 = __importDefault$v(boltProtocolV4x1);
var neo4j_driver_core_1$o = lib$1;
var bolt_protocol_v4x2_transformer_1$1 = __importDefault$v(boltProtocolV4x2_transformer);
var transformer_1$b = __importDefault$v(transformer);
var BOLT_PROTOCOL_V4_2 = neo4j_driver_core_1$o.internal.constants.BOLT_PROTOCOL_V4_2;
var BoltProtocol$b = /** @class */ (function (_super) {
    __extends$i(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V4_2;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$b.default(Object.values(bolt_protocol_v4x2_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    return BoltProtocol;
}(bolt_protocol_v4x1_1$1.default));
boltProtocolV4x2.default = BoltProtocol$b;

var boltProtocolV4x3 = {};

var boltProtocolV4x3_transformer = {};

/**
 * 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 __assign$j = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$j = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$j.apply(this, arguments);
};
var __importDefault$u = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x3_transformer, "__esModule", { value: true });
var bolt_protocol_v4x2_transformer_1 = __importDefault$u(boltProtocolV4x2_transformer);
boltProtocolV4x3_transformer.default = __assign$j({}, bolt_protocol_v4x2_transformer_1.default);

var boltProtocolV5x0_utc_transformer = {};

var boltProtocolV4x4_transformer = {};

/**
 * 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 __assign$i = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$i = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$i.apply(this, arguments);
};
var __importDefault$t = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x4_transformer, "__esModule", { value: true });
var bolt_protocol_v4x3_transformer_1$1 = __importDefault$t(boltProtocolV4x3_transformer);
boltProtocolV4x4_transformer.default = __assign$i({}, bolt_protocol_v4x3_transformer_1$1.default);

/**
 * 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 __read$4 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __importDefault$s = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x0_utc_transformer, "__esModule", { value: true });
var packstream_1$1 = packstream;
var neo4j_driver_core_1$n = lib$1;
var bolt_protocol_v4x4_transformer_1$2 = __importDefault$s(boltProtocolV4x4_transformer);
var temporal_factory_1 = temporalFactory;
var functional_1 = functional;
var localDateTimeToEpochSecond = neo4j_driver_core_1$n.internal.temporalUtil.localDateTimeToEpochSecond;
var DATE_TIME_WITH_ZONE_OFFSET = 0x49;
var DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE = 3;
var DATE_TIME_WITH_ZONE_ID = 0x69;
var DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE = 3;
function createDateTimeWithZoneIdTransformer(config, logger) {
    var disableLosslessIntegers = config.disableLosslessIntegers, useBigInt = config.useBigInt;
    var dateTimeWithZoneIdTransformer = bolt_protocol_v4x4_transformer_1$2.default.createDateTimeWithZoneIdTransformer(config);
    return dateTimeWithZoneIdTransformer.extendsWith({
        signature: DATE_TIME_WITH_ZONE_ID,
        fromStructure: function (struct) {
            packstream_1$1.structure.verifyStructSize('DateTimeWithZoneId', DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE, struct.size);
            var _a = __read$4(struct.fields, 3), epochSecond = _a[0], nano = _a[1], timeZoneId = _a[2];
            var localDateTime = getTimeInZoneId(timeZoneId, epochSecond, nano);
            var result = new neo4j_driver_core_1$n.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, (0, neo4j_driver_core_1$n.int)(nano), localDateTime.timeZoneOffsetSeconds, timeZoneId);
            return convertIntegerPropsIfNeeded(result, disableLosslessIntegers, useBigInt);
        },
        toStructure: function (value) {
            var epochSecond = localDateTimeToEpochSecond(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
            var offset = value.timeZoneOffsetSeconds != null
                ? value.timeZoneOffsetSeconds
                : getOffsetFromZoneId(value.timeZoneId, epochSecond, value.nanosecond);
            if (value.timeZoneOffsetSeconds == null) {
                logger.warn('DateTime objects without "timeZoneOffsetSeconds" property ' +
                    'are prune to bugs related to ambiguous times. For instance, ' +
                    '2022-10-30T2:30:00[Europe/Berlin] could be GMT+1 or GMT+2.');
            }
            var utc = epochSecond.subtract(offset);
            var nano = (0, neo4j_driver_core_1$n.int)(value.nanosecond);
            var timeZoneId = value.timeZoneId;
            return new packstream_1$1.structure.Structure(DATE_TIME_WITH_ZONE_ID, [utc, nano, timeZoneId]);
        }
    });
}
/**
 * Returns the offset for a given timezone id
 *
 * Javascript doesn't have support for direct getting the timezone offset from a given
 * TimeZoneId and DateTime in the given TimeZoneId. For solving this issue,
 *
 * 1. The ZoneId is applied to the timestamp, so we could make the difference between the
 * given timestamp and the new calculated one. This is the offset for the timezone
 * in the utc is equal to epoch (some time in the future or past)
 * 2. The offset is subtracted from the timestamp, so we have an estimated utc timestamp.
 * 3. The ZoneId is applied to the new timestamp, se we could could make the difference
 * between the new timestamp and the calculated one. This is the offset for the given timezone.
 *
 * Example:
 *    Input: 2022-3-27 1:59:59 'Europe/Berlin'
 *    Apply 1, 2022-3-27 1:59:59 => 2022-3-27 3:59:59 'Europe/Berlin' +2:00
 *    Apply 2, 2022-3-27 1:59:59 - 2:00 => 2022-3-26 23:59:59
 *    Apply 3, 2022-3-26 23:59:59 => 2022-3-27 00:59:59 'Europe/Berlin' +1:00
 *  The offset is +1 hour.
 *
 * @param {string} timeZoneId The timezone id
 * @param {Integer} epochSecond The epoch second in the timezone id
 * @param {Integerable} nanosecond The nanoseconds in the timezone id
 * @returns The timezone offset
 */
function getOffsetFromZoneId(timeZoneId, epochSecond, nanosecond) {
    var dateTimeWithZoneAppliedTwice = getTimeInZoneId(timeZoneId, epochSecond, nanosecond);
    // The wallclock form the current date time
    var epochWithZoneAppliedTwice = localDateTimeToEpochSecond(dateTimeWithZoneAppliedTwice.year, dateTimeWithZoneAppliedTwice.month, dateTimeWithZoneAppliedTwice.day, dateTimeWithZoneAppliedTwice.hour, dateTimeWithZoneAppliedTwice.minute, dateTimeWithZoneAppliedTwice.second, nanosecond);
    var offsetOfZoneInTheFutureUtc = epochWithZoneAppliedTwice.subtract(epochSecond);
    var guessedUtc = epochSecond.subtract(offsetOfZoneInTheFutureUtc);
    var zonedDateTimeFromGuessedUtc = getTimeInZoneId(timeZoneId, guessedUtc, nanosecond);
    var zonedEpochFromGuessedUtc = localDateTimeToEpochSecond(zonedDateTimeFromGuessedUtc.year, zonedDateTimeFromGuessedUtc.month, zonedDateTimeFromGuessedUtc.day, zonedDateTimeFromGuessedUtc.hour, zonedDateTimeFromGuessedUtc.minute, zonedDateTimeFromGuessedUtc.second, nanosecond);
    var offset = zonedEpochFromGuessedUtc.subtract(guessedUtc);
    return offset;
}
var dateTimeFormatCache = new Map();
function getDateTimeFormatForZoneId(timeZoneId) {
    if (!dateTimeFormatCache.has(timeZoneId)) {
        var formatter = new Intl.DateTimeFormat('en-US', {
            timeZone: timeZoneId,
            year: 'numeric',
            month: 'numeric',
            day: 'numeric',
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
            hour12: false,
            era: 'narrow'
        });
        dateTimeFormatCache.set(timeZoneId, formatter);
    }
    return dateTimeFormatCache.get(timeZoneId);
}
function getTimeInZoneId(timeZoneId, epochSecond, nano) {
    var formatter = getDateTimeFormatForZoneId(timeZoneId);
    var utc = (0, neo4j_driver_core_1$n.int)(epochSecond)
        .multiply(1000)
        .add((0, neo4j_driver_core_1$n.int)(nano).div(1000000))
        .toNumber();
    var formattedUtcParts = formatter.formatToParts(utc);
    var localDateTime = formattedUtcParts.reduce(function (obj, currentValue) {
        if (currentValue.type === 'era') {
            obj.adjustEra =
                currentValue.value.toUpperCase() === 'B'
                    ? function (year) { return year.subtract(1).negate(); } // 1BC equals to year 0 in astronomical year numbering
                    : functional_1.identity;
        }
        else if (currentValue.type === 'hour') {
            obj.hour = (0, neo4j_driver_core_1$n.int)(currentValue.value).modulo(24);
        }
        else if (currentValue.type !== 'literal') {
            obj[currentValue.type] = (0, neo4j_driver_core_1$n.int)(currentValue.value);
        }
        return obj;
    }, {});
    localDateTime.year = localDateTime.adjustEra(localDateTime.year);
    var epochInTimeZone = localDateTimeToEpochSecond(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond);
    localDateTime.timeZoneOffsetSeconds = epochInTimeZone.subtract(epochSecond);
    localDateTime.hour = localDateTime.hour.modulo(24);
    return localDateTime;
}
function createDateTimeWithOffsetTransformer(config) {
    var disableLosslessIntegers = config.disableLosslessIntegers, useBigInt = config.useBigInt;
    var dateTimeWithOffsetTransformer = bolt_protocol_v4x4_transformer_1$2.default.createDateTimeWithOffsetTransformer(config);
    return dateTimeWithOffsetTransformer.extendsWith({
        signature: DATE_TIME_WITH_ZONE_OFFSET,
        toStructure: function (value) {
            var epochSecond = localDateTimeToEpochSecond(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond);
            var nano = (0, neo4j_driver_core_1$n.int)(value.nanosecond);
            var timeZoneOffsetSeconds = (0, neo4j_driver_core_1$n.int)(value.timeZoneOffsetSeconds);
            var utcSecond = epochSecond.subtract(timeZoneOffsetSeconds);
            return new packstream_1$1.structure.Structure(DATE_TIME_WITH_ZONE_OFFSET, [utcSecond, nano, timeZoneOffsetSeconds]);
        },
        fromStructure: function (struct) {
            packstream_1$1.structure.verifyStructSize('DateTimeWithZoneOffset', DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE, struct.size);
            var _a = __read$4(struct.fields, 3), utcSecond = _a[0], nano = _a[1], timeZoneOffsetSeconds = _a[2];
            var epochSecond = (0, neo4j_driver_core_1$n.int)(utcSecond).add(timeZoneOffsetSeconds);
            var localDateTime = (0, temporal_factory_1.epochSecondAndNanoToLocalDateTime)(epochSecond, nano);
            var result = new neo4j_driver_core_1$n.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, timeZoneOffsetSeconds, null);
            return convertIntegerPropsIfNeeded(result, disableLosslessIntegers, useBigInt);
        }
    });
}
function convertIntegerPropsIfNeeded(obj, disableLosslessIntegers, useBigInt) {
    if (!disableLosslessIntegers && !useBigInt) {
        return obj;
    }
    var convert = function (value) {
        return useBigInt ? value.toBigInt() : value.toNumberOrInfinity();
    };
    var clone = Object.create(Object.getPrototypeOf(obj));
    for (var prop in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, prop) === true) {
            var value = obj[prop];
            clone[prop] = (0, neo4j_driver_core_1$n.isInt)(value) ? convert(value) : value;
        }
    }
    Object.freeze(clone);
    return clone;
}
boltProtocolV5x0_utc_transformer.default = {
    createDateTimeWithZoneIdTransformer: createDateTimeWithZoneIdTransformer,
    createDateTimeWithOffsetTransformer: createDateTimeWithOffsetTransformer
};

var __extends$h = (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 __assign$h = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$h = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$h.apply(this, arguments);
};
var __importDefault$r = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x3, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v4x2_1$1 = __importDefault$r(boltProtocolV4x2);
var request_message_1$8 = __importDefault$r(requestMessage);
var stream_observers_1$8 = streamObservers;
var bolt_protocol_util_1$3 = boltProtocolUtil;
var bolt_protocol_v4x3_transformer_1 = __importDefault$r(boltProtocolV4x3_transformer);
var bolt_protocol_v5x0_utc_transformer_1$2 = __importDefault$r(boltProtocolV5x0_utc_transformer);
var transformer_1$a = __importDefault$r(transformer);
var neo4j_driver_core_1$m = lib$1;
var Bookmarks$2 = neo4j_driver_core_1$m.internal.bookmarks.Bookmarks, BOLT_PROTOCOL_V4_3 = neo4j_driver_core_1$m.internal.constants.BOLT_PROTOCOL_V4_3;
var BoltProtocol$a = /** @class */ (function (_super) {
    __extends$h(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V4_3;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$a.default(Object.values(bolt_protocol_v4x3_transformer_1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Request routing information
     *
     * @param {Object} param -
     * @param {object} param.routingContext The routing context used to define the routing table.
     *  Multi-datacenter deployments is one of its use cases
     * @param {string} param.databaseName The database name
     * @param {Bookmarks} params.sessionContext.bookmarks The bookmarks used for requesting the routing table
     * @param {function(err: Error)} param.onError
     * @param {function(RawRoutingTable)} param.onCompleted
     * @returns {RouteObserver} the route observer
     */
    BoltProtocol.prototype.requestRoutingInformation = function (_a) {
        var _b = _a.routingContext, routingContext = _b === void 0 ? {} : _b, _c = _a.databaseName, databaseName = _c === void 0 ? null : _c, _d = _a.sessionContext, sessionContext = _d === void 0 ? {} : _d, onError = _a.onError, onCompleted = _a.onCompleted;
        var observer = new stream_observers_1$8.RouteObserver({
            onProtocolError: this._onProtocolError,
            onError: onError,
            onCompleted: onCompleted
        });
        var bookmarks = sessionContext.bookmarks || Bookmarks$2.empty();
        this.write(request_message_1$8.default.route(routingContext, bookmarks.values(), databaseName), observer, true);
        return observer;
    };
    /**
     * Initialize a connection with the server
     *
     * @param {Object} args The params
     * @param {string} args.userAgent The user agent
     * @param {any} args.authToken The auth token
     * @param {NotificationFilter} args.notificationFilter The notification filter.
     * @param {function(error)} args.onError On error callback
     * @param {function(onComplte)} args.onComplete On complete callback
     * @returns {LoginObserver} The Login observer
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var observer = new stream_observers_1$8.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) {
                if (metadata.patch_bolt !== undefined) {
                    _this._applyPatches(metadata.patch_bolt);
                }
                return _this._onLoginCompleted(metadata, authToken, onComplete);
            }
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$3.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$8.default.hello(userAgent, authToken, this._serversideRouting, ['utc']), observer, true);
        return observer;
    };
    /**
     *
     * @param {string[]} patches Patches to be applied to the protocol
     */
    BoltProtocol.prototype._applyPatches = function (patches) {
        if (patches.includes('utc')) {
            this._applyUtcPatch();
        }
    };
    BoltProtocol.prototype._applyUtcPatch = function () {
        var _this = this;
        this._transformer = new transformer_1$a.default(Object.values(__assign$h(__assign$h({}, bolt_protocol_v4x3_transformer_1.default), bolt_protocol_v5x0_utc_transformer_1$2.default)).map(function (create) { return create(_this._config, _this._log); }));
    };
    return BoltProtocol;
}(bolt_protocol_v4x2_1$1.default));
boltProtocolV4x3.default = BoltProtocol$a;

var boltProtocolV4x4 = {};

var __extends$g = (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 __assign$g = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$g = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$g.apply(this, arguments);
};
var __importDefault$q = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV4x4, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v4x3_1$1 = __importDefault$q(boltProtocolV4x3);
var neo4j_driver_core_1$l = lib$1;
var request_message_1$7 = __importDefault$q(requestMessage);
var stream_observers_1$7 = streamObservers;
var bolt_protocol_util_1$2 = boltProtocolUtil;
var bolt_protocol_v4x4_transformer_1$1 = __importDefault$q(boltProtocolV4x4_transformer);
var bolt_protocol_v5x0_utc_transformer_1$1 = __importDefault$q(boltProtocolV5x0_utc_transformer);
var transformer_1$9 = __importDefault$q(transformer);
var _a$7 = neo4j_driver_core_1$l.internal.constants, BOLT_PROTOCOL_V4_4$2 = _a$7.BOLT_PROTOCOL_V4_4, FETCH_ALL$3 = _a$7.FETCH_ALL, Bookmarks$1 = neo4j_driver_core_1$l.internal.bookmarks.Bookmarks;
var BoltProtocol$9 = /** @class */ (function (_super) {
    __extends$g(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V4_4$2;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$9.default(Object.values(bolt_protocol_v4x4_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
    * Request routing information
    *
    * @param {Object} param -
    * @param {object} param.routingContext The routing context used to define the routing table.
    *  Multi-datacenter deployments is one of its use cases
    * @param {string} param.databaseName The database name
    * @param {Bookmarks} params.sessionContext.bookmarks The bookmarks used for requesting the routing table
    * @param {function(err: Error)} param.onError
    * @param {function(RawRoutingTable)} param.onCompleted
    * @returns {RouteObserver} the route observer
    */
    BoltProtocol.prototype.requestRoutingInformation = function (_a) {
        var _b = _a.routingContext, routingContext = _b === void 0 ? {} : _b, _c = _a.databaseName, databaseName = _c === void 0 ? null : _c, _d = _a.impersonatedUser, impersonatedUser = _d === void 0 ? null : _d, _e = _a.sessionContext, sessionContext = _e === void 0 ? {} : _e, onError = _a.onError, onCompleted = _a.onCompleted;
        var observer = new stream_observers_1$7.RouteObserver({
            onProtocolError: this._onProtocolError,
            onError: onError,
            onCompleted: onCompleted
        });
        var bookmarks = sessionContext.bookmarks || Bookmarks$1.empty();
        this.write(request_message_1$7.default.routeV4x4(routingContext, bookmarks.values(), { databaseName: databaseName, impersonatedUser: impersonatedUser }), observer, true);
        return observer;
    };
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.reactive, reactive = _d === void 0 ? false : _d, _e = _b.fetchSize, fetchSize = _e === void 0 ? FETCH_ALL$3 : _e, _f = _b.highRecordWatermark, highRecordWatermark = _f === void 0 ? Number.MAX_VALUE : _f, _g = _b.lowRecordWatermark, lowRecordWatermark = _g === void 0 ? Number.MAX_VALUE : _g;
        var observer = new stream_observers_1$7.ResultStreamObserver({
            server: this._server,
            reactive: reactive,
            fetchSize: fetchSize,
            moreFunction: this._requestMore.bind(this),
            discardFunction: this._requestDiscard.bind(this),
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$2.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        var flushRun = reactive;
        this.write(request_message_1$7.default.runWithMetadata(query, parameters, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            database: database,
            mode: mode,
            impersonatedUser: impersonatedUser
        }), observer, flushRun && flush);
        if (!reactive) {
            this.write(request_message_1$7.default.pull({ n: fetchSize }), observer, flush);
        }
        return observer;
    };
    BoltProtocol.prototype.beginTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$7.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$2.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$7.default.begin({ bookmarks: bookmarks, txConfig: txConfig, database: database, mode: mode, impersonatedUser: impersonatedUser }), observer, true);
        return observer;
    };
    BoltProtocol.prototype._applyUtcPatch = function () {
        var _this = this;
        this._transformer = new transformer_1$9.default(Object.values(__assign$g(__assign$g({}, bolt_protocol_v4x4_transformer_1$1.default), bolt_protocol_v5x0_utc_transformer_1$1.default)).map(function (create) { return create(_this._config, _this._log); }));
    };
    return BoltProtocol;
}(bolt_protocol_v4x3_1$1.default));
boltProtocolV4x4.default = BoltProtocol$9;

var boltProtocolV5x0 = {};

var boltProtocolV5x0_transformer = {};

/**
 * 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 __assign$f = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$f = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$f.apply(this, arguments);
};
var __read$3 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __importDefault$p = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x0_transformer, "__esModule", { value: true });
var packstream_1 = packstream;
var neo4j_driver_core_1$k = lib$1;
var bolt_protocol_v4x4_transformer_1 = __importDefault$p(boltProtocolV4x4_transformer);
var bolt_protocol_v5x0_utc_transformer_1 = __importDefault$p(boltProtocolV5x0_utc_transformer);
var NODE_STRUCT_SIZE = 4;
var RELATIONSHIP_STRUCT_SIZE = 8;
var UNBOUND_RELATIONSHIP_STRUCT_SIZE = 4;
/**
 * Create an extend Node transformer with support to elementId
 * @param {any} config
 * @returns {TypeTransformer}
 */
function createNodeTransformer(config) {
    var node4x4Transformer = bolt_protocol_v4x4_transformer_1.default.createNodeTransformer(config);
    return node4x4Transformer.extendsWith({
        fromStructure: function (struct) {
            packstream_1.structure.verifyStructSize('Node', NODE_STRUCT_SIZE, struct.size);
            var _a = __read$3(struct.fields, 4), identity = _a[0], lables = _a[1], properties = _a[2], elementId = _a[3];
            return new neo4j_driver_core_1$k.Node(identity, lables, properties, elementId);
        }
    });
}
/**
 * Create an extend Relationship transformer with support to elementId
 * @param {any} config
 * @returns {TypeTransformer}
 */
function createRelationshipTransformer(config) {
    var relationship4x4Transformer = bolt_protocol_v4x4_transformer_1.default.createRelationshipTransformer(config);
    return relationship4x4Transformer.extendsWith({
        fromStructure: function (struct) {
            packstream_1.structure.verifyStructSize('Relationship', RELATIONSHIP_STRUCT_SIZE, struct.size);
            var _a = __read$3(struct.fields, 8), identity = _a[0], startNodeIdentity = _a[1], endNodeIdentity = _a[2], type = _a[3], properties = _a[4], elementId = _a[5], startNodeElementId = _a[6], endNodeElementId = _a[7];
            return new neo4j_driver_core_1$k.Relationship(identity, startNodeIdentity, endNodeIdentity, type, properties, elementId, startNodeElementId, endNodeElementId);
        }
    });
}
/**
 * Create an extend Unbound Relationship transformer with support to elementId
 * @param {any} config
 * @returns {TypeTransformer}
 */
function createUnboundRelationshipTransformer(config) {
    var unboundRelationshipTransformer = bolt_protocol_v4x4_transformer_1.default.createUnboundRelationshipTransformer(config);
    return unboundRelationshipTransformer.extendsWith({
        fromStructure: function (struct) {
            packstream_1.structure.verifyStructSize('UnboundRelationship', UNBOUND_RELATIONSHIP_STRUCT_SIZE, struct.size);
            var _a = __read$3(struct.fields, 4), identity = _a[0], type = _a[1], properties = _a[2], elementId = _a[3];
            return new neo4j_driver_core_1$k.UnboundRelationship(identity, type, properties, elementId);
        }
    });
}
boltProtocolV5x0_transformer.default = __assign$f(__assign$f(__assign$f({}, bolt_protocol_v4x4_transformer_1.default), bolt_protocol_v5x0_utc_transformer_1.default), { createNodeTransformer: createNodeTransformer, createRelationshipTransformer: createRelationshipTransformer, createUnboundRelationshipTransformer: createUnboundRelationshipTransformer });

var __extends$f = (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 __importDefault$o = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x0, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v4x4_1$1 = __importDefault$o(boltProtocolV4x4);
var bolt_protocol_util_1$1 = boltProtocolUtil;
var bolt_protocol_v5x0_transformer_1$1 = __importDefault$o(boltProtocolV5x0_transformer);
var transformer_1$8 = __importDefault$o(transformer);
var request_message_1$6 = __importDefault$o(requestMessage);
var stream_observers_1$6 = streamObservers;
var neo4j_driver_core_1$j = lib$1;
var BOLT_PROTOCOL_V5_0 = neo4j_driver_core_1$j.internal.constants.BOLT_PROTOCOL_V5_0;
var BoltProtocol$8 = /** @class */ (function (_super) {
    __extends$f(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$8.default(Object.values(bolt_protocol_v5x0_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Initialize a connection with the server
     *
     * @param {Object} args The params
     * @param {string} args.userAgent The user agent
     * @param {any} args.authToken The auth token
     * @param {NotificationFilter} args.notificationFilter The notification filter.
     * @param {function(error)} args.onError On error callback
     * @param {function(onComplte)} args.onComplete On complete callback
     * @returns {LoginObserver} The Login observer
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var observer = new stream_observers_1$6.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) { return _this._onLoginCompleted(metadata, authToken, onComplete); }
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1$1.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$6.default.hello(userAgent, authToken, this._serversideRouting), observer, true);
        return observer;
    };
    return BoltProtocol;
}(bolt_protocol_v4x4_1$1.default));
boltProtocolV5x0.default = BoltProtocol$8;

var boltProtocolV5x1 = {};

var boltProtocolV5x1_transformer = {};

/**
 * 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 __assign$e = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$e = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$e.apply(this, arguments);
};
var __importDefault$n = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x1_transformer, "__esModule", { value: true });
var bolt_protocol_v5x0_transformer_1 = __importDefault$n(boltProtocolV5x0_transformer);
boltProtocolV5x1_transformer.default = __assign$e({}, bolt_protocol_v5x0_transformer_1.default);

var __extends$e = (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 __assign$d = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$d = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$d.apply(this, arguments);
};
var __importDefault$m = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x1, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x0_1$1 = __importDefault$m(boltProtocolV5x0);
var bolt_protocol_util_1 = boltProtocolUtil;
var bolt_protocol_v5x1_transformer_1$1 = __importDefault$m(boltProtocolV5x1_transformer);
var transformer_1$7 = __importDefault$m(transformer);
var request_message_1$5 = __importDefault$m(requestMessage);
var stream_observers_1$5 = streamObservers;
var neo4j_driver_core_1$i = lib$1;
var BOLT_PROTOCOL_V5_1$2 = neo4j_driver_core_1$i.internal.constants.BOLT_PROTOCOL_V5_1;
var BoltProtocol$7 = /** @class */ (function (_super) {
    __extends$e(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_1$2;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$7.default(Object.values(bolt_protocol_v5x1_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "supportsReAuth", {
        get: function () {
            return true;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Initialize a connection with the server
     *
     * @param {Object} args The params
     * @param {string} args.userAgent The user agent
     * @param {any} args.authToken The auth token
     * @param {NotificationFilter} args.notificationFilter The notification filters.
     * @param {function(error)} args.onError On error callback
     * @param {function(onComplete)} args.onComplete On complete callback
     * @returns {LoginObserver} The Login observer
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var state = {};
        var observer = new stream_observers_1$5.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) {
                state.metadata = metadata;
                return _this._onLoginCompleted(metadata);
            }
        });
        // passing notification filter on this protocol version throws an error
        (0, bolt_protocol_util_1.assertNotificationFilterIsEmpty)(notificationFilter, this._onProtocolError, observer);
        this.write(request_message_1$5.default.hello5x1(userAgent, this._serversideRouting), observer, false);
        return this.logon({
            authToken: authToken,
            onComplete: function (metadata) { return onComplete(__assign$d(__assign$d({}, metadata), state.metadata)); },
            onError: onError,
            flush: true
        });
    };
    /**
     * Performs login of the underlying connection
     *
     * @param {Object} args
     * @param {Object} args.authToken the authentication token.
     * @param {function(err: Error)} args.onError the callback to invoke on error.
     * @param {function()} args.onComplete the callback to invoke on completion.
     * @param {boolean} args.flush whether to flush the buffered messages.
     *
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.logon = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, authToken = _b.authToken, onComplete = _b.onComplete, onError = _b.onError, flush = _b.flush;
        var observer = new stream_observers_1$5.LoginObserver({
            onCompleted: function () { return _this._onLoginCompleted(null, authToken, onComplete); },
            onError: function (error) { return _this._onLoginError(error, onError); }
        });
        this.write(request_message_1$5.default.logon(authToken), observer, flush);
        return observer;
    };
    /**
     * Performs logoff of the underlying connection
     *
     * @param {Object} param
     * @param {function(err: Error)} param.onError the callback to invoke on error.
     * @param {function()} param.onComplete the callback to invoke on completion.
     * @param {boolean} param.flush whether to flush the buffered messages.
     *
     * @returns {StreamObserver} the stream observer that monitors the corresponding server response.
    */
    BoltProtocol.prototype.logoff = function (_a) {
        var _b = _a === void 0 ? {} : _a, onComplete = _b.onComplete, onError = _b.onError, flush = _b.flush;
        var observer = new stream_observers_1$5.LogoffObserver({
            onCompleted: onComplete,
            onError: onError
        });
        this.write(request_message_1$5.default.logoff(), observer, flush);
        return observer;
    };
    return BoltProtocol;
}(bolt_protocol_v5x0_1$1.default));
boltProtocolV5x1.default = BoltProtocol$7;

var boltProtocolV5x2 = {};

var boltProtocolV5x2_transformer = {};

/**
 * 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 __assign$c = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$c = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$c.apply(this, arguments);
};
var __importDefault$l = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x2_transformer, "__esModule", { value: true });
var bolt_protocol_v5x1_transformer_1 = __importDefault$l(boltProtocolV5x1_transformer);
boltProtocolV5x2_transformer.default = __assign$c({}, bolt_protocol_v5x1_transformer_1.default);

var __extends$d = (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 __assign$b = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$b = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$b.apply(this, arguments);
};
var __importDefault$k = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x2, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x1_1$1 = __importDefault$k(boltProtocolV5x1);
var bolt_protocol_v5x2_transformer_1$1 = __importDefault$k(boltProtocolV5x2_transformer);
var transformer_1$6 = __importDefault$k(transformer);
var request_message_1$4 = __importDefault$k(requestMessage);
var stream_observers_1$4 = streamObservers;
var neo4j_driver_core_1$h = lib$1;
var _a$6 = neo4j_driver_core_1$h.internal.constants, BOLT_PROTOCOL_V5_2 = _a$6.BOLT_PROTOCOL_V5_2, FETCH_ALL$2 = _a$6.FETCH_ALL;
var BoltProtocol$6 = /** @class */ (function (_super) {
    __extends$d(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_2;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$6.default(Object.values(bolt_protocol_v5x2_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "supportsReAuth", {
        get: function () {
            return true;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Initialize a connection with the server
     *
     * @param {Object} args The params
     * @param {string} args.userAgent The user agent
     * @param {string} args.boltAgent The bolt agent
     * @param {any} args.authToken The auth token
     * @param {NotificationFilter} args.notificationFilter The notification filters.
     * @param {function(error)} args.onError On error callback
     * @param {function(onComplete)} args.onComplete On complete callback
     * @returns {LoginObserver} The Login observer
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent; _b.boltAgent; var authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var state = {};
        var observer = new stream_observers_1$4.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) {
                state.metadata = metadata;
                return _this._onLoginCompleted(metadata);
            }
        });
        this.write(
        // if useragent is null then for all versions before 5.3 it should be bolt agent by default
        request_message_1$4.default.hello5x2(userAgent, notificationFilter, this._serversideRouting), observer, false);
        return this.logon({
            authToken: authToken,
            onComplete: function (metadata) { return onComplete(__assign$b(__assign$b({}, metadata), state.metadata)); },
            onError: onError,
            flush: true
        });
    };
    BoltProtocol.prototype.beginTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$4.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        this.write(request_message_1$4.default.begin({ bookmarks: bookmarks, txConfig: txConfig, database: database, mode: mode, impersonatedUser: impersonatedUser, notificationFilter: notificationFilter }), observer, true);
        return observer;
    };
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.reactive, reactive = _d === void 0 ? false : _d, _e = _b.fetchSize, fetchSize = _e === void 0 ? FETCH_ALL$2 : _e, _f = _b.highRecordWatermark, highRecordWatermark = _f === void 0 ? Number.MAX_VALUE : _f, _g = _b.lowRecordWatermark, lowRecordWatermark = _g === void 0 ? Number.MAX_VALUE : _g;
        var observer = new stream_observers_1$4.ResultStreamObserver({
            server: this._server,
            reactive: reactive,
            fetchSize: fetchSize,
            moreFunction: this._requestMore.bind(this),
            discardFunction: this._requestDiscard.bind(this),
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark
        });
        var flushRun = reactive;
        this.write(request_message_1$4.default.runWithMetadata(query, parameters, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            database: database,
            mode: mode,
            impersonatedUser: impersonatedUser,
            notificationFilter: notificationFilter
        }), observer, flushRun && flush);
        if (!reactive) {
            this.write(request_message_1$4.default.pull({ n: fetchSize }), observer, flush);
        }
        return observer;
    };
    return BoltProtocol;
}(bolt_protocol_v5x1_1$1.default));
boltProtocolV5x2.default = BoltProtocol$6;

var boltProtocolV5x3 = {};

var boltProtocolV5x3_transformer = {};

/**
 * 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 __assign$a = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$a = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$a.apply(this, arguments);
};
var __importDefault$j = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x3_transformer, "__esModule", { value: true });
var bolt_protocol_v5x2_transformer_1 = __importDefault$j(boltProtocolV5x2_transformer);
boltProtocolV5x3_transformer.default = __assign$a({}, bolt_protocol_v5x2_transformer_1.default);

var __extends$c = (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 __assign$9 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$9 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$9.apply(this, arguments);
};
var __importDefault$i = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x3, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x2_1$1 = __importDefault$i(boltProtocolV5x2);
var bolt_protocol_v5x3_transformer_1$1 = __importDefault$i(boltProtocolV5x3_transformer);
var transformer_1$5 = __importDefault$i(transformer);
var request_message_1$3 = __importDefault$i(requestMessage);
var stream_observers_1$3 = streamObservers;
var neo4j_driver_core_1$g = lib$1;
var BOLT_PROTOCOL_V5_3 = neo4j_driver_core_1$g.internal.constants.BOLT_PROTOCOL_V5_3;
var BoltProtocol$5 = /** @class */ (function (_super) {
    __extends$c(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_3;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$5.default(Object.values(bolt_protocol_v5x3_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Initialize a connection with the server
     *
     * @param {Object} args The params
     * @param {string} args.userAgent The user agent
     * @param {any} args.authToken The auth token
     * @param {NotificationFilter} args.notificationFilter The notification filters.
     * @param {function(error)} args.onError On error callback
     * @param {function(onComplete)} args.onComplete On complete callback
     * @returns {LoginObserver} The Login observer
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent, boltAgent = _b.boltAgent, authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var state = {};
        var observer = new stream_observers_1$3.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) {
                state.metadata = metadata;
                return _this._onLoginCompleted(metadata);
            }
        });
        this.write(request_message_1$3.default.hello5x3(userAgent, boltAgent, notificationFilter, this._serversideRouting), observer, false);
        return this.logon({
            authToken: authToken,
            onComplete: function (metadata) { return onComplete(__assign$9(__assign$9({}, metadata), state.metadata)); },
            onError: onError,
            flush: true
        });
    };
    return BoltProtocol;
}(bolt_protocol_v5x2_1$1.default));
boltProtocolV5x3.default = BoltProtocol$5;

var boltProtocolV5x4 = {};

var boltProtocolV5x4_transformer = {};

/**
 * 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 __assign$8 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$8 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$8.apply(this, arguments);
};
var __importDefault$h = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x4_transformer, "__esModule", { value: true });
var bolt_protocol_v5x3_transformer_1 = __importDefault$h(boltProtocolV5x3_transformer);
boltProtocolV5x4_transformer.default = __assign$8({}, bolt_protocol_v5x3_transformer_1.default);

var __extends$b = (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 __importDefault$g = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x4, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x3_1$1 = __importDefault$g(boltProtocolV5x3);
var bolt_protocol_v5x4_transformer_1$1 = __importDefault$g(boltProtocolV5x4_transformer);
var request_message_1$2 = __importDefault$g(requestMessage);
var stream_observers_1$2 = streamObservers;
var transformer_1$4 = __importDefault$g(transformer);
var neo4j_driver_core_1$f = lib$1;
var BOLT_PROTOCOL_V5_4 = neo4j_driver_core_1$f.internal.constants.BOLT_PROTOCOL_V5_4;
var BoltProtocol$4 = /** @class */ (function (_super) {
    __extends$b(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_4;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$4.default(Object.values(bolt_protocol_v5x4_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Send a TELEMETRY through the underlying connection.
     *
     * @param {object} param0 Message params
     * @param {number} param0.api The API called
     * @param {object} param1 Configuration and callbacks callbacks
     * @param {function()} param1.onCompleted Called when completed
     * @param {function()} param1.onError Called when error
     * @return {StreamObserver} the stream observer that monitors the corresponding server response.
     */
    BoltProtocol.prototype.telemetry = function (_a, _b) {
        var api = _a.api;
        var _c = _b === void 0 ? {} : _b, onError = _c.onError, onCompleted = _c.onCompleted;
        var observer = new stream_observers_1$2.TelemetryObserver({ onCompleted: onCompleted, onError: onError });
        this.write(request_message_1$2.default.telemetry({ api: api }), observer, false);
        return observer;
    };
    return BoltProtocol;
}(bolt_protocol_v5x3_1$1.default));
boltProtocolV5x4.default = BoltProtocol$4;

var boltProtocolV5x5 = {};

var boltProtocolV5x5_transformer = {};

/**
 * 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 __assign$7 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$7 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$7.apply(this, arguments);
};
var __importDefault$f = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x5_transformer, "__esModule", { value: true });
var bolt_protocol_v5x4_transformer_1 = __importDefault$f(boltProtocolV5x4_transformer);
boltProtocolV5x5_transformer.default = __assign$7({}, bolt_protocol_v5x4_transformer_1.default);

var __extends$a = (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 __assign$6 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$6 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$6.apply(this, arguments);
};
var __importDefault$e = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x5, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x4_1$1 = __importDefault$e(boltProtocolV5x4);
var bolt_protocol_v5x5_transformer_1$1 = __importDefault$e(boltProtocolV5x5_transformer);
var transformer_1$3 = __importDefault$e(transformer);
var request_message_1$1 = __importDefault$e(requestMessage);
var stream_observers_1$1 = streamObservers;
var neo4j_driver_core_1$e = lib$1;
var _a$5 = neo4j_driver_core_1$e.internal.constants, BOLT_PROTOCOL_V5_5 = _a$5.BOLT_PROTOCOL_V5_5, FETCH_ALL$1 = _a$5.FETCH_ALL;
var DEFAULT_DIAGNOSTIC_RECORD$2 = Object.freeze({
    OPERATION: '',
    OPERATION_CODE: '0',
    CURRENT_SCHEMA: '/'
});
var BoltProtocol$3 = /** @class */ (function (_super) {
    __extends$a(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_5;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$3.default(Object.values(bolt_protocol_v5x5_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Initialize a connection with the server
     *
     * @param {Object} args The params
     * @param {string} args.userAgent The user agent
     * @param {any} args.authToken The auth token
     * @param {NotificationFilter} args.notificationFilter The notification filters.
     * @param {function(error)} args.onError On error callback
     * @param {function(onComplete)} args.onComplete On complete callback
     * @returns {LoginObserver} The Login observer
     */
    BoltProtocol.prototype.initialize = function (_a) {
        var _this = this;
        var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent, boltAgent = _b.boltAgent, authToken = _b.authToken, notificationFilter = _b.notificationFilter, onError = _b.onError, onComplete = _b.onComplete;
        var state = {};
        var observer = new stream_observers_1$1.LoginObserver({
            onError: function (error) { return _this._onLoginError(error, onError); },
            onCompleted: function (metadata) {
                state.metadata = metadata;
                return _this._onLoginCompleted(metadata);
            }
        });
        this.write(request_message_1$1.default.hello5x5(userAgent, boltAgent, notificationFilter, this._serversideRouting), observer, false);
        return this.logon({
            authToken: authToken,
            onComplete: function (metadata) { return onComplete(__assign$6(__assign$6({}, metadata), state.metadata)); },
            onError: onError,
            flush: true
        });
    };
    BoltProtocol.prototype.beginTransaction = function (_a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete;
        var observer = new stream_observers_1$1.ResultStreamObserver({
            server: this._server,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete
        });
        observer.prepareToHandleSingleResponse();
        this.write(request_message_1$1.default.begin5x5({ bookmarks: bookmarks, txConfig: txConfig, database: database, mode: mode, impersonatedUser: impersonatedUser, notificationFilter: notificationFilter }), observer, true);
        return observer;
    };
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.reactive, reactive = _d === void 0 ? false : _d, _e = _b.fetchSize, fetchSize = _e === void 0 ? FETCH_ALL$1 : _e, _f = _b.highRecordWatermark, highRecordWatermark = _f === void 0 ? Number.MAX_VALUE : _f, _g = _b.lowRecordWatermark, lowRecordWatermark = _g === void 0 ? Number.MAX_VALUE : _g;
        var observer = new stream_observers_1$1.ResultStreamObserver({
            server: this._server,
            reactive: reactive,
            fetchSize: fetchSize,
            moreFunction: this._requestMore.bind(this),
            discardFunction: this._requestDiscard.bind(this),
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark,
            enrichMetadata: this._enrichMetadata
        });
        var flushRun = reactive;
        this.write(request_message_1$1.default.runWithMetadata5x5(query, parameters, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            database: database,
            mode: mode,
            impersonatedUser: impersonatedUser,
            notificationFilter: notificationFilter
        }), observer, flushRun && flush);
        if (!reactive) {
            this.write(request_message_1$1.default.pull({ n: fetchSize }), observer, flush);
        }
        return observer;
    };
    /**
     *
     * @param {object} metadata
     * @returns {object}
     */
    BoltProtocol.prototype._enrichMetadata = function (metadata) {
        if (Array.isArray(metadata.statuses)) {
            metadata.statuses = metadata.statuses.map(function (status) { return (__assign$6(__assign$6({}, status), { description: status.neo4j_code != null ? status.status_description : status.description, diagnostic_record: status.diagnostic_record !== null ? __assign$6(__assign$6({}, DEFAULT_DIAGNOSTIC_RECORD$2), status.diagnostic_record) : null })); });
        }
        return metadata;
    };
    return BoltProtocol;
}(bolt_protocol_v5x4_1$1.default));
boltProtocolV5x5.default = BoltProtocol$3;

var boltProtocolV5x6 = {};

var boltProtocolV5x6_transformer = {};

/**
 * 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 __assign$5 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$5 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$5.apply(this, arguments);
};
var __importDefault$d = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x6_transformer, "__esModule", { value: true });
var bolt_protocol_v5x5_transformer_1 = __importDefault$d(boltProtocolV5x5_transformer);
boltProtocolV5x6_transformer.default = __assign$5({}, bolt_protocol_v5x5_transformer_1.default);

var __extends$9 = (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 __assign$4 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$4 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$4.apply(this, arguments);
};
var __importDefault$c = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x6, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x5_1$1 = __importDefault$c(boltProtocolV5x5);
var bolt_protocol_v5x6_transformer_1$1 = __importDefault$c(boltProtocolV5x6_transformer);
var transformer_1$2 = __importDefault$c(transformer);
var neo4j_driver_core_1$d = lib$1;
var BOLT_PROTOCOL_V5_6 = neo4j_driver_core_1$d.internal.constants.BOLT_PROTOCOL_V5_6;
var DEFAULT_DIAGNOSTIC_RECORD$1 = Object.freeze({
    OPERATION: '',
    OPERATION_CODE: '0',
    CURRENT_SCHEMA: '/'
});
var BoltProtocol$2 = /** @class */ (function (_super) {
    __extends$9(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_6;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$2.default(Object.values(bolt_protocol_v5x6_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     *
     * @param {object} metadata
     * @returns {object}
     */
    BoltProtocol.prototype._enrichMetadata = function (metadata) {
        if (Array.isArray(metadata.statuses)) {
            metadata.statuses = metadata.statuses.map(function (status) { return (__assign$4(__assign$4({}, status), { diagnostic_record: status.diagnostic_record !== null ? __assign$4(__assign$4({}, DEFAULT_DIAGNOSTIC_RECORD$1), status.diagnostic_record) : null })); });
        }
        return metadata;
    };
    return BoltProtocol;
}(bolt_protocol_v5x5_1$1.default));
boltProtocolV5x6.default = BoltProtocol$2;

var boltProtocolV5x7 = {};

var boltProtocolV5x7_transformer = {};

/**
 * 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 __assign$3 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$3 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$3.apply(this, arguments);
};
var __importDefault$b = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x7_transformer, "__esModule", { value: true });
var bolt_protocol_v5x6_transformer_1 = __importDefault$b(boltProtocolV5x6_transformer);
boltProtocolV5x7_transformer.default = __assign$3({}, bolt_protocol_v5x6_transformer_1.default);

var __extends$8 = (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 __assign$2 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$2 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$2.apply(this, arguments);
};
var __importDefault$a = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x7, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x6_1$1 = __importDefault$a(boltProtocolV5x6);
var bolt_protocol_v5x7_transformer_1$1 = __importDefault$a(boltProtocolV5x7_transformer);
var transformer_1$1 = __importDefault$a(transformer);
var neo4j_driver_core_1$c = lib$1;
var BOLT_PROTOCOL_V5_7 = neo4j_driver_core_1$c.internal.constants.BOLT_PROTOCOL_V5_7;
var DEFAULT_DIAGNOSTIC_RECORD = Object.freeze({
    OPERATION: '',
    OPERATION_CODE: '0',
    CURRENT_SCHEMA: '/'
});
var BoltProtocol$1 = /** @class */ (function (_super) {
    __extends$8(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_7;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1$1.default(Object.values(bolt_protocol_v5x7_transformer_1$1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    /**
     *
     * @param {object} metadata
     * @returns {object}
     */
    BoltProtocol.prototype.enrichErrorMetadata = function (metadata) {
        return __assign$2(__assign$2({}, metadata), { cause: (metadata.cause !== null && metadata.cause !== undefined) ? this.enrichErrorMetadata(metadata.cause) : null, code: metadata.neo4j_code, diagnostic_record: metadata.diagnostic_record !== null ? __assign$2(__assign$2({}, DEFAULT_DIAGNOSTIC_RECORD), metadata.diagnostic_record) : null });
    };
    return BoltProtocol;
}(bolt_protocol_v5x6_1$1.default));
boltProtocolV5x7.default = BoltProtocol$1;

var boltProtocolV5x8 = {};

var boltProtocolV5x8_transformer = {};

/**
 * 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 __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign$1 = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign$1.apply(this, arguments);
};
var __importDefault$9 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x8_transformer, "__esModule", { value: true });
var bolt_protocol_v5x7_transformer_1 = __importDefault$9(boltProtocolV5x7_transformer);
boltProtocolV5x8_transformer.default = __assign$1({}, bolt_protocol_v5x7_transformer_1.default);

var __extends$7 = (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 __importDefault$8 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(boltProtocolV5x8, "__esModule", { value: true });
/**
 * 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 bolt_protocol_v5x7_1$1 = __importDefault$8(boltProtocolV5x7);
var bolt_protocol_v5x8_transformer_1 = __importDefault$8(boltProtocolV5x8_transformer);
var transformer_1 = __importDefault$8(transformer);
var request_message_1 = __importDefault$8(requestMessage);
var stream_observers_1 = streamObservers;
var neo4j_driver_core_1$b = lib$1;
var _a$4 = neo4j_driver_core_1$b.internal.constants, BOLT_PROTOCOL_V5_8 = _a$4.BOLT_PROTOCOL_V5_8, FETCH_ALL = _a$4.FETCH_ALL;
var BoltProtocol = /** @class */ (function (_super) {
    __extends$7(BoltProtocol, _super);
    function BoltProtocol() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(BoltProtocol.prototype, "version", {
        get: function () {
            return BOLT_PROTOCOL_V5_8;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoltProtocol.prototype, "transformer", {
        get: function () {
            var _this = this;
            if (this._transformer === undefined) {
                this._transformer = new transformer_1.default(Object.values(bolt_protocol_v5x8_transformer_1.default).map(function (create) { return create(_this._config, _this._log); }));
            }
            return this._transformer;
        },
        enumerable: false,
        configurable: true
    });
    BoltProtocol.prototype.run = function (query, parameters, _a) {
        var _b = _a === void 0 ? {} : _a, bookmarks = _b.bookmarks, txConfig = _b.txConfig, database = _b.database, mode = _b.mode, impersonatedUser = _b.impersonatedUser, notificationFilter = _b.notificationFilter, beforeKeys = _b.beforeKeys, afterKeys = _b.afterKeys, beforeError = _b.beforeError, afterError = _b.afterError, beforeComplete = _b.beforeComplete, afterComplete = _b.afterComplete, _c = _b.flush, flush = _c === void 0 ? true : _c, _d = _b.reactive, reactive = _d === void 0 ? false : _d, _e = _b.fetchSize, fetchSize = _e === void 0 ? FETCH_ALL : _e, _f = _b.highRecordWatermark, highRecordWatermark = _f === void 0 ? Number.MAX_VALUE : _f, _g = _b.lowRecordWatermark, lowRecordWatermark = _g === void 0 ? Number.MAX_VALUE : _g, onDb = _b.onDb;
        var observer = new stream_observers_1.ResultStreamObserver({
            server: this._server,
            reactive: reactive,
            fetchSize: fetchSize,
            moreFunction: this._requestMore.bind(this),
            discardFunction: this._requestDiscard.bind(this),
            beforeKeys: beforeKeys,
            afterKeys: afterKeys,
            beforeError: beforeError,
            afterError: afterError,
            beforeComplete: beforeComplete,
            afterComplete: afterComplete,
            highRecordWatermark: highRecordWatermark,
            lowRecordWatermark: lowRecordWatermark,
            enrichMetadata: this._enrichMetadata,
            onDb: onDb
        });
        var flushRun = reactive;
        this.write(request_message_1.default.runWithMetadata5x5(query, parameters, {
            bookmarks: bookmarks,
            txConfig: txConfig,
            database: database,
            mode: mode,
            impersonatedUser: impersonatedUser,
            notificationFilter: notificationFilter
        }), observer, flushRun && flush);
        if (!reactive) {
            this.write(request_message_1.default.pull({ n: fetchSize }), observer, flush);
        }
        return observer;
    };
    return BoltProtocol;
}(bolt_protocol_v5x7_1$1.default));
boltProtocolV5x8.default = BoltProtocol;

var responseHandler = {};

Object.defineProperty(responseHandler, "__esModule", { value: true });
/**
 * 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 neo4j_driver_core_1$a = lib$1;
// Signature bytes for each response message type
var SUCCESS = 0x70; // 0111 0000 // SUCCESS <metadata>
var RECORD = 0x71; // 0111 0001 // RECORD <value>
var IGNORED = 0x7e; // 0111 1110 // IGNORED <metadata>
var FAILURE = 0x7f; // 0111 1111 // FAILURE <metadata>
function NO_OP() { }
function NO_OP_IDENTITY(subject) {
    return subject;
}
var NO_OP_OBSERVER = {
    onNext: NO_OP,
    onCompleted: NO_OP,
    onError: NO_OP
};
/**
 * Treat the protocol responses and notify the observers
 */
var ResponseHandler = /** @class */ (function () {
    /**
     * Called when something went wrong with the connectio
     * @callback ResponseHandler~Observer~OnErrorApplyTransformation
     * @param {any} error The error
     * @returns {any} The new error
     */
    /**
     * Called when something went wrong with the connectio
     * @callback ResponseHandler~Observer~OnError
     * @param {any} error The error
     */
    /**
     * Called when something went wrong with the connectio
     * @callback ResponseHandler~MetadataTransformer
     * @param {any} metadata The metadata got onSuccess
     * @returns {any} The transformed metadata
     */
    /**
     * @typedef {Object} ResponseHandler~Observer
     * @property {ResponseHandler~Observer~OnError} onError Invoke when a connection error occurs
     * @property {ResponseHandler~Observer~OnError} onFailure Invoke when a protocol failure occurs
     * @property {ResponseHandler~Observer~OnErrorApplyTransformation} onErrorApplyTransformation Invoke just after the failure occurs,
     *  before notify to respective observer. This method should transform the failure reason to the approprited one.
     */
    /**
     * Constructor
     * @param {Object} param The params
     * @param {ResponseHandler~MetadataTransformer} transformMetadata Transform metadata when the SUCCESS is received.
     * @param {Channel} channel The channel used to exchange messages
     * @param {Logger} log The logger
     * @param {ResponseHandler~Observer} observer Object which will be notified about errors
     */
    function ResponseHandler(_a) {
        var _b = _a === void 0 ? {} : _a, transformMetadata = _b.transformMetadata, enrichErrorMetadata = _b.enrichErrorMetadata, log = _b.log, observer = _b.observer;
        this._pendingObservers = [];
        this._log = log;
        this._transformMetadata = transformMetadata || NO_OP_IDENTITY;
        this._enrichErrorMetadata = enrichErrorMetadata || NO_OP_IDENTITY;
        this._observer = Object.assign({
            onObserversCountChange: NO_OP,
            onError: NO_OP,
            onFailure: NO_OP,
            onErrorApplyTransformation: NO_OP_IDENTITY
        }, observer);
    }
    Object.defineProperty(ResponseHandler.prototype, "currentFailure", {
        get: function () {
            return this._currentFailure;
        },
        enumerable: false,
        configurable: true
    });
    ResponseHandler.prototype.handleResponse = function (msg) {
        var payload = msg.fields[0];
        switch (msg.signature) {
            case RECORD:
                if (this._log.isDebugEnabled()) {
                    this._log.debug("S: RECORD ".concat(neo4j_driver_core_1$a.json.stringify(msg)));
                }
                this._currentObserver.onNext(payload);
                break;
            case SUCCESS:
                if (this._log.isDebugEnabled()) {
                    this._log.debug("S: SUCCESS ".concat(neo4j_driver_core_1$a.json.stringify(msg)));
                }
                try {
                    var metadata = this._transformMetadata(payload);
                    this._currentObserver.onCompleted(metadata);
                }
                finally {
                    this._updateCurrentObserver();
                }
                break;
            case FAILURE:
                if (this._log.isDebugEnabled()) {
                    this._log.debug("S: FAILURE ".concat(neo4j_driver_core_1$a.json.stringify(msg)));
                }
                try {
                    this._currentFailure = this._handleErrorPayload(this._enrichErrorMetadata(payload));
                    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._observer.onFailure(this._currentFailure);
                }
                break;
            case IGNORED:
                if (this._log.isDebugEnabled()) {
                    this._log.debug("S: IGNORED ".concat(neo4j_driver_core_1$a.json.stringify(msg)));
                }
                try {
                    if (this._currentFailure && this._currentObserver.onError) {
                        this._currentObserver.onError(this._currentFailure);
                    }
                    else if (this._currentObserver.onError) {
                        this._currentObserver.onError((0, neo4j_driver_core_1$a.newError)('Ignored either because of an error or RESET'));
                    }
                }
                finally {
                    this._updateCurrentObserver();
                }
                break;
            default:
                this._observer.onError((0, neo4j_driver_core_1$a.newError)('Unknown Bolt protocol message: ' + msg));
        }
    };
    /*
     * Pop next pending observer form the list of observers and make it current observer.
     * @protected
     */
    ResponseHandler.prototype._updateCurrentObserver = function () {
        this._currentObserver = this._pendingObservers.shift();
        this._observer.onObserversCountChange(this._observersCount);
    };
    Object.defineProperty(ResponseHandler.prototype, "_observersCount", {
        get: function () {
            return this._currentObserver == null ? this._pendingObservers.length : this._pendingObservers.length + 1;
        },
        enumerable: false,
        configurable: true
    });
    ResponseHandler.prototype._queueObserver = function (observer) {
        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);
        }
        this._observer.onObserversCountChange(this._observersCount);
        return true;
    };
    ResponseHandler.prototype._notifyErrorToObservers = function (error) {
        if (this._currentObserver && this._currentObserver.onError) {
            this._currentObserver.onError(error);
        }
        while (this._pendingObservers.length > 0) {
            var observer = this._pendingObservers.shift();
            if (observer && observer.onError) {
                observer.onError(error);
            }
        }
    };
    ResponseHandler.prototype.hasOngoingObservableRequests = function () {
        return this._currentObserver != null || this._pendingObservers.length > 0;
    };
    ResponseHandler.prototype._resetFailure = function () {
        this._currentFailure = null;
    };
    ResponseHandler.prototype._handleErrorPayload = function (payload) {
        var standardizedCode = _standardizeCode(payload.code);
        var cause = payload.cause != null ? this._handleErrorCause(payload.cause) : undefined;
        var error = (0, neo4j_driver_core_1$a.newError)(payload.message, standardizedCode, cause, payload.gql_status, payload.description, payload.diagnostic_record);
        return this._observer.onErrorApplyTransformation(error);
    };
    ResponseHandler.prototype._handleErrorCause = function (payload) {
        var cause = payload.cause != null ? this._handleErrorCause(payload.cause) : undefined;
        var error = (0, neo4j_driver_core_1$a.newGQLError)(payload.message, cause, payload.gql_status, payload.description, payload.diagnostic_record);
        return this._observer.onErrorApplyTransformation(error);
    };
    return ResponseHandler;
}());
responseHandler.default = ResponseHandler;
/**
 * Standardize error classification that are different between 5.x and previous versions.
 *
 * The transient error were clean-up for being retrieable and because of this
 * `Terminated` and `LockClientStopped` were reclassified as `ClientError`.
 *
 * @param {string} code
 * @returns {string} the standardized error code
 */
function _standardizeCode(code) {
    if (code === 'Neo.TransientError.Transaction.Terminated') {
        return 'Neo.ClientError.Transaction.Terminated';
    }
    else if (code === 'Neo.TransientError.Transaction.LockClientStopped') {
        return 'Neo.ClientError.Transaction.LockClientStopped';
    }
    return code;
}

/**
 * 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 __importDefault$7 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(create$1, "__esModule", { value: true });
create$1.default = create;
var neo4j_driver_core_1$9 = lib$1;
var bolt_protocol_v1_1 = __importDefault$7(boltProtocolV1);
var bolt_protocol_v2_1 = __importDefault$7(boltProtocolV2);
var bolt_protocol_v3_1 = __importDefault$7(boltProtocolV3);
var bolt_protocol_v4x0_1 = __importDefault$7(boltProtocolV4x0);
var bolt_protocol_v4x1_1 = __importDefault$7(boltProtocolV4x1);
var bolt_protocol_v4x2_1 = __importDefault$7(boltProtocolV4x2);
var bolt_protocol_v4x3_1 = __importDefault$7(boltProtocolV4x3);
var bolt_protocol_v4x4_1 = __importDefault$7(boltProtocolV4x4);
var bolt_protocol_v5x0_1 = __importDefault$7(boltProtocolV5x0);
var bolt_protocol_v5x1_1 = __importDefault$7(boltProtocolV5x1);
var bolt_protocol_v5x2_1 = __importDefault$7(boltProtocolV5x2);
var bolt_protocol_v5x3_1 = __importDefault$7(boltProtocolV5x3);
var bolt_protocol_v5x4_1 = __importDefault$7(boltProtocolV5x4);
var bolt_protocol_v5x5_1 = __importDefault$7(boltProtocolV5x5);
var bolt_protocol_v5x6_1 = __importDefault$7(boltProtocolV5x6);
var bolt_protocol_v5x7_1 = __importDefault$7(boltProtocolV5x7);
var bolt_protocol_v5x8_1 = __importDefault$7(boltProtocolV5x8);
var response_handler_1 = __importDefault$7(responseHandler);
/**
 * Creates a protocol with a given version
 *
 * @param {object} config
 * @param {number} config.version The version of the protocol
 * @param {channel} config.channel The channel
 * @param {Chunker} config.chunker The chunker
 * @param {Dechunker} config.dechunker The dechunker
 * @param {Logger} config.log The logger
 * @param {ResponseHandler~Observer} config.observer Observer
 * @param {boolean} config.disableLosslessIntegers Disable the lossless integers
 * @param {boolean} packstreamConfig.useBigInt if this connection should convert all received integers to native BigInt numbers.
 * @param {boolean} config.serversideRouting It's using server side routing
 */
function create(_a) {
    var _b = _a === void 0 ? {} : _a, version = _b.version, chunker = _b.chunker, dechunker = _b.dechunker, channel = _b.channel, disableLosslessIntegers = _b.disableLosslessIntegers, useBigInt = _b.useBigInt, serversideRouting = _b.serversideRouting, server = _b.server, // server info
    log = _b.log, observer = _b.observer;
    var createResponseHandler = function (protocol) {
        var responseHandler = new response_handler_1.default({
            transformMetadata: protocol.transformMetadata.bind(protocol),
            enrichErrorMetadata: protocol.enrichErrorMetadata.bind(protocol),
            log: log,
            observer: observer
        });
        // reset the error handler to just handle errors and forget about the handshake promise
        channel.onerror = observer.onError.bind(observer);
        // Ok, protocol running. Simply forward all messages to the dechunker
        channel.onmessage = function (buf) { return dechunker.write(buf); };
        // setup dechunker to dechunk messages and forward them to the message handler
        dechunker.onmessage = function (buf) {
            try {
                responseHandler.handleResponse(protocol.unpack(buf));
            }
            catch (e) {
                return observer.onError(e);
            }
        };
        return responseHandler;
    };
    return createProtocol(version, server, chunker, { disableLosslessIntegers: disableLosslessIntegers, useBigInt: useBigInt }, serversideRouting, createResponseHandler, observer.onProtocolError.bind(observer), log);
}
function createProtocol(version, server, chunker, packingConfig, serversideRouting, createResponseHandler, onProtocolError, log) {
    switch (version) {
        case 1:
            return new bolt_protocol_v1_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError);
        case 2:
            return new bolt_protocol_v2_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError);
        case 3:
            return new bolt_protocol_v3_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError);
        case 4.0:
            return new bolt_protocol_v4x0_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError);
        case 4.1:
            return new bolt_protocol_v4x1_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 4.2:
            return new bolt_protocol_v4x2_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 4.3:
            return new bolt_protocol_v4x3_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 4.4:
            return new bolt_protocol_v4x4_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.0:
            return new bolt_protocol_v5x0_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.1:
            return new bolt_protocol_v5x1_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.2:
            return new bolt_protocol_v5x2_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.3:
            return new bolt_protocol_v5x3_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.4:
            return new bolt_protocol_v5x4_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.5:
            return new bolt_protocol_v5x5_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.6:
            return new bolt_protocol_v5x6_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.7:
            return new bolt_protocol_v5x7_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        case 5.8:
            return new bolt_protocol_v5x8_1.default(server, chunker, packingConfig, createResponseHandler, log, onProtocolError, serversideRouting);
        default:
            throw (0, neo4j_driver_core_1$9.newError)('Unknown Bolt protocol version: ' + version);
    }
}

(function (exports) {
var __createBinding = (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 __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RawRoutingTable = exports.BoltProtocol = 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.
 */
var handshake_1 = __importDefault(handshake$1);
var create_1 = __importDefault(create$1);
var bolt_protocol_v4x3_1 = __importDefault(boltProtocolV4x3);
var routing_table_raw_1 = __importDefault(routingTableRaw);
__exportStar(streamObservers, exports);
exports.BoltProtocol = bolt_protocol_v4x3_1.default;
exports.RawRoutingTable = routing_table_raw_1.default;
exports.default = {
    handshake: handshake_1.default,
    create: create_1.default
};
}(bolt));

var connectionProvider = {};

var connectionProviderSingle = {};

/**
 * 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$6 = (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 __());
    };
})();
Object.defineProperty(connectionProviderSingle, "__esModule", { value: true });
var neo4j_driver_core_1$8 = lib$1;
var SingleConnectionProvider = /** @class */ (function (_super) {
    __extends$6(SingleConnectionProvider, _super);
    function SingleConnectionProvider(connection) {
        var _this = _super.call(this) || this;
        _this._connection = connection;
        return _this;
    }
    /**
     * See {@link ConnectionProvider} for more information about this method and
     * its arguments.
     */
    SingleConnectionProvider.prototype.acquireConnection = function (_a) {
        var _b = _a === void 0 ? {} : _a; _b.accessMode; _b.database; _b.bookmarks;
        var connection = this._connection;
        this._connection = null;
        return Promise.resolve(connection);
    };
    return SingleConnectionProvider;
}(neo4j_driver_core_1$8.ConnectionProvider));
connectionProviderSingle.default = SingleConnectionProvider;

var connectionProviderPooled = {};

var connection$1 = {};

var connection = {};

var __extends$5 = (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 __());
    };
})();
Object.defineProperty(connection, "__esModule", { value: true });
var neo4j_driver_core_1$7 = lib$1;
var Connection = /** @class */ (function (_super) {
    __extends$5(Connection, _super);
    /**
     * @param {ConnectionErrorHandler} errorHandler the error handler
     */
    function Connection(errorHandler) {
        var _this = _super.call(this) || this;
        _this._errorHandler = errorHandler;
        return _this;
    }
    Object.defineProperty(Connection.prototype, "id", {
        get: function () {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "databaseId", {
        get: function () {
            throw new Error('not implemented');
        },
        set: function (value) {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "authToken", {
        get: function () {
            throw new Error('not implemented');
        },
        set: function (value) {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "supportsReAuth", {
        get: function () {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "creationTimestamp", {
        get: function () {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "idleTimestamp", {
        get: function () {
            throw new Error('not implemented');
        },
        set: function (value) {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    /**
     * @returns {BoltProtocol} the underlying bolt protocol assigned to this connection
     */
    Connection.prototype.protocol = function () {
        throw new Error('not implemented');
    };
    Object.defineProperty(Connection.prototype, "address", {
        /**
         * @returns {ServerAddress} the server address this connection is opened against
         */
        get: function () {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "version", {
        /**
         * @returns {ServerVersion} the version of the server this connection is connected to
         */
        get: function () {
            throw new Error('not implemented');
        },
        set: function (value) {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Connection.prototype, "server", {
        get: function () {
            throw new Error('not implemented');
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Connect to the target address, negotiate Bolt protocol and send initialization message.
     * @param {string} userAgent the user agent for this driver.
     * @param {Object} boltAgent the bolt agent for this driver.
     * @param {Object} authToken the object containing auth information.
     * @param {boolean} shouldWaitReAuth whether ot not the connection will wait for re-authentication to happen
     * @return {Promise<Connection>} promise resolved with the current connection if connection is successful. Rejected promise otherwise.
     */
    Connection.prototype.connect = function (userAgent, boltAgent, authToken, shouldWaitReAuth) {
        throw new Error('not implemented');
    };
    /**
     * Write a message to the network channel.
     * @param {RequestMessage} message the message to write.
     * @param {ResultStreamObserver} observer the response observer.
     * @param {boolean} flush `true` if flush should happen after the message is written to the buffer.
     */
    Connection.prototype.write = function (message, observer, flush) {
        throw new Error('not implemented');
    };
    /**
     * Call close on the channel.
     * @returns {Promise<void>} - A promise that will be resolved when the connection is closed.
     *
     */
    Connection.prototype.close = function () {
        throw new Error('not implemented');
    };
    /**
     *
     * @param error
     * @param address
     * @returns {Neo4jError|*}
     */
    Connection.prototype.handleAndTransformError = function (error, address) {
        if (this._errorHandler) {
            return this._errorHandler.handleAndTransformError(error, address, this);
        }
        return error;
    };
    return Connection;
}(neo4j_driver_core_1$7.Connection));
connection.default = Connection;

var connectionChannel = {};

/**
 * 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$4 = (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 __awaiter$6 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$6 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$6 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(connectionChannel, "__esModule", { value: true });
connectionChannel.createChannelConnection = createChannelConnection;
var channel_1$2 = channel;
var neo4j_driver_core_1$6 = lib$1;
var connection_1$4 = __importDefault$6(connection);
var bolt_1 = __importDefault$6(bolt);
var PROTOCOL_ERROR$1 = neo4j_driver_core_1$6.error.PROTOCOL_ERROR;
var Logger = neo4j_driver_core_1$6.internal.logger.Logger;
var idGenerator = 0;
/**
 * Crete new connection to the provided address. Returned connection is not connected.
 * @param {ServerAddress} address - the Bolt endpoint to connect to.
 * @param {Object} config - the driver configuration.
 * @param {ConnectionErrorHandler} errorHandler - the error handler for connection errors.
 * @param {Logger} log - configured logger.
 * @param {clientCertificate} clientCertificate - configured client certificate
 * @param ssrCallback - callback function used to update the counts of ssr enabled and disabled connections
 * @param createChannel - function taking a channelConfig object and creating a channel with it
 * @return {Connection} - new connection.
 */
function createChannelConnection(address, config, errorHandler, log, clientCertificate, serversideRouting, ssrCallback, createChannel) {
    if (serversideRouting === void 0) { serversideRouting = null; }
    if (createChannel === void 0) { createChannel = function (channelConfig) { return new channel_1$2.Channel(channelConfig); }; }
    var channelConfig = new channel_1$2.ChannelConfig(address, config, errorHandler.errorCode(), clientCertificate);
    var channel = createChannel(channelConfig);
    return bolt_1.default.handshake(channel, log)
        .then(function (_a) {
        var version = _a.protocolVersion, consumeRemainingBuffer = _a.consumeRemainingBuffer;
        var chunker = new channel_1$2.Chunker(channel);
        var dechunker = new channel_1$2.Dechunker();
        var createProtocol = function (conn) {
            return bolt_1.default.create({
                version: version,
                channel: channel,
                chunker: chunker,
                dechunker: dechunker,
                disableLosslessIntegers: config.disableLosslessIntegers,
                useBigInt: config.useBigInt,
                serversideRouting: serversideRouting,
                server: conn.server,
                log: conn.logger,
                observer: {
                    onObserversCountChange: conn._handleOngoingRequestsNumberChange.bind(conn),
                    onError: conn._handleFatalError.bind(conn),
                    onFailure: conn._resetOnFailure.bind(conn),
                    onProtocolError: conn._handleProtocolError.bind(conn),
                    onErrorApplyTransformation: function (error) {
                        return conn.handleAndTransformError(error, conn._address);
                    }
                }
            });
        };
        var connection = new ChannelConnection(channel, errorHandler, address, log, config.disableLosslessIntegers, serversideRouting, chunker, config.notificationFilter, createProtocol, config.telemetryDisabled, ssrCallback);
        // forward all pending bytes to the dechunker
        consumeRemainingBuffer(function (buffer) { return dechunker.write(buffer); });
        return connection;
    })
        .catch(function (reason) {
        return channel.close().then(function () {
            throw reason;
        });
    });
}
var ChannelConnection = /** @class */ (function (_super) {
    __extends$4(ChannelConnection, _super);
    /**
     * @constructor
     * @param {Channel} channel - channel with a 'write' function and a 'onmessage' callback property.
     * @param {ConnectionErrorHandler} errorHandler the error handler.
     * @param {ServerAddress} address - the server address to connect to.
     * @param {Logger} log - the configured logger.
     * @param {boolean} disableLosslessIntegers - if this connection should convert all received integers to native JS numbers.
     * @param {Chunker} chunker - the chunker
     * @param protocolSupplier - Bolt protocol supplier
     * @param {boolean} telemetryDisabled - wether telemetry has been disabled in driver config.
     * @param ssrCallback - callback function used to update the counts of ssr enabled and disabled connections.
     */
    function ChannelConnection(channel, errorHandler, address, log, disableLosslessIntegers, serversideRouting, chunker, // to be removed,
    notificationFilter, protocolSupplier, telemetryDisabled, ssrCallback) {
        if (disableLosslessIntegers === void 0) { disableLosslessIntegers = false; }
        if (serversideRouting === void 0) { serversideRouting = null; }
        if (ssrCallback === void 0) { ssrCallback = function (_) { }; }
        var _this = _super.call(this, errorHandler) || this;
        _this._authToken = null;
        _this._idle = false;
        _this._reseting = false;
        _this._resetObservers = [];
        _this._id = idGenerator++;
        _this._address = address;
        _this._server = { address: address.asHostPort() };
        _this._creationTimestamp = Date.now();
        _this._disableLosslessIntegers = disableLosslessIntegers;
        _this._ch = channel;
        _this._chunker = chunker;
        _this._log = createConnectionLogger(_this, log);
        _this._serversideRouting = serversideRouting;
        _this._notificationFilter = notificationFilter;
        _this._telemetryDisabledDriverConfig = telemetryDisabled === true;
        _this._telemetryDisabledConnection = true;
        _this._ssrCallback = ssrCallback;
        // connection from the database, returned in response for HELLO message and might not be available
        _this._dbConnectionId = null;
        // bolt protocol is initially not initialized
        /**
         * @private
         * @type {BoltProtocol}
         */
        _this._protocol = protocolSupplier(_this);
        // Set to true on fatal errors, to get this out of connection pool.
        _this._isBroken = false;
        if (_this._log.isDebugEnabled()) {
            _this._log.debug("created towards ".concat(address));
        }
        return _this;
    }
    ChannelConnection.prototype.beginTransaction = function (config) {
        this._sendTelemetryIfEnabled(config);
        return this._protocol.beginTransaction(config);
    };
    ChannelConnection.prototype.run = function (query, parameters, config) {
        this._sendTelemetryIfEnabled(config);
        return this._protocol.run(query, parameters, config);
    };
    ChannelConnection.prototype._sendTelemetryIfEnabled = function (config) {
        if (this._telemetryDisabledConnection ||
            this._telemetryDisabledDriverConfig ||
            config == null ||
            config.apiTelemetryConfig == null) {
            return;
        }
        this._protocol.telemetry({
            api: config.apiTelemetryConfig.api
        }, {
            onCompleted: config.apiTelemetryConfig.onTelemetrySuccess,
            onError: config.beforeError
        });
    };
    ChannelConnection.prototype.commitTransaction = function (config) {
        return this._protocol.commitTransaction(config);
    };
    ChannelConnection.prototype.rollbackTransaction = function (config) {
        return this._protocol.rollbackTransaction(config);
    };
    ChannelConnection.prototype.getProtocolVersion = function () {
        return this._protocol.version;
    };
    Object.defineProperty(ChannelConnection.prototype, "authToken", {
        get: function () {
            return this._authToken;
        },
        set: function (value) {
            this._authToken = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "supportsReAuth", {
        get: function () {
            return this._protocol.supportsReAuth;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "id", {
        get: function () {
            return this._id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "databaseId", {
        get: function () {
            return this._dbConnectionId;
        },
        set: function (value) {
            this._dbConnectionId = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "idleTimestamp", {
        get: function () {
            return this._idleTimestamp;
        },
        set: function (value) {
            this._idleTimestamp = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "creationTimestamp", {
        get: function () {
            return this._creationTimestamp;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Send initialization message.
     * @param {string} userAgent the user agent for this driver.
     * @param {Object} boltAgent the bolt agent for this driver.
     * @param {Object} authToken the object containing auth information.
     * @param {boolean} waitReAuth whether ot not the connection will wait for re-authentication to happen
     * @return {Promise<Connection>} promise resolved with the current connection if connection is successful. Rejected promise otherwise.
     */
    ChannelConnection.prototype.connect = function (userAgent, boltAgent, authToken, waitReAuth) {
        return __awaiter$6(this, void 0, void 0, function () {
            var _this = this;
            return __generator$6(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this._protocol.initialized && !this._protocol.supportsReAuth) {
                            throw (0, neo4j_driver_core_1$6.newError)('Connection does not support re-auth');
                        }
                        this._authToken = authToken;
                        if (!!this._protocol.initialized) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._initialize(userAgent, boltAgent, authToken)];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2:
                        if (!waitReAuth) return [3 /*break*/, 4];
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                _this._protocol.logoff({
                                    onError: reject
                                });
                                _this._protocol.logon({
                                    authToken: authToken,
                                    onError: reject,
                                    onComplete: function () { return resolve(_this); },
                                    flush: true
                                });
                            })];
                    case 3: return [2 /*return*/, _a.sent()];
                    case 4:
                        this._protocol.logoff();
                        this._protocol.logon({ authToken: authToken, flush: true });
                        return [2 /*return*/, this];
                }
            });
        });
    };
    /**
     * Perform protocol-specific initialization which includes authentication.
     * @param {string} userAgent the user agent for this driver.
     * @param {string} boltAgent the bolt agent for this driver.
     * @param {Object} authToken the object containing auth information.
     * @return {Promise<Connection>} promise resolved with the current connection if initialization is successful. Rejected promise otherwise.
     */
    ChannelConnection.prototype._initialize = function (userAgent, boltAgent, authToken) {
        var _this = this;
        var self = this;
        return new Promise(function (resolve, reject) {
            _this._protocol.initialize({
                userAgent: userAgent,
                boltAgent: boltAgent,
                authToken: authToken,
                notificationFilter: _this._notificationFilter,
                onError: function (err) { return reject(err); },
                onComplete: function (metadata) {
                    var _a;
                    if (metadata) {
                        // read server version from the response metadata, if it is available
                        var serverVersion = metadata.server;
                        if (!_this.version || serverVersion) {
                            _this.version = serverVersion;
                        }
                        // read database connection id from the response metadata, if it is available
                        var dbConnectionId = metadata.connection_id;
                        if (!_this.databaseId) {
                            _this.databaseId = dbConnectionId;
                        }
                        if (metadata.hints) {
                            var receiveTimeoutRaw = metadata.hints['connection.recv_timeout_seconds'];
                            if (receiveTimeoutRaw !== null &&
                                receiveTimeoutRaw !== undefined) {
                                var receiveTimeoutInSeconds = (0, neo4j_driver_core_1$6.toNumber)(receiveTimeoutRaw);
                                if (Number.isInteger(receiveTimeoutInSeconds) &&
                                    receiveTimeoutInSeconds > 0) {
                                    _this._ch.setupReceiveTimeout(receiveTimeoutInSeconds * 1000);
                                }
                                else {
                                    _this._log.info("Server located at ".concat(_this._address, " supplied an invalid connection receive timeout value (").concat(receiveTimeoutInSeconds, "). ") +
                                        'Please, verify the server configuration and status because this can be the symptom of a bigger issue.');
                                }
                            }
                            var telemetryEnabledHint = metadata.hints['telemetry.enabled'];
                            if (telemetryEnabledHint === true) {
                                _this._telemetryDisabledConnection = false;
                            }
                            _this.SSREnabledHint = metadata.hints['ssr.enabled'];
                        }
                        _this._ssrCallback((_a = _this.SSREnabledHint) !== null && _a !== void 0 ? _a : false, 'OPEN');
                    }
                    resolve(self);
                }
            });
        });
    };
    /**
     * Get the Bolt protocol for the connection.
     * @return {BoltProtocol} the protocol.
     */
    ChannelConnection.prototype.protocol = function () {
        return this._protocol;
    };
    Object.defineProperty(ChannelConnection.prototype, "address", {
        get: function () {
            return this._address;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "version", {
        /**
         * Get the version of the connected server.
         * Available only after initialization
         *
         * @returns {ServerVersion} version
         */
        get: function () {
            return this._server.version;
        },
        set: function (value) {
            this._server.version = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "server", {
        get: function () {
            return this._server;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ChannelConnection.prototype, "logger", {
        get: function () {
            return this._log;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * "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 error an error object, forwarded to all current and future subscribers
     */
    ChannelConnection.prototype._handleFatalError = function (error) {
        this._isBroken = true;
        this._error = this.handleAndTransformError(this._protocol.currentFailure || error, this._address);
        if (this._log.isErrorEnabled()) {
            this._log.error("experienced a fatal error caused by ".concat(this._error, " (").concat(neo4j_driver_core_1$6.json.stringify(this._error), ")"));
        }
        this._protocol.notifyFatalError(this._error);
    };
    /**
     * This method is used by the {@link PooledConnectionProvider}
     *
     * @param {any} observer
     */
    ChannelConnection.prototype._setIdle = function (observer) {
        this._idle = true;
        this._ch.stopReceiveTimeout();
        this._protocol.queueObserverIfProtocolIsNotBroken(observer);
    };
    /**
     * This method is used by the {@link PooledConnectionProvider}
     */
    ChannelConnection.prototype._unsetIdle = function () {
        this._idle = false;
        this._updateCurrentObserver();
    };
    /**
     * This method still here because of the connection-channel.tests.js
     *
     * @param {any} observer
     */
    ChannelConnection.prototype._queueObserver = function (observer) {
        return this._protocol.queueObserverIfProtocolIsNotBroken(observer);
    };
    ChannelConnection.prototype.hasOngoingObservableRequests = function () {
        return !this._idle && this._protocol.hasOngoingObservableRequests();
    };
    /**
     * Send a RESET-message to the database. Message is immediately flushed to the network.
     * @return {Promise<void>} promise resolved when SUCCESS-message response arrives, or failed when other response messages arrives.
     */
    ChannelConnection.prototype.resetAndFlush = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this._reset({
                onError: function (error) {
                    if (_this._isBroken) {
                        // handling a fatal error, no need to raise a protocol violation
                        reject(error);
                    }
                    else {
                        var neo4jError = _this._handleProtocolError("Received FAILURE as a response for RESET: ".concat(error));
                        reject(neo4jError);
                    }
                },
                onComplete: function () {
                    resolve();
                }
            });
        });
    };
    ChannelConnection.prototype._resetOnFailure = function () {
        var _this = this;
        if (!this.isOpen()) {
            return;
        }
        this._reset({
            onError: function () {
                _this._protocol.resetFailure();
            },
            onComplete: function () {
                _this._protocol.resetFailure();
            }
        });
    };
    ChannelConnection.prototype._reset = function (observer) {
        var _this = this;
        if (this._reseting) {
            if (!this._protocol.isLastMessageReset()) {
                this._protocol.reset({
                    onError: function (error) {
                        observer.onError(error);
                    },
                    onComplete: function () {
                        observer.onComplete();
                    }
                });
            }
            else {
                this._resetObservers.push(observer);
            }
            return;
        }
        this._resetObservers.push(observer);
        this._reseting = true;
        var notifyFinish = function (notify) {
            _this._reseting = false;
            var observers = _this._resetObservers;
            _this._resetObservers = [];
            observers.forEach(notify);
        };
        this._protocol.reset({
            onError: function (error) {
                notifyFinish(function (obs) { return obs.onError(error); });
            },
            onComplete: function () {
                notifyFinish(function (obs) { return obs.onComplete(); });
            }
        });
    };
    /*
     * Pop next pending observer form the list of observers and make it current observer.
     * @protected
     */
    ChannelConnection.prototype._updateCurrentObserver = function () {
        this._protocol.updateCurrentObserver();
    };
    /** Check if this connection is in working condition */
    ChannelConnection.prototype.isOpen = function () {
        return !this._isBroken && this._ch._open;
    };
    /**
     * Starts and stops the receive timeout timer.
     * @param {number} requestsNumber Ongoing requests number
     */
    ChannelConnection.prototype._handleOngoingRequestsNumberChange = function (requestsNumber) {
        if (this._idle) {
            return;
        }
        if (requestsNumber === 0) {
            this._ch.stopReceiveTimeout();
        }
        else {
            this._ch.startReceiveTimeout();
        }
    };
    /**
     * Call close on the channel.
     * @returns {Promise<void>} - A promise that will be resolved when the underlying channel is closed.
     */
    ChannelConnection.prototype.close = function () {
        return __awaiter$6(this, void 0, void 0, function () {
            var _a;
            return __generator$6(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this._ssrCallback((_a = this.SSREnabledHint) !== null && _a !== void 0 ? _a : false, 'CLOSE');
                        if (this._log.isDebugEnabled()) {
                            this._log.debug('closing');
                        }
                        if (this._protocol && this.isOpen()) {
                            // protocol has been initialized and this connection is healthy
                            // notify the database about the upcoming close of the connection
                            this._protocol.prepareToClose();
                        }
                        return [4 /*yield*/, this._ch.close()];
                    case 1:
                        _b.sent();
                        if (this._log.isDebugEnabled()) {
                            this._log.debug('closed');
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    ChannelConnection.prototype.toString = function () {
        return "Connection [".concat(this.id, "][").concat(this.databaseId || '', "]");
    };
    ChannelConnection.prototype._handleProtocolError = function (message) {
        this._protocol.resetFailure();
        this._updateCurrentObserver();
        var error = (0, neo4j_driver_core_1$6.newError)(message, PROTOCOL_ERROR$1);
        this._handleFatalError(error);
        return error;
    };
    return ChannelConnection;
}(connection_1$4.default));
connectionChannel.default = ChannelConnection;
/**
 * Creates a log with the connection info as prefix
 * @param {Connection} connection The connection
 * @param {Logger} logger The logger
 * @returns {Logger} The new logger with enriched messages
 */
function createConnectionLogger(connection, logger) {
    return new Logger(logger._level, function (level, message) {
        return logger._loggerFunction(level, "".concat(connection, " ").concat(message));
    });
}

var connectionDelegate = {};

/**
 * 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$3 = (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 __importDefault$5 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(connectionDelegate, "__esModule", { value: true });
var connection_1$3 = __importDefault$5(connection);
var DelegateConnection = /** @class */ (function (_super) {
    __extends$3(DelegateConnection, _super);
    /**
     * @param delegate {Connection} the delegated connection
     * @param errorHandler {ConnectionErrorHandler} the error handler
     */
    function DelegateConnection(delegate, errorHandler) {
        var _this = _super.call(this, errorHandler) || this;
        if (errorHandler) {
            _this._originalErrorHandler = delegate._errorHandler;
            delegate._errorHandler = _this._errorHandler;
        }
        _this._delegate = delegate;
        return _this;
    }
    DelegateConnection.prototype.beginTransaction = function (config) {
        return this._delegate.beginTransaction(config);
    };
    DelegateConnection.prototype.run = function (query, param, config) {
        return this._delegate.run(query, param, config);
    };
    DelegateConnection.prototype.commitTransaction = function (config) {
        return this._delegate.commitTransaction(config);
    };
    DelegateConnection.prototype.rollbackTransaction = function (config) {
        return this._delegate.rollbackTransaction(config);
    };
    DelegateConnection.prototype.getProtocolVersion = function () {
        return this._delegate.getProtocolVersion();
    };
    Object.defineProperty(DelegateConnection.prototype, "id", {
        get: function () {
            return this._delegate.id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "databaseId", {
        get: function () {
            return this._delegate.databaseId;
        },
        set: function (value) {
            this._delegate.databaseId = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "server", {
        get: function () {
            return this._delegate.server;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "authToken", {
        get: function () {
            return this._delegate.authToken;
        },
        set: function (value) {
            this._delegate.authToken = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "supportsReAuth", {
        get: function () {
            return this._delegate.supportsReAuth;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "address", {
        get: function () {
            return this._delegate.address;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "version", {
        get: function () {
            return this._delegate.version;
        },
        set: function (value) {
            this._delegate.version = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "creationTimestamp", {
        get: function () {
            return this._delegate.creationTimestamp;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DelegateConnection.prototype, "idleTimestamp", {
        get: function () {
            return this._delegate.idleTimestamp;
        },
        set: function (value) {
            this._delegate.idleTimestamp = value;
        },
        enumerable: false,
        configurable: true
    });
    DelegateConnection.prototype.isOpen = function () {
        return this._delegate.isOpen();
    };
    DelegateConnection.prototype.protocol = function () {
        return this._delegate.protocol();
    };
    DelegateConnection.prototype.connect = function (userAgent, boltAgent, authToken, waitReAuth) {
        return this._delegate.connect(userAgent, boltAgent, authToken, waitReAuth);
    };
    DelegateConnection.prototype.write = function (message, observer, flush) {
        return this._delegate.write(message, observer, flush);
    };
    DelegateConnection.prototype.resetAndFlush = function () {
        return this._delegate.resetAndFlush();
    };
    DelegateConnection.prototype.hasOngoingObservableRequests = function () {
        return this._delegate.hasOngoingObservableRequests();
    };
    DelegateConnection.prototype.close = function () {
        return this._delegate.close();
    };
    DelegateConnection.prototype.release = function () {
        if (this._originalErrorHandler) {
            this._delegate._errorHandler = this._originalErrorHandler;
        }
        return this._delegate.release();
    };
    return DelegateConnection;
}(connection_1$3.default));
connectionDelegate.default = DelegateConnection;

var connectionErrorHandler = {};

/**
 * 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(connectionErrorHandler, "__esModule", { value: true });
var neo4j_driver_core_1$5 = lib$1;
var SERVICE_UNAVAILABLE$3 = neo4j_driver_core_1$5.error.SERVICE_UNAVAILABLE, SESSION_EXPIRED$1 = neo4j_driver_core_1$5.error.SESSION_EXPIRED;
var ConnectionErrorHandler = /** @class */ (function () {
    function ConnectionErrorHandler(errorCode, handleUnavailability, handleWriteFailure, handleSecurityError) {
        this._errorCode = errorCode;
        this._handleUnavailability = handleUnavailability || noOpHandler;
        this._handleWriteFailure = handleWriteFailure || noOpHandler;
        this._handleSecurityError = handleSecurityError || noOpHandler;
    }
    ConnectionErrorHandler.create = function (_a) {
        var errorCode = _a.errorCode, handleUnavailability = _a.handleUnavailability, handleWriteFailure = _a.handleWriteFailure, handleSecurityError = _a.handleSecurityError;
        return new ConnectionErrorHandler(errorCode, handleUnavailability, handleWriteFailure, handleSecurityError);
    };
    /**
     * Error code to use for network errors.
     * @return {string} the error code.
     */
    ConnectionErrorHandler.prototype.errorCode = function () {
        return this._errorCode;
    };
    /**
     * Handle and transform the error.
     * @param {Neo4jError} error the original error.
     * @param {ServerAddress} address the address of the connection where the error happened.
     * @return {Neo4jError} new error that should be propagated to the user.
     */
    ConnectionErrorHandler.prototype.handleAndTransformError = function (error, address, connection) {
        if (isSecurityError(error)) {
            return this._handleSecurityError(error, address, connection);
        }
        if (isAvailabilityError(error)) {
            return this._handleUnavailability(error, address, connection);
        }
        if (isFailureToWrite(error)) {
            return this._handleWriteFailure(error, address, connection);
        }
        return error;
    };
    return ConnectionErrorHandler;
}());
connectionErrorHandler.default = ConnectionErrorHandler;
function isSecurityError(error) {
    return error != null &&
        error.code != null &&
        error.code.startsWith('Neo.ClientError.Security.');
}
function isAvailabilityError(error) {
    if (error) {
        return (error.code === SESSION_EXPIRED$1 ||
            error.code === SERVICE_UNAVAILABLE$3 ||
            error.code === 'Neo.TransientError.General.DatabaseUnavailable');
    }
    return false;
}
function isFailureToWrite(error) {
    if (error) {
        return (error.code === 'Neo.ClientError.Cluster.NotALeader' ||
            error.code === 'Neo.ClientError.General.ForbiddenOnReadOnlyDatabase');
    }
    return false;
}
function noOpHandler(error) {
    return error;
}

(function (exports) {
/**
 * 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 __createBinding = (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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createChannelConnection = exports.ConnectionErrorHandler = exports.DelegateConnection = exports.ChannelConnection = exports.Connection = void 0;
var connection_1 = __importDefault(connection);
exports.Connection = connection_1.default;
var connection_channel_1 = __importStar(connectionChannel);
exports.ChannelConnection = connection_channel_1.default;
Object.defineProperty(exports, "createChannelConnection", { enumerable: true, get: function () { return connection_channel_1.createChannelConnection; } });
var connection_delegate_1 = __importDefault(connectionDelegate);
exports.DelegateConnection = connection_delegate_1.default;
var connection_error_handler_1 = __importDefault(connectionErrorHandler);
exports.ConnectionErrorHandler = connection_error_handler_1.default;
exports.default = connection_1.default;
}(connection$1));

var authenticationProvider = {};

/**
 * 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 __awaiter$5 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$5 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(authenticationProvider, "__esModule", { value: true });
var neo4j_driver_core_1$4 = lib$1;
var lang_1$2 = lang;
/**
 * Class which provides Authorization for {@link Connection}
 */
var AuthenticationProvider = /** @class */ (function () {
    function AuthenticationProvider(_a) {
        var authTokenManager = _a.authTokenManager, userAgent = _a.userAgent, boltAgent = _a.boltAgent;
        this._authTokenManager = authTokenManager || (0, neo4j_driver_core_1$4.staticAuthTokenManager)({});
        this._userAgent = userAgent;
        this._boltAgent = boltAgent;
    }
    AuthenticationProvider.prototype.authenticate = function (_a) {
        return __awaiter$5(this, arguments, void 0, function (_b) {
            var shouldReAuth, authToken;
            var connection = _b.connection, auth = _b.auth, skipReAuth = _b.skipReAuth, waitReAuth = _b.waitReAuth, forceReAuth = _b.forceReAuth;
            return __generator$5(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!(auth != null)) return [3 /*break*/, 3];
                        shouldReAuth = connection.supportsReAuth === true && ((!lang_1$2.object.equals(connection.authToken, auth) && skipReAuth !== true) ||
                            forceReAuth === true);
                        if (!(connection.authToken == null || shouldReAuth)) return [3 /*break*/, 2];
                        return [4 /*yield*/, connection.connect(this._userAgent, this._boltAgent, auth, waitReAuth || false)];
                    case 1: return [2 /*return*/, _c.sent()];
                    case 2: return [2 /*return*/, connection];
                    case 3: return [4 /*yield*/, this._authTokenManager.getToken()];
                    case 4:
                        authToken = _c.sent();
                        if (!!lang_1$2.object.equals(authToken, connection.authToken)) return [3 /*break*/, 6];
                        return [4 /*yield*/, connection.connect(this._userAgent, this._boltAgent, authToken, false)];
                    case 5: return [2 /*return*/, _c.sent()];
                    case 6: return [2 /*return*/, connection];
                }
            });
        });
    };
    AuthenticationProvider.prototype.handleError = function (_a) {
        var connection = _a.connection, code = _a.code;
        if (connection &&
            code.startsWith('Neo.ClientError.Security.')) {
            return this._authTokenManager.handleSecurityException(connection.authToken, code);
        }
        return false;
    };
    return AuthenticationProvider;
}());
authenticationProvider.default = AuthenticationProvider;

var livenessCheckProvider = {};

var __awaiter$4 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$4 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(livenessCheckProvider, "__esModule", { value: true });
/**
 * 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 LivenessCheckProvider = /** @class */ (function () {
    function LivenessCheckProvider(_a) {
        var connectionLivenessCheckTimeout = _a.connectionLivenessCheckTimeout;
        this._connectionLivenessCheckTimeout = connectionLivenessCheckTimeout;
    }
    /**
     * Checks connection liveness with configured params.
     *
     * @param {Connection} connection
     * @returns {Promise<true>} If liveness checks succeed, throws otherwise
     */
    LivenessCheckProvider.prototype.check = function (connection) {
        return __awaiter$4(this, void 0, void 0, function () {
            var idleFor;
            return __generator$4(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this._isCheckDisabled || this._isNewlyCreatedConnection(connection)) {
                            return [2 /*return*/, true];
                        }
                        idleFor = Date.now() - connection.idleTimestamp;
                        if (!(this._connectionLivenessCheckTimeout === 0 ||
                            idleFor > this._connectionLivenessCheckTimeout)) return [3 /*break*/, 2];
                        return [4 /*yield*/, connection.resetAndFlush()
                                .then(function () { return true; })];
                    case 1: return [2 /*return*/, _a.sent()];
                    case 2: return [2 /*return*/, true];
                }
            });
        });
    };
    Object.defineProperty(LivenessCheckProvider.prototype, "_isCheckDisabled", {
        get: function () {
            return this._connectionLivenessCheckTimeout == null || this._connectionLivenessCheckTimeout < 0;
        },
        enumerable: false,
        configurable: true
    });
    LivenessCheckProvider.prototype._isNewlyCreatedConnection = function (connection) {
        return connection.authToken == null;
    };
    return LivenessCheckProvider;
}());
livenessCheckProvider.default = LivenessCheckProvider;

var clientCertificateHolder = {};

var __awaiter$3 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$3 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(clientCertificateHolder, "__esModule", { value: true });
/**
 * 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 channel_1$1 = channel;
var ClientCertificateHolder = /** @class */ (function () {
    function ClientCertificateHolder(_a) {
        var clientCertificateProvider = _a.clientCertificateProvider, loader = _a.loader;
        this._clientCertificateProvider = clientCertificateProvider;
        this._loader = loader || channel_1$1.ClientCertificatesLoader;
        this._clientCertificate = null;
    }
    ClientCertificateHolder.prototype.getClientCertificate = function () {
        return __awaiter$3(this, void 0, void 0, function () {
            var _a, _b;
            var _this = this;
            return __generator$3(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = this._clientCertificateProvider != null;
                        if (!_a) return [3 /*break*/, 3];
                        _b = this._clientCertificate == null;
                        if (_b) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._clientCertificateProvider.hasUpdate()];
                    case 1:
                        _b = (_c.sent());
                        _c.label = 2;
                    case 2:
                        _a = (_b);
                        _c.label = 3;
                    case 3:
                        if (_a) {
                            this._clientCertificate = Promise.resolve(this._clientCertificateProvider.getClientCertificate())
                                .then(this._loader.load)
                                .then(function (clientCertificate) {
                                _this._clientCertificate = clientCertificate;
                                return _this._clientCertificate;
                            })
                                .catch(function (error) {
                                _this._clientCertificate = null;
                                throw error;
                            });
                        }
                        return [2 /*return*/, this._clientCertificate];
                }
            });
        });
    };
    return ClientCertificateHolder;
}());
clientCertificateHolder.default = ClientCertificateHolder;

/**
 * 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$2 = (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 __awaiter$2 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$2 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read$2 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray$1 = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault$4 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(connectionProviderPooled, "__esModule", { value: true });
var connection_1$2 = connection$1;
var neo4j_driver_core_1$3 = lib$1;
var authentication_provider_1 = __importDefault$4(authenticationProvider);
var lang_1$1 = lang;
var liveness_check_provider_1 = __importDefault$4(livenessCheckProvider);
var client_certificate_holder_1 = __importDefault$4(clientCertificateHolder);
var SERVICE_UNAVAILABLE$2 = neo4j_driver_core_1$3.error.SERVICE_UNAVAILABLE;
var AUTHENTICATION_ERRORS = [
    'Neo.ClientError.Security.CredentialsExpired',
    'Neo.ClientError.Security.Forbidden',
    'Neo.ClientError.Security.TokenExpired',
    'Neo.ClientError.Security.Unauthorized'
];
var _a$3 = neo4j_driver_core_1$3.internal.pool, Pool = _a$3.Pool, PoolConfig = _a$3.PoolConfig;
var PooledConnectionProvider = /** @class */ (function (_super) {
    __extends$2(PooledConnectionProvider, _super);
    function PooledConnectionProvider(_a, createChannelConnectionHook) {
        var id = _a.id, config = _a.config, log = _a.log, userAgent = _a.userAgent, boltAgent = _a.boltAgent, authTokenManager = _a.authTokenManager, _b = _a.newPool, newPool = _b === void 0 ? function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return new (Pool.bind.apply(Pool, __spreadArray$1([void 0], __read$2(args), false)))();
        } : _b;
        if (createChannelConnectionHook === void 0) { createChannelConnectionHook = null; }
        var _this = _super.call(this) || this;
        _this._id = id;
        _this._config = config;
        _this._log = log;
        _this._clientCertificateHolder = new client_certificate_holder_1.default({ clientCertificateProvider: _this._config.clientCertificate });
        _this._authenticationProvider = new authentication_provider_1.default({ authTokenManager: authTokenManager, userAgent: userAgent, boltAgent: boltAgent });
        _this._livenessCheckProvider = new liveness_check_provider_1.default({ connectionLivenessCheckTimeout: config.connectionLivenessCheckTimeout });
        _this._userAgent = userAgent;
        _this._boltAgent = boltAgent;
        _this._createChannelConnection =
            createChannelConnectionHook ||
                (function (address) { return __awaiter$2(_this, void 0, void 0, function () {
                    var _a, _b;
                    return __generator$2(this, function (_c) {
                        switch (_c.label) {
                            case 0:
                                _a = connection_1$2.createChannelConnection;
                                _b = [address,
                                    this._config,
                                    this._createConnectionErrorHandler(),
                                    this._log];
                                return [4 /*yield*/, this._clientCertificateHolder.getClientCertificate()];
                            case 1: return [2 /*return*/, _a.apply(void 0, _b.concat([_c.sent()]))];
                        }
                    });
                }); });
        _this._connectionPool = newPool({
            create: _this._createConnection.bind(_this),
            destroy: _this._destroyConnection.bind(_this),
            validateOnAcquire: _this._validateConnectionOnAcquire.bind(_this),
            validateOnRelease: _this._validateConnectionOnRelease.bind(_this),
            installIdleObserver: PooledConnectionProvider._installIdleObserverOnConnection.bind(_this),
            removeIdleObserver: PooledConnectionProvider._removeIdleObserverOnConnection.bind(_this),
            config: PoolConfig.fromDriverConfig(config),
            log: _this._log
        });
        _this._openConnections = {};
        return _this;
    }
    PooledConnectionProvider.prototype._createConnectionErrorHandler = function () {
        return new connection_1$2.ConnectionErrorHandler(SERVICE_UNAVAILABLE$2);
    };
    PooledConnectionProvider.prototype._getClientCertificate = function () {
        return __awaiter$2(this, void 0, void 0, function () {
            return __generator$2(this, function (_a) {
                return [2 /*return*/, this._config.clientCertificate.getClientCertificate()];
            });
        });
    };
    /**
     * Create a new connection and initialize it.
     * @return {Promise<Connection>} promise resolved with a new connection or rejected when failed to connect.
     * @access private
     */
    PooledConnectionProvider.prototype._createConnection = function (_a, address, release) {
        var _this = this;
        var auth = _a.auth;
        return this._createChannelConnection(address).then(function (connection) {
            connection.release = function () {
                connection.idleTimestamp = Date.now();
                return release(address, connection);
            };
            _this._openConnections[connection.id] = connection;
            return _this._authenticationProvider.authenticate({ connection: connection, auth: auth })
                .catch(function (error) {
                // let's destroy this connection
                _this._destroyConnection(connection);
                // propagate the error because connection failed to connect / initialize
                throw error;
            });
        });
    };
    PooledConnectionProvider.prototype._validateConnectionOnAcquire = function (_a, conn_1) {
        return __awaiter$2(this, arguments, void 0, function (_b, conn) {
            var error_1, error_2;
            var auth = _b.auth, skipReAuth = _b.skipReAuth;
            return __generator$2(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!this._validateConnection(conn)) {
                            return [2 /*return*/, false];
                        }
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this._livenessCheckProvider.check(conn)];
                    case 2:
                        _c.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _c.sent();
                        this._log.debug("The connection ".concat(conn.id, " is not alive because of an error ").concat(error_1.code, " '").concat(error_1.message, "'"));
                        return [2 /*return*/, false];
                    case 4:
                        _c.trys.push([4, 6, , 7]);
                        return [4 /*yield*/, this._authenticationProvider.authenticate({ connection: conn, auth: auth, skipReAuth: skipReAuth })];
                    case 5:
                        _c.sent();
                        return [2 /*return*/, true];
                    case 6:
                        error_2 = _c.sent();
                        this._log.debug("The connection ".concat(conn.id, " is not valid because of an error ").concat(error_2.code, " '").concat(error_2.message, "'"));
                        return [2 /*return*/, false];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    PooledConnectionProvider.prototype._validateConnectionOnRelease = function (conn) {
        return conn._sticky !== true && this._validateConnection(conn);
    };
    /**
     * Check that a connection is usable
     * @return {boolean} true if the connection is open
     * @access private
     **/
    PooledConnectionProvider.prototype._validateConnection = function (conn) {
        if (!conn.isOpen()) {
            return false;
        }
        var maxConnectionLifetime = this._config.maxConnectionLifetime;
        var lifetime = Date.now() - conn.creationTimestamp;
        if (lifetime > maxConnectionLifetime) {
            return false;
        }
        return true;
    };
    /**
     * Dispose of a connection.
     * @return {Connection} the connection to dispose.
     * @access private
     */
    PooledConnectionProvider.prototype._destroyConnection = function (conn) {
        delete this._openConnections[conn.id];
        return conn.close();
    };
    /**
     * Acquire a connection from the pool and return it ServerInfo
     * @param {object} param
     * @param {string} param.address the server address
     * @return {Promise<ServerInfo>} the server info
     */
    PooledConnectionProvider.prototype._verifyConnectivityAndGetServerVersion = function (_a) {
        return __awaiter$2(this, arguments, void 0, function (_b) {
            var connection, serverInfo;
            var address = _b.address;
            return __generator$2(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this._connectionPool.acquire({}, address)];
                    case 1:
                        connection = _c.sent();
                        serverInfo = new neo4j_driver_core_1$3.ServerInfo(connection.server, connection.protocol().version);
                        _c.label = 2;
                    case 2:
                        _c.trys.push([2, , 5, 7]);
                        if (!!connection.protocol().isLastMessageLogon()) return [3 /*break*/, 4];
                        return [4 /*yield*/, connection.resetAndFlush()];
                    case 3:
                        _c.sent();
                        _c.label = 4;
                    case 4: return [3 /*break*/, 7];
                    case 5: return [4 /*yield*/, connection.release()];
                    case 6:
                        _c.sent();
                        return [7 /*endfinally*/];
                    case 7: return [2 /*return*/, serverInfo];
                }
            });
        });
    };
    PooledConnectionProvider.prototype._verifyAuthentication = function (_a) {
        return __awaiter$2(this, arguments, void 0, function (_b) {
            var connectionsToRelease, address, connection, lastMessageIsNotLogin, stickyConnection, error_3;
            var getAddress = _b.getAddress, auth = _b.auth;
            return __generator$2(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        connectionsToRelease = [];
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 8, 9, 11]);
                        return [4 /*yield*/, getAddress()];
                    case 2:
                        address = _c.sent();
                        return [4 /*yield*/, this._connectionPool.acquire({ auth: auth, skipReAuth: true }, address)];
                    case 3:
                        connection = _c.sent();
                        connectionsToRelease.push(connection);
                        lastMessageIsNotLogin = !connection.protocol().isLastMessageLogon();
                        if (!connection.supportsReAuth) {
                            throw (0, neo4j_driver_core_1$3.newError)('Driver is connected to a database that does not support user switch.');
                        }
                        if (!(lastMessageIsNotLogin && connection.supportsReAuth)) return [3 /*break*/, 5];
                        return [4 /*yield*/, this._authenticationProvider.authenticate({ connection: connection, auth: auth, waitReAuth: true, forceReAuth: true })];
                    case 4:
                        _c.sent();
                        return [3 /*break*/, 7];
                    case 5:
                        if (!(lastMessageIsNotLogin && !connection.supportsReAuth)) return [3 /*break*/, 7];
                        return [4 /*yield*/, this._connectionPool.acquire({ auth: auth }, address, { requireNew: true })];
                    case 6:
                        stickyConnection = _c.sent();
                        stickyConnection._sticky = true;
                        connectionsToRelease.push(stickyConnection);
                        _c.label = 7;
                    case 7: return [2 /*return*/, true];
                    case 8:
                        error_3 = _c.sent();
                        if (AUTHENTICATION_ERRORS.includes(error_3.code)) {
                            return [2 /*return*/, false];
                        }
                        throw error_3;
                    case 9: return [4 /*yield*/, Promise.all(connectionsToRelease.map(function (conn) { return conn.release(); }))];
                    case 10:
                        _c.sent();
                        return [7 /*endfinally*/];
                    case 11: return [2 /*return*/];
                }
            });
        });
    };
    PooledConnectionProvider.prototype._verifyStickyConnection = function (_a) {
        return __awaiter$2(this, arguments, void 0, function (_b) {
            var connectionWithSameCredentials, shouldCreateStickyConnection;
            var auth = _b.auth, connection = _b.connection; _b.address;
            return __generator$2(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        connectionWithSameCredentials = lang_1$1.object.equals(auth, connection.authToken);
                        shouldCreateStickyConnection = !connectionWithSameCredentials;
                        connection._sticky = connectionWithSameCredentials && !connection.supportsReAuth;
                        if (!(shouldCreateStickyConnection || connection._sticky)) return [3 /*break*/, 2];
                        return [4 /*yield*/, connection.release()];
                    case 1:
                        _c.sent();
                        throw (0, neo4j_driver_core_1$3.newError)('Driver is connected to a database that does not support user switch.');
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    PooledConnectionProvider.prototype.close = function () {
        return __awaiter$2(this, void 0, void 0, function () {
            return __generator$2(this, function (_a) {
                switch (_a.label) {
                    case 0: 
                    // purge all idle connections in the connection pool
                    return [4 /*yield*/, this._connectionPool.close()
                        // then close all connections driver has ever created
                        // it is needed to close connections that are active right now and are acquired from the pool
                    ];
                    case 1:
                        // purge all idle connections in the connection pool
                        _a.sent();
                        // then close all connections driver has ever created
                        // it is needed to close connections that are active right now and are acquired from the pool
                        return [4 /*yield*/, Promise.all(Object.values(this._openConnections).map(function (c) { return c.close(); }))];
                    case 2:
                        // then close all connections driver has ever created
                        // it is needed to close connections that are active right now and are acquired from the pool
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    PooledConnectionProvider._installIdleObserverOnConnection = function (conn, observer) {
        conn._setIdle(observer);
    };
    PooledConnectionProvider._removeIdleObserverOnConnection = function (conn) {
        conn._unsetIdle();
    };
    PooledConnectionProvider.prototype._handleSecurityError = function (error, address, connection) {
        var handled = this._authenticationProvider.handleError({ connection: connection, code: error.code });
        if (handled) {
            error.retriable = true;
        }
        if (error.code === 'Neo.ClientError.Security.AuthorizationExpired') {
            this._connectionPool.apply(address, function (conn) { conn.authToken = null; });
        }
        if (connection) {
            connection.close().catch(function () { return undefined; });
        }
        return error;
    };
    return PooledConnectionProvider;
}(neo4j_driver_core_1$3.ConnectionProvider));
connectionProviderPooled.default = PooledConnectionProvider;

var connectionProviderDirect = {};

/**
 * 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$1 = (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 __awaiter$1 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator$1 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault$3 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(connectionProviderDirect, "__esModule", { value: true });
var connection_provider_pooled_1$1 = __importDefault$3(connectionProviderPooled);
var connection_1$1 = connection$1;
var neo4j_driver_core_1$2 = lib$1;
var _a$2 = neo4j_driver_core_1$2.internal.constants, BOLT_PROTOCOL_V3$1 = _a$2.BOLT_PROTOCOL_V3, BOLT_PROTOCOL_V4_0$1 = _a$2.BOLT_PROTOCOL_V4_0, BOLT_PROTOCOL_V4_4$1 = _a$2.BOLT_PROTOCOL_V4_4, BOLT_PROTOCOL_V5_1$1 = _a$2.BOLT_PROTOCOL_V5_1;
var SERVICE_UNAVAILABLE$1 = neo4j_driver_core_1$2.error.SERVICE_UNAVAILABLE;
var DirectConnectionProvider = /** @class */ (function (_super) {
    __extends$1(DirectConnectionProvider, _super);
    function DirectConnectionProvider(_a) {
        var id = _a.id, config = _a.config, log = _a.log, address = _a.address, userAgent = _a.userAgent, boltAgent = _a.boltAgent, authTokenManager = _a.authTokenManager, newPool = _a.newPool;
        var _this = _super.call(this, { id: id, config: config, log: log, userAgent: userAgent, boltAgent: boltAgent, authTokenManager: authTokenManager, newPool: newPool }) || this;
        _this._address = address;
        return _this;
    }
    /**
     * See {@link ConnectionProvider} for more information about this method and
     * its arguments.
     */
    DirectConnectionProvider.prototype.acquireConnection = function () {
        return __awaiter$1(this, arguments, void 0, function (_a) {
            var databaseSpecificErrorHandler, connection;
            var _this = this;
            var _b = _a === void 0 ? {} : _a; _b.accessMode; var database = _b.database; _b.bookmarks; var auth = _b.auth, forceReAuth = _b.forceReAuth;
            return __generator$1(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        databaseSpecificErrorHandler = connection_1$1.ConnectionErrorHandler.create({
                            errorCode: SERVICE_UNAVAILABLE$1,
                            handleSecurityError: function (error, address, conn) {
                                return _this._handleSecurityError(error, address, conn, database);
                            }
                        });
                        return [4 /*yield*/, this._connectionPool.acquire({ auth: auth, forceReAuth: forceReAuth }, this._address)];
                    case 1:
                        connection = _c.sent();
                        if (!auth) return [3 /*break*/, 3];
                        return [4 /*yield*/, this._verifyStickyConnection({
                                auth: auth,
                                connection: connection,
                                address: this._address
                            })];
                    case 2:
                        _c.sent();
                        return [2 /*return*/, connection];
                    case 3: return [2 /*return*/, new connection_1$1.DelegateConnection(connection, databaseSpecificErrorHandler)];
                }
            });
        });
    };
    DirectConnectionProvider.prototype._handleSecurityError = function (error, address, connection, database) {
        this._log.warn("Direct driver ".concat(this._id, " will close connection to ").concat(address, " for database '").concat(database, "' because of an error ").concat(error.code, " '").concat(error.message, "'"));
        return _super.prototype._handleSecurityError.call(this, error, address, connection);
    };
    DirectConnectionProvider.prototype._hasProtocolVersion = function (versionPredicate) {
        return __awaiter$1(this, void 0, void 0, function () {
            var connection, protocolVersion;
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._createChannelConnection(this._address)];
                    case 1:
                        connection = _a.sent();
                        protocolVersion = connection.protocol()
                            ? connection.protocol().version
                            : null;
                        return [4 /*yield*/, connection.close()];
                    case 2:
                        _a.sent();
                        if (protocolVersion) {
                            return [2 /*return*/, versionPredicate(protocolVersion)];
                        }
                        return [2 /*return*/, false];
                }
            });
        });
    };
    DirectConnectionProvider.prototype.supportsMultiDb = function () {
        return __awaiter$1(this, void 0, void 0, function () {
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V4_0$1; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DirectConnectionProvider.prototype.getNegotiatedProtocolVersion = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this._hasProtocolVersion(resolve)
                .catch(reject);
        });
    };
    DirectConnectionProvider.prototype.supportsTransactionConfig = function () {
        return __awaiter$1(this, void 0, void 0, function () {
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V3$1; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DirectConnectionProvider.prototype.supportsUserImpersonation = function () {
        return __awaiter$1(this, void 0, void 0, function () {
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V4_4$1; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DirectConnectionProvider.prototype.supportsSessionAuth = function () {
        return __awaiter$1(this, void 0, void 0, function () {
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V5_1$1; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DirectConnectionProvider.prototype.verifyAuthentication = function (_a) {
        return __awaiter$1(this, arguments, void 0, function (_b) {
            var _this = this;
            var auth = _b.auth;
            return __generator$1(this, function (_c) {
                return [2 /*return*/, this._verifyAuthentication({
                        auth: auth,
                        getAddress: function () { return _this._address; }
                    })];
            });
        });
    };
    DirectConnectionProvider.prototype.verifyConnectivityAndGetServerInfo = function () {
        return __awaiter$1(this, void 0, void 0, function () {
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._verifyConnectivityAndGetServerVersion({ address: this._address })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    return DirectConnectionProvider;
}(connection_provider_pooled_1$1.default));
connectionProviderDirect.default = DirectConnectionProvider;

var connectionProviderRouting = {};

var rediscovery$1 = {};

var rediscovery = {};

var routingTable = {};

var __read$1 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(routingTable, "__esModule", { value: true });
routingTable.createValidRoutingTable = createValidRoutingTable;
/**
 * 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 neo4j_driver_core_1$1 = lib$1;
var _a$1 = neo4j_driver_core_1$1.internal.constants, WRITE$1 = _a$1.ACCESS_MODE_WRITE, READ$1 = _a$1.ACCESS_MODE_READ, ServerAddress = neo4j_driver_core_1$1.internal.serverAddress.ServerAddress;
var PROTOCOL_ERROR = neo4j_driver_core_1$1.error.PROTOCOL_ERROR;
var MIN_ROUTERS = 1;
/**
 * The routing table object used to determine the role of the servers in the driver.
 */
var RoutingTable = /** @class */ (function () {
    function RoutingTable(_a) {
        var _b = _a === void 0 ? {} : _a, database = _b.database, routers = _b.routers, readers = _b.readers, writers = _b.writers, expirationTime = _b.expirationTime, ttl = _b.ttl;
        this.database = database || null;
        this.databaseName = database || 'default database';
        this.routers = routers || [];
        this.readers = readers || [];
        this.writers = writers || [];
        this.expirationTime = expirationTime || (0, neo4j_driver_core_1$1.int)(0);
        this.ttl = ttl;
    }
    /**
     * Create a valid routing table from a raw object
     *
     * @param {string} database the database name. It is used for logging purposes
     * @param {ServerAddress} routerAddress The router address, it is used for loggin purposes
     * @param {RawRoutingTable} rawRoutingTable Method used to get the raw routing table to be processed
     * @param {RoutingTable} The valid Routing Table
     */
    RoutingTable.fromRawRoutingTable = function (database, routerAddress, rawRoutingTable) {
        return createValidRoutingTable(database, routerAddress, rawRoutingTable);
    };
    RoutingTable.prototype.forget = function (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);
    };
    RoutingTable.prototype.forgetRouter = function (address) {
        this.routers = removeFromArray(this.routers, address);
    };
    RoutingTable.prototype.forgetWriter = function (address) {
        this.writers = removeFromArray(this.writers, address);
    };
    /**
     * 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} `true` when this table contains servers to serve the required operation, `false` otherwise.
     */
    RoutingTable.prototype.isStaleFor = function (accessMode) {
        return (this.expirationTime.lessThan(Date.now()) ||
            this.routers.length < MIN_ROUTERS ||
            (accessMode === READ$1 && this.readers.length === 0) ||
            (accessMode === WRITE$1 && this.writers.length === 0));
    };
    /**
     * Check if this routing table is expired for specified amount of duration
     *
     * @param {Integer} duration amount of duration in milliseconds to check for expiration
     * @returns {boolean}
     */
    RoutingTable.prototype.isExpiredFor = function (duration) {
        return this.expirationTime.add(duration).lessThan(Date.now());
    };
    RoutingTable.prototype.allServers = function () {
        return __spreadArray(__spreadArray(__spreadArray([], __read$1(this.routers), false), __read$1(this.readers), false), __read$1(this.writers), false);
    };
    RoutingTable.prototype.toString = function () {
        return ('RoutingTable[' +
            "database=".concat(this.databaseName, ", ") +
            "expirationTime=".concat(this.expirationTime, ", ") +
            "currentTime=".concat(Date.now(), ", ") +
            "routers=[".concat(this.routers, "], ") +
            "readers=[".concat(this.readers, "], ") +
            "writers=[".concat(this.writers, "]]"));
    };
    return RoutingTable;
}());
routingTable.default = 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.
 */
function removeFromArray(array, element) {
    return array.filter(function (item) { return item.asKey() !== element.asKey(); });
}
/**
 * Create a valid routing table from a raw object
 *
 * @param {string} db the database name. It is used for logging purposes
 * @param {ServerAddress} routerAddress The router address, it is used for loggin purposes
 * @param {RawRoutingTable} rawRoutingTable Method used to get the raw routing table to be processed
 * @param {RoutingTable} The valid Routing Table
 */
function createValidRoutingTable(database, routerAddress, rawRoutingTable) {
    var ttl = rawRoutingTable.ttl;
    var expirationTime = calculateExpirationTime(rawRoutingTable, routerAddress);
    var _a = parseServers(rawRoutingTable, routerAddress), routers = _a.routers, readers = _a.readers, writers = _a.writers;
    assertNonEmpty(routers, 'routers', routerAddress);
    assertNonEmpty(readers, 'readers', routerAddress);
    return new RoutingTable({
        database: database || rawRoutingTable.db,
        routers: routers,
        readers: readers,
        writers: writers,
        expirationTime: expirationTime,
        ttl: ttl
    });
}
/**
 * Parse server from the RawRoutingTable.
 *
 * @param {RawRoutingTable} rawRoutingTable the raw routing table
 * @param {string} routerAddress the router address
 * @returns {Object} The object with the list of routers, readers and writers
 */
function parseServers(rawRoutingTable, routerAddress) {
    try {
        var routers_1 = [];
        var readers_1 = [];
        var writers_1 = [];
        rawRoutingTable.servers.forEach(function (server) {
            var role = server.role;
            var addresses = server.addresses;
            if (role === 'ROUTE') {
                routers_1 = parseArray(addresses).map(function (address) {
                    return ServerAddress.fromUrl(address);
                });
            }
            else if (role === 'WRITE') {
                writers_1 = parseArray(addresses).map(function (address) {
                    return ServerAddress.fromUrl(address);
                });
            }
            else if (role === 'READ') {
                readers_1 = parseArray(addresses).map(function (address) {
                    return ServerAddress.fromUrl(address);
                });
            }
        });
        return {
            routers: routers_1,
            readers: readers_1,
            writers: writers_1
        };
    }
    catch (error) {
        throw (0, neo4j_driver_core_1$1.newError)("Unable to parse servers entry from router ".concat(routerAddress, " from addresses:\n").concat(neo4j_driver_core_1$1.json.stringify(rawRoutingTable.servers), "\nError message: ").concat(error.message), PROTOCOL_ERROR);
    }
}
/**
 * Call the expiration time using the ttls from the raw routing table and return it
 *
 * @param {RawRoutingTable} rawRoutingTable the routing table
 * @param {string} routerAddress the router address
 * @returns {number} the ttl
 */
function calculateExpirationTime(rawRoutingTable, routerAddress) {
    try {
        var now = (0, neo4j_driver_core_1$1.int)(Date.now());
        var expires = (0, neo4j_driver_core_1$1.int)(rawRoutingTable.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 neo4j_driver_core_1$1.Integer.MAX_VALUE;
        }
        return expires;
    }
    catch (error) {
        throw (0, neo4j_driver_core_1$1.newError)("Unable to parse TTL entry from router ".concat(routerAddress, " from raw routing table:\n").concat(neo4j_driver_core_1$1.json.stringify(rawRoutingTable), "\nError message: ").concat(error.message), PROTOCOL_ERROR);
    }
}
/**
 * Assert if serverAddressesArray is not empty, throws and PROTOCOL_ERROR otherwise
 *
 * @param {string[]} serverAddressesArray array of addresses
 * @param {string} serversName the server name
 * @param {string} routerAddress the router address
 */
function assertNonEmpty(serverAddressesArray, serversName, routerAddress) {
    if (serverAddressesArray.length === 0) {
        throw (0, neo4j_driver_core_1$1.newError)('Received no ' + serversName + ' from router ' + routerAddress, PROTOCOL_ERROR);
    }
}
function parseArray(addresses) {
    if (!Array.isArray(addresses)) {
        throw new TypeError('Array expected but got: ' + addresses);
    }
    return Array.from(addresses);
}

var __importDefault$2 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(rediscovery, "__esModule", { value: true });
/**
 * 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 routing_table_1$1 = __importDefault$2(routingTable);
var Rediscovery = /** @class */ (function () {
    /**
     * @constructor
     * @param {object} routingContext
     */
    function Rediscovery(routingContext) {
        this._routingContext = routingContext;
    }
    /**
     * Try to fetch new routing table from the given router.
     * @param {Session} session the session to use.
     * @param {string} database the database for which to lookup routing table.
     * @param {ServerAddress} routerAddress the URL of the router.
     * @param {string} impersonatedUser The impersonated user
     * @return {Promise<RoutingTable>} promise resolved with new routing table or null when connection error happened.
     */
    Rediscovery.prototype.lookupRoutingTableOnRouter = function (session, database, routerAddress, impersonatedUser) {
        var _this = this;
        return session._acquireConnection(function (connection) {
            return _this._requestRawRoutingTable(connection, session, database, routerAddress, impersonatedUser).then(function (rawRoutingTable) {
                if (rawRoutingTable.isNull) {
                    return null;
                }
                return routing_table_1$1.default.fromRawRoutingTable(database, routerAddress, rawRoutingTable);
            });
        });
    };
    Rediscovery.prototype._requestRawRoutingTable = function (connection, session, database, routerAddress, impersonatedUser) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            connection.protocol().requestRoutingInformation({
                routingContext: _this._routingContext,
                databaseName: database,
                impersonatedUser: impersonatedUser,
                sessionContext: {
                    bookmarks: session._lastBookmarks,
                    mode: session._mode,
                    database: session._database,
                    afterComplete: session._onComplete
                },
                onCompleted: resolve,
                onError: reject
            });
        });
    };
    return Rediscovery;
}());
rediscovery.default = Rediscovery;

/**
 * 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 __importDefault$1 = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(rediscovery$1, "__esModule", { value: true });
rediscovery$1.RoutingTable = rediscovery$1.Rediscovery = void 0;
var rediscovery_1$1 = __importDefault$1(rediscovery);
rediscovery$1.Rediscovery = rediscovery_1$1.default;
var routing_table_1 = __importDefault$1(routingTable);
rediscovery$1.RoutingTable = routing_table_1.default;
rediscovery$1.default = rediscovery_1$1.default;

/**
 * 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 = (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 __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(connectionProviderRouting, "__esModule", { value: true });
var neo4j_driver_core_1 = lib$1;
var rediscovery_1 = __importStar(rediscovery$1);
var channel_1 = channel;
var connection_provider_single_1 = __importDefault(connectionProviderSingle);
var connection_provider_pooled_1 = __importDefault(connectionProviderPooled);
var load_balancing_1 = loadBalancing;
var connection_1 = connection$1;
var lang_1 = lang;
var SERVICE_UNAVAILABLE = neo4j_driver_core_1.error.SERVICE_UNAVAILABLE, SESSION_EXPIRED = neo4j_driver_core_1.error.SESSION_EXPIRED;
var Bookmarks = neo4j_driver_core_1.internal.bookmarks.Bookmarks, _a = neo4j_driver_core_1.internal.constants, READ = _a.ACCESS_MODE_READ, WRITE = _a.ACCESS_MODE_WRITE, BOLT_PROTOCOL_V3 = _a.BOLT_PROTOCOL_V3, BOLT_PROTOCOL_V4_0 = _a.BOLT_PROTOCOL_V4_0, BOLT_PROTOCOL_V4_4 = _a.BOLT_PROTOCOL_V4_4, BOLT_PROTOCOL_V5_1 = _a.BOLT_PROTOCOL_V5_1;
var PROCEDURE_NOT_FOUND_CODE = 'Neo.ClientError.Procedure.ProcedureNotFound';
var DATABASE_NOT_FOUND_CODE = 'Neo.ClientError.Database.DatabaseNotFound';
var INVALID_BOOKMARK_CODE = 'Neo.ClientError.Transaction.InvalidBookmark';
var INVALID_BOOKMARK_MIXTURE_CODE = 'Neo.ClientError.Transaction.InvalidBookmarkMixture';
var AUTHORIZATION_EXPIRED_CODE = 'Neo.ClientError.Security.AuthorizationExpired';
var INVALID_ARGUMENT_ERROR = 'Neo.ClientError.Statement.ArgumentError';
var INVALID_REQUEST_ERROR = 'Neo.ClientError.Request.Invalid';
var STATEMENT_TYPE_ERROR = 'Neo.ClientError.Statement.TypeError';
var NOT_AVAILABLE = 'N/A';
var SYSTEM_DB_NAME = 'system';
var DEFAULT_DB_NAME = null;
var DEFAULT_ROUTING_TABLE_PURGE_DELAY = (0, neo4j_driver_core_1.int)(30000);
var RoutingConnectionProvider = /** @class */ (function (_super) {
    __extends(RoutingConnectionProvider, _super);
    function RoutingConnectionProvider(_a) {
        var id = _a.id, address = _a.address, routingContext = _a.routingContext, hostNameResolver = _a.hostNameResolver, config = _a.config, log = _a.log, userAgent = _a.userAgent, boltAgent = _a.boltAgent, authTokenManager = _a.authTokenManager, routingTablePurgeDelay = _a.routingTablePurgeDelay, newPool = _a.newPool;
        var _this = _super.call(this, { id: id, config: config, log: log, userAgent: userAgent, boltAgent: boltAgent, authTokenManager: authTokenManager, newPool: newPool }, function (address) { return __awaiter(_this, void 0, void 0, function () {
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _a = connection_1.createChannelConnection;
                        _b = [address,
                            this._config,
                            this._createConnectionErrorHandler(),
                            this._log];
                        return [4 /*yield*/, this._clientCertificateHolder.getClientCertificate()];
                    case 1: return [2 /*return*/, _a.apply(void 0, _b.concat([_c.sent(), this._routingContext,
                            this._channelSsrCallback.bind(this)]))];
                }
            });
        }); }) || this;
        _this._routingContext = __assign(__assign({}, routingContext), { address: address.toString() });
        _this._seedRouter = address;
        _this._rediscovery = new rediscovery_1.default(_this._routingContext);
        _this._loadBalancingStrategy = new load_balancing_1.LeastConnectedLoadBalancingStrategy(_this._connectionPool);
        _this._hostNameResolver = hostNameResolver;
        _this._dnsResolver = new channel_1.HostNameResolver();
        _this._log = log;
        _this._useSeedRouter = true;
        _this._routingTableRegistry = new RoutingTableRegistry(routingTablePurgeDelay
            ? (0, neo4j_driver_core_1.int)(routingTablePurgeDelay)
            : DEFAULT_ROUTING_TABLE_PURGE_DELAY);
        _this._refreshRoutingTable = lang_1.functional.reuseOngoingRequest(_this._refreshRoutingTable, _this);
        _this._withSSR = 0;
        _this._withoutSSR = 0;
        return _this;
    }
    RoutingConnectionProvider.prototype._createConnectionErrorHandler = function () {
        // 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 new connection_1.ConnectionErrorHandler(SESSION_EXPIRED);
    };
    RoutingConnectionProvider.prototype._handleUnavailability = function (error, address, database) {
        this._log.warn("Routing driver ".concat(this._id, " will forget ").concat(address, " for database '").concat(database, "' because of an error ").concat(error.code, " '").concat(error.message, "'"));
        this.forget(address, database || DEFAULT_DB_NAME);
        return error;
    };
    RoutingConnectionProvider.prototype._handleSecurityError = function (error, address, connection, database) {
        this._log.warn("Routing driver ".concat(this._id, " will close connections to ").concat(address, " for database '").concat(database, "' because of an error ").concat(error.code, " '").concat(error.message, "'"));
        return _super.prototype._handleSecurityError.call(this, error, address, connection, database);
    };
    RoutingConnectionProvider.prototype._handleWriteFailure = function (error, address, database) {
        this._log.warn("Routing driver ".concat(this._id, " will forget writer ").concat(address, " for database '").concat(database, "' because of an error ").concat(error.code, " '").concat(error.message, "'"));
        this.forgetWriter(address, database || DEFAULT_DB_NAME);
        return (0, neo4j_driver_core_1.newError)('No longer possible to write to server at ' + address, SESSION_EXPIRED, error);
    };
    /**
     * See {@link ConnectionProvider} for more information about this method and
     * its arguments.
     */
    RoutingConnectionProvider.prototype.acquireConnection = function () {
        return __awaiter(this, arguments, void 0, function (_a) {
            var context, databaseSpecificErrorHandler, conn, currentRoutingTable, routingTable;
            var _this = this;
            var _b = _a === void 0 ? {} : _a, accessMode = _b.accessMode, database = _b.database, bookmarks = _b.bookmarks, impersonatedUser = _b.impersonatedUser, onDatabaseNameResolved = _b.onDatabaseNameResolved, auth = _b.auth, homeDb = _b.homeDb;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        context = { database: database || DEFAULT_DB_NAME };
                        databaseSpecificErrorHandler = new connection_1.ConnectionErrorHandler(SESSION_EXPIRED, function (error, address) { return _this._handleUnavailability(error, address, context.database); }, function (error, address) { return _this._handleWriteFailure(error, address, homeDb !== null && homeDb !== void 0 ? homeDb : context.database); }, function (error, address, conn) { return _this._handleSecurityError(error, address, conn, context.database); });
                        if (!(this.SSREnabled() && homeDb !== undefined && database === '')) return [3 /*break*/, 2];
                        currentRoutingTable = this._routingTableRegistry.get(homeDb, function () { return new rediscovery_1.RoutingTable({ database: homeDb }); });
                        if (!(currentRoutingTable && !currentRoutingTable.isStaleFor(accessMode))) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.getConnectionFromRoutingTable(currentRoutingTable, auth, accessMode, databaseSpecificErrorHandler)];
                    case 1:
                        conn = _c.sent();
                        if (this.SSREnabled()) {
                            return [2 /*return*/, conn];
                        }
                        conn.release();
                        _c.label = 2;
                    case 2: return [4 /*yield*/, this._freshRoutingTable({
                            accessMode: accessMode,
                            database: context.database,
                            bookmarks: bookmarks,
                            impersonatedUser: impersonatedUser,
                            auth: auth,
                            onDatabaseNameResolved: function (databaseName) {
                                context.database = context.database || databaseName;
                                if (onDatabaseNameResolved) {
                                    onDatabaseNameResolved(databaseName);
                                }
                            }
                        })];
                    case 3:
                        routingTable = _c.sent();
                        return [2 /*return*/, this.getConnectionFromRoutingTable(routingTable, auth, accessMode, databaseSpecificErrorHandler)];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.getConnectionFromRoutingTable = function (routingTable, auth, accessMode, databaseSpecificErrorHandler) {
        return __awaiter(this, void 0, void 0, function () {
            var name, address, connection, error_1, transformed;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        // select a target server based on specified access mode
                        if (accessMode === READ) {
                            address = this._loadBalancingStrategy.selectReader(routingTable.readers);
                            name = 'read';
                        }
                        else if (accessMode === WRITE) {
                            address = this._loadBalancingStrategy.selectWriter(routingTable.writers);
                            name = 'write';
                        }
                        else {
                            throw (0, neo4j_driver_core_1.newError)('Illegal mode ' + accessMode);
                        }
                        // we couldn't select a target server
                        if (!address) {
                            throw (0, neo4j_driver_core_1.newError)("Failed to obtain connection towards ".concat(name, " server. Known routing table is: ").concat(routingTable), SESSION_EXPIRED);
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, , 6]);
                        return [4 /*yield*/, this._connectionPool.acquire({ auth: auth }, address)];
                    case 2:
                        connection = _a.sent();
                        if (!auth) return [3 /*break*/, 4];
                        return [4 /*yield*/, this._verifyStickyConnection({
                                auth: auth,
                                connection: connection,
                                address: address
                            })];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, connection];
                    case 4: return [2 /*return*/, new connection_1.DelegateConnection(connection, databaseSpecificErrorHandler)];
                    case 5:
                        error_1 = _a.sent();
                        transformed = databaseSpecificErrorHandler.handleAndTransformError(error_1, address);
                        throw transformed;
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._hasProtocolVersion = function (versionPredicate) {
        return __awaiter(this, void 0, void 0, function () {
            var addresses, lastError, i, connection, protocolVersion, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._resolveSeedRouter(this._seedRouter)];
                    case 1:
                        addresses = _a.sent();
                        i = 0;
                        _a.label = 2;
                    case 2:
                        if (!(i < addresses.length)) return [3 /*break*/, 8];
                        _a.label = 3;
                    case 3:
                        _a.trys.push([3, 6, , 7]);
                        return [4 /*yield*/, this._createChannelConnection(addresses[i])];
                    case 4:
                        connection = _a.sent();
                        protocolVersion = connection.protocol()
                            ? connection.protocol().version
                            : null;
                        return [4 /*yield*/, connection.close()];
                    case 5:
                        _a.sent();
                        if (protocolVersion) {
                            return [2 /*return*/, versionPredicate(protocolVersion)];
                        }
                        return [2 /*return*/, false];
                    case 6:
                        error_2 = _a.sent();
                        lastError = error_2;
                        return [3 /*break*/, 7];
                    case 7:
                        i++;
                        return [3 /*break*/, 2];
                    case 8:
                        if (lastError) {
                            throw lastError;
                        }
                        return [2 /*return*/, false];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.supportsMultiDb = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V4_0; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.supportsTransactionConfig = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V3; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.supportsUserImpersonation = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V4_4; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.supportsSessionAuth = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hasProtocolVersion(function (version) { return version >= BOLT_PROTOCOL_V5_1; })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.getNegotiatedProtocolVersion = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this._hasProtocolVersion(resolve)
                .catch(reject);
        });
    };
    RoutingConnectionProvider.prototype.verifyAuthentication = function (_a) {
        return __awaiter(this, arguments, void 0, function (_b) {
            var _this = this;
            var database = _b.database, accessMode = _b.accessMode, auth = _b.auth;
            return __generator(this, function (_c) {
                return [2 /*return*/, this._verifyAuthentication({
                        auth: auth,
                        getAddress: function () { return __awaiter(_this, void 0, void 0, function () {
                            var context, routingTable, servers;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        context = { database: database || DEFAULT_DB_NAME };
                                        return [4 /*yield*/, this._freshRoutingTable({
                                                accessMode: accessMode,
                                                database: context.database,
                                                auth: auth,
                                                onDatabaseNameResolved: function (databaseName) {
                                                    context.database = context.database || databaseName;
                                                }
                                            })];
                                    case 1:
                                        routingTable = _a.sent();
                                        servers = accessMode === WRITE ? routingTable.writers : routingTable.readers;
                                        if (servers.length === 0) {
                                            throw (0, neo4j_driver_core_1.newError)("No servers available for database '".concat(context.database, "' with access mode '").concat(accessMode, "'"), SERVICE_UNAVAILABLE);
                                        }
                                        return [2 /*return*/, servers[0]];
                                }
                            });
                        }); }
                    })];
            });
        });
    };
    RoutingConnectionProvider.prototype.verifyConnectivityAndGetServerInfo = function (_a) {
        return __awaiter(this, arguments, void 0, function (_b) {
            var context, routingTable, servers, error, servers_1, servers_1_1, address, serverInfo, e_1, e_2_1;
            var e_2, _c;
            var database = _b.database, accessMode = _b.accessMode;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        context = { database: database || DEFAULT_DB_NAME };
                        return [4 /*yield*/, this._freshRoutingTable({
                                accessMode: accessMode,
                                database: context.database,
                                onDatabaseNameResolved: function (databaseName) {
                                    context.database = context.database || databaseName;
                                }
                            })];
                    case 1:
                        routingTable = _d.sent();
                        servers = accessMode === WRITE ? routingTable.writers : routingTable.readers;
                        error = (0, neo4j_driver_core_1.newError)("No servers available for database '".concat(context.database, "' with access mode '").concat(accessMode, "'"), SERVICE_UNAVAILABLE);
                        _d.label = 2;
                    case 2:
                        _d.trys.push([2, 9, 10, 11]);
                        servers_1 = __values(servers), servers_1_1 = servers_1.next();
                        _d.label = 3;
                    case 3:
                        if (!!servers_1_1.done) return [3 /*break*/, 8];
                        address = servers_1_1.value;
                        _d.label = 4;
                    case 4:
                        _d.trys.push([4, 6, , 7]);
                        return [4 /*yield*/, this._verifyConnectivityAndGetServerVersion({ address: address })];
                    case 5:
                        serverInfo = _d.sent();
                        return [2 /*return*/, serverInfo];
                    case 6:
                        e_1 = _d.sent();
                        error = e_1;
                        return [3 /*break*/, 7];
                    case 7:
                        servers_1_1 = servers_1.next();
                        return [3 /*break*/, 3];
                    case 8: return [3 /*break*/, 11];
                    case 9:
                        e_2_1 = _d.sent();
                        e_2 = { error: e_2_1 };
                        return [3 /*break*/, 11];
                    case 10:
                        try {
                            if (servers_1_1 && !servers_1_1.done && (_c = servers_1.return)) _c.call(servers_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                        return [7 /*endfinally*/];
                    case 11: throw error;
                }
            });
        });
    };
    RoutingConnectionProvider.prototype.forget = function (address, database) {
        this._routingTableRegistry.apply(database, {
            applyWhenExists: function (routingTable) { return routingTable.forget(address); }
        });
        // We're firing and forgetting this operation explicitly and listening for any
        // errors to avoid unhandled promise rejection
        this._connectionPool.purge(address).catch(function () { });
    };
    RoutingConnectionProvider.prototype.forgetWriter = function (address, database) {
        this._routingTableRegistry.apply(database, {
            applyWhenExists: function (routingTable) { return routingTable.forgetWriter(address); }
        });
    };
    RoutingConnectionProvider.prototype._freshRoutingTable = function (_a) {
        var _b = _a === void 0 ? {} : _a, accessMode = _b.accessMode, database = _b.database, bookmarks = _b.bookmarks, impersonatedUser = _b.impersonatedUser, onDatabaseNameResolved = _b.onDatabaseNameResolved, auth = _b.auth;
        var currentRoutingTable = this._routingTableRegistry.get(database, function () { return new rediscovery_1.RoutingTable({ database: database }); });
        if (!currentRoutingTable.isStaleFor(accessMode)) {
            return currentRoutingTable;
        }
        this._log.info("Routing table is stale for database: \"".concat(database, "\" and access mode: \"").concat(accessMode, "\": ").concat(currentRoutingTable));
        return this._refreshRoutingTable(currentRoutingTable, bookmarks, impersonatedUser, auth)
            .then(function (newRoutingTable) {
            onDatabaseNameResolved(newRoutingTable.database);
            return newRoutingTable;
        });
    };
    RoutingConnectionProvider.prototype._refreshRoutingTable = function (currentRoutingTable, bookmarks, impersonatedUser, auth) {
        var knownRouters = currentRoutingTable.routers;
        if (this._useSeedRouter) {
            return this._fetchRoutingTableFromSeedRouterFallbackToKnownRouters(knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth);
        }
        return this._fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth);
    };
    RoutingConnectionProvider.prototype._fetchRoutingTableFromSeedRouterFallbackToKnownRouters = function (knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth) {
        return __awaiter(this, void 0, void 0, function () {
            var seenRouters, _a, newRoutingTable, error, _b, newRoutingTable2, error2;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        seenRouters = [];
                        return [4 /*yield*/, this._fetchRoutingTableUsingSeedRouter(seenRouters, this._seedRouter, currentRoutingTable, bookmarks, impersonatedUser, auth)];
                    case 1:
                        _a = __read.apply(void 0, [_c.sent(), 2]), newRoutingTable = _a[0], error = _a[1];
                        if (!newRoutingTable) return [3 /*break*/, 2];
                        this._useSeedRouter = false;
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth)];
                    case 3:
                        _b = __read.apply(void 0, [_c.sent(), 2]), newRoutingTable2 = _b[0], error2 = _b[1];
                        newRoutingTable = newRoutingTable2;
                        error = error2 || error;
                        _c.label = 4;
                    case 4: return [4 /*yield*/, this._applyRoutingTableIfPossible(currentRoutingTable, newRoutingTable, error)];
                    case 5: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._fetchRoutingTableFromKnownRoutersFallbackToSeedRouter = function (knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, newRoutingTable, error;
            var _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth)];
                    case 1:
                        _a = __read.apply(void 0, [_c.sent(), 2]), newRoutingTable = _a[0], error = _a[1];
                        if (!!newRoutingTable) return [3 /*break*/, 3];
                        return [4 /*yield*/, this._fetchRoutingTableUsingSeedRouter(knownRouters, this._seedRouter, currentRoutingTable, bookmarks, impersonatedUser, auth)];
                    case 2:
                        // none of the known routers returned a valid routing table - try to use seed router address for rediscovery
                        _b = __read.apply(void 0, [_c.sent(), 2]), newRoutingTable = _b[0], error = _b[1];
                        _c.label = 3;
                    case 3: return [4 /*yield*/, this._applyRoutingTableIfPossible(currentRoutingTable, newRoutingTable, error)];
                    case 4: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._fetchRoutingTableUsingKnownRouters = function (knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, newRoutingTable, error, lastRouterIndex;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this._fetchRoutingTable(knownRouters, currentRoutingTable, bookmarks, impersonatedUser, auth)];
                    case 1:
                        _a = __read.apply(void 0, [_b.sent(), 2]), newRoutingTable = _a[0], error = _a[1];
                        if (newRoutingTable) {
                            // one of the known routers returned a valid routing table - use it
                            return [2 /*return*/, [newRoutingTable, null]];
                        }
                        lastRouterIndex = knownRouters.length - 1;
                        RoutingConnectionProvider._forgetRouter(currentRoutingTable, knownRouters, lastRouterIndex);
                        return [2 /*return*/, [null, error]];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._fetchRoutingTableUsingSeedRouter = function (seenRouters, seedRouter, routingTable, bookmarks, impersonatedUser, auth) {
        return __awaiter(this, void 0, void 0, function () {
            var resolvedAddresses, newAddresses;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._resolveSeedRouter(seedRouter)
                        // filter out all addresses that we've already tried
                    ];
                    case 1:
                        resolvedAddresses = _a.sent();
                        newAddresses = resolvedAddresses.filter(function (address) { return seenRouters.indexOf(address) < 0; });
                        return [4 /*yield*/, this._fetchRoutingTable(newAddresses, routingTable, bookmarks, impersonatedUser, auth)];
                    case 2: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._resolveSeedRouter = function (seedRouter) {
        return __awaiter(this, void 0, void 0, function () {
            var resolvedAddresses, dnsResolvedAddresses;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._hostNameResolver.resolve(seedRouter)];
                    case 1:
                        resolvedAddresses = _a.sent();
                        return [4 /*yield*/, Promise.all(resolvedAddresses.map(function (address) { return _this._dnsResolver.resolve(address); }))];
                    case 2:
                        dnsResolvedAddresses = _a.sent();
                        return [2 /*return*/, [].concat.apply([], dnsResolvedAddresses)];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._fetchRoutingTable = function (routerAddresses, routingTable, bookmarks, impersonatedUser, auth) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, routerAddresses.reduce(function (refreshedTablePromise, currentRouter, currentIndex) { return __awaiter(_this, void 0, void 0, function () {
                        var _a, newRoutingTable, previousRouterIndex, _b, session, error, error_3;
                        return __generator(this, function (_c) {
                            switch (_c.label) {
                                case 0: return [4 /*yield*/, refreshedTablePromise];
                                case 1:
                                    _a = __read.apply(void 0, [_c.sent(), 1]), newRoutingTable = _a[0];
                                    if (newRoutingTable) {
                                        // valid routing table was fetched - just return it, try next router otherwise
                                        return [2 /*return*/, [newRoutingTable, null]];
                                    }
                                    else {
                                        previousRouterIndex = currentIndex - 1;
                                        RoutingConnectionProvider._forgetRouter(routingTable, routerAddresses, previousRouterIndex);
                                    }
                                    return [4 /*yield*/, this._createSessionForRediscovery(currentRouter, bookmarks, impersonatedUser, auth)];
                                case 2:
                                    _b = __read.apply(void 0, [_c.sent(), 2]), session = _b[0], error = _b[1];
                                    if (!session) return [3 /*break*/, 8];
                                    _c.label = 3;
                                case 3:
                                    _c.trys.push([3, 5, 6, 7]);
                                    return [4 /*yield*/, this._rediscovery.lookupRoutingTableOnRouter(session, routingTable.database, currentRouter, impersonatedUser)];
                                case 4: return [2 /*return*/, [_c.sent(), null]];
                                case 5:
                                    error_3 = _c.sent();
                                    return [2 /*return*/, this._handleRediscoveryError(error_3, currentRouter)];
                                case 6:
                                    session.close();
                                    return [7 /*endfinally*/];
                                case 7: return [3 /*break*/, 9];
                                case 8: 
                                // unable to acquire connection and create session towards the current router
                                // return null to signal that the next router should be tried
                                return [2 /*return*/, [null, error]];
                                case 9: return [2 /*return*/];
                            }
                        });
                    }); }, Promise.resolve([null, null]))];
            });
        });
    };
    RoutingConnectionProvider.prototype._createSessionForRediscovery = function (routerAddress, bookmarks, impersonatedUser, auth) {
        return __awaiter(this, void 0, void 0, function () {
            var connection, databaseSpecificErrorHandler, delegateConnection, connectionProvider, protocolVersion, error_4;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 5]);
                        return [4 /*yield*/, this._connectionPool.acquire({ auth: auth }, routerAddress)];
                    case 1:
                        connection = _a.sent();
                        if (!auth) return [3 /*break*/, 3];
                        return [4 /*yield*/, this._verifyStickyConnection({
                                auth: auth,
                                connection: connection,
                                address: routerAddress
                            })];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        databaseSpecificErrorHandler = connection_1.ConnectionErrorHandler.create({
                            errorCode: SESSION_EXPIRED,
                            handleSecurityError: function (error, address, conn) { return _this._handleSecurityError(error, address, conn); }
                        });
                        delegateConnection = !connection._sticky
                            ? new connection_1.DelegateConnection(connection, databaseSpecificErrorHandler)
                            : new connection_1.DelegateConnection(connection);
                        connectionProvider = new connection_provider_single_1.default(delegateConnection);
                        protocolVersion = connection.protocol().version;
                        if (protocolVersion < 4.0) {
                            return [2 /*return*/, [new neo4j_driver_core_1.Session({
                                        mode: WRITE,
                                        bookmarks: Bookmarks.empty(),
                                        connectionProvider: connectionProvider
                                    }), null]];
                        }
                        return [2 /*return*/, [new neo4j_driver_core_1.Session({
                                    mode: READ,
                                    database: SYSTEM_DB_NAME,
                                    bookmarks: bookmarks,
                                    connectionProvider: connectionProvider,
                                    impersonatedUser: impersonatedUser
                                }), null]];
                    case 4:
                        error_4 = _a.sent();
                        return [2 /*return*/, this._handleRediscoveryError(error_4, routerAddress)];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._handleRediscoveryError = function (error, routerAddress) {
        if (_isFailFastError(error) || _isFailFastSecurityError(error)) {
            throw error;
        }
        else if (error.code === PROCEDURE_NOT_FOUND_CODE) {
            // throw when getServers procedure not found because this is clearly a configuration issue
            throw (0, neo4j_driver_core_1.newError)("Server at ".concat(routerAddress.asHostPort(), " can't perform routing. Make sure you are connecting to a causal cluster"), SERVICE_UNAVAILABLE, error);
        }
        this._log.warn("unable to fetch routing table because of an error ".concat(error));
        return [null, error];
    };
    RoutingConnectionProvider.prototype._applyRoutingTableIfPossible = function (currentRoutingTable, newRoutingTable, error) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!newRoutingTable) {
                            // none of routing servers returned valid routing table, throw exception
                            throw (0, neo4j_driver_core_1.newError)("Could not perform discovery. No routing servers available. Known routing table: ".concat(currentRoutingTable), SERVICE_UNAVAILABLE, error);
                        }
                        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;
                        }
                        return [4 /*yield*/, this._updateRoutingTable(newRoutingTable)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, newRoutingTable];
                }
            });
        });
    };
    RoutingConnectionProvider.prototype._updateRoutingTable = function (newRoutingTable) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: 
                    // close old connections to servers not present in the new routing table
                    return [4 /*yield*/, this._connectionPool.keepAll(newRoutingTable.allServers())];
                    case 1:
                        // close old connections to servers not present in the new routing table
                        _a.sent();
                        this._routingTableRegistry.removeExpired();
                        this._routingTableRegistry.register(newRoutingTable);
                        this._log.info("Updated routing table ".concat(newRoutingTable));
                        return [2 /*return*/];
                }
            });
        });
    };
    RoutingConnectionProvider._forgetRouter = function (routingTable, routersArray, routerIndex) {
        var address = routersArray[routerIndex];
        if (routingTable && address) {
            routingTable.forgetRouter(address);
        }
    };
    RoutingConnectionProvider.prototype._channelSsrCallback = function (isEnabled, action) {
        if (action === 'OPEN') {
            if (isEnabled === true) {
                this._withSSR = this._withSSR + 1;
            }
            else {
                this._withoutSSR = this._withoutSSR + 1;
            }
        }
        else if (action === 'CLOSE') {
            if (isEnabled === true) {
                this._withSSR = this._withSSR - 1;
            }
            else {
                this._withoutSSR = this._withoutSSR - 1;
            }
        }
        else {
            throw (0, neo4j_driver_core_1.newError)("Channel SSR Callback invoked with action other than 'OPEN' or 'CLOSE'");
        }
    };
    RoutingConnectionProvider.prototype.SSREnabled = function () {
        return this._withSSR > 0 && this._withoutSSR === 0;
    };
    return RoutingConnectionProvider;
}(connection_provider_pooled_1.default));
connectionProviderRouting.default = RoutingConnectionProvider;
/**
 * Responsible for keeping track of the existing routing tables
 */
var RoutingTableRegistry = /** @class */ (function () {
    /**
     * Constructor
     * @param {int} routingTablePurgeDelay The routing table purge delay
     */
    function RoutingTableRegistry(routingTablePurgeDelay) {
        this._tables = new Map();
        this._routingTablePurgeDelay = routingTablePurgeDelay;
    }
    /**
     * Put a routing table in the registry
     *
     * @param {RoutingTable} table The routing table
     * @returns {RoutingTableRegistry} this
     */
    RoutingTableRegistry.prototype.register = function (table) {
        this._tables.set(table.database, table);
        return this;
    };
    /**
     * Apply function in the routing table for an specific database. If the database name is not defined, the function will
     * be applied for each element
     *
     * @param {string} database The database name
     * @param {object} callbacks The actions
     * @param {function (RoutingTable)} callbacks.applyWhenExists Call when the db exists or when the database property is not informed
     * @param {function ()} callbacks.applyWhenDontExists Call when the database doesn't have the routing table registred
     * @returns {RoutingTableRegistry} this
     */
    RoutingTableRegistry.prototype.apply = function (database, _a) {
        var _b = _a === void 0 ? {} : _a, applyWhenExists = _b.applyWhenExists, _c = _b.applyWhenDontExists, applyWhenDontExists = _c === void 0 ? function () { } : _c;
        if (this._tables.has(database)) {
            applyWhenExists(this._tables.get(database));
        }
        else if (typeof database === 'string' || database === null) {
            applyWhenDontExists();
        }
        else {
            this._forEach(applyWhenExists);
        }
        return this;
    };
    /**
     * Retrieves a routing table from a given database name
     *
     * @param {string|impersonatedUser} impersonatedUser The impersonated User
     * @param {string} database The database name
     * @param {function()|RoutingTable} defaultSupplier The routing table supplier, if it's not a function or not exists, it will return itself as default value
     * @returns {RoutingTable} The routing table for the respective database
     */
    RoutingTableRegistry.prototype.get = function (database, defaultSupplier) {
        if (this._tables.has(database)) {
            return this._tables.get(database);
        }
        return typeof defaultSupplier === 'function'
            ? defaultSupplier()
            : defaultSupplier;
    };
    /**
     * Remove the routing table which is already expired
     * @returns {RoutingTableRegistry} this
     */
    RoutingTableRegistry.prototype.removeExpired = function () {
        var _this = this;
        return this._removeIf(function (value) {
            return value.isExpiredFor(_this._routingTablePurgeDelay);
        });
    };
    RoutingTableRegistry.prototype._forEach = function (apply) {
        var e_3, _a;
        try {
            for (var _b = __values(this._tables), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read(_c.value, 2), value = _d[1];
                apply(value);
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_3) throw e_3.error; }
        }
        return this;
    };
    RoutingTableRegistry.prototype._remove = function (key) {
        this._tables.delete(key);
        return this;
    };
    RoutingTableRegistry.prototype._removeIf = function (predicate) {
        var e_4, _a;
        try {
            for (var _b = __values(this._tables), _c = _b.next(); !_c.done; _c = _b.next()) {
                var _d = __read(_c.value, 2), key = _d[0], value = _d[1];
                if (predicate(value)) {
                    this._remove(key);
                }
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_4) throw e_4.error; }
        }
        return this;
    };
    return RoutingTableRegistry;
}());
function _isFailFastError(error) {
    return [
        DATABASE_NOT_FOUND_CODE,
        INVALID_BOOKMARK_CODE,
        INVALID_BOOKMARK_MIXTURE_CODE,
        INVALID_ARGUMENT_ERROR,
        INVALID_REQUEST_ERROR,
        STATEMENT_TYPE_ERROR,
        NOT_AVAILABLE
    ].includes(error.code);
}
function _isFailFastSecurityError(error) {
    var _a;
    return ((_a = error.code) === null || _a === void 0 ? void 0 : _a.startsWith('Neo.ClientError.Security.')) &&
        ![
            AUTHORIZATION_EXPIRED_CODE
        ].includes(error.code);
}

(function (exports) {
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoutingConnectionProvider = exports.DirectConnectionProvider = exports.PooledConnectionProvider = exports.SingleConnectionProvider = 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.
 */
var connection_provider_single_1 = connectionProviderSingle;
Object.defineProperty(exports, "SingleConnectionProvider", { enumerable: true, get: function () { return __importDefault(connection_provider_single_1).default; } });
var connection_provider_pooled_1 = connectionProviderPooled;
Object.defineProperty(exports, "PooledConnectionProvider", { enumerable: true, get: function () { return __importDefault(connection_provider_pooled_1).default; } });
var connection_provider_direct_1 = connectionProviderDirect;
Object.defineProperty(exports, "DirectConnectionProvider", { enumerable: true, get: function () { return __importDefault(connection_provider_direct_1).default; } });
var connection_provider_routing_1 = connectionProviderRouting;
Object.defineProperty(exports, "RoutingConnectionProvider", { enumerable: true, get: function () { return __importDefault(connection_provider_routing_1).default; } });
}(connectionProvider));

(function (exports) {
/**
 * 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 __createBinding = (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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.packstream = exports.channel = exports.buf = exports.bolt = exports.loadBalancing = void 0;
exports.loadBalancing = __importStar(loadBalancing);
exports.bolt = __importStar(bolt);
exports.buf = __importStar(buf);
exports.channel = __importStar(channel);
exports.packstream = __importStar(packstream);
__exportStar(connectionProvider, exports);
}(lib));

(function (exports) {
var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathSegment = exports.Path = exports.UnboundRelationship = exports.Relationship = exports.Node = exports.Record = exports.ServerInfo = exports.GqlStatusObject = exports.Notification = exports.QueryStatistics = exports.ProfiledPlan = exports.Plan = exports.ResultSummary = exports.RxResult = exports.RxManagedTransaction = exports.RxTransaction = exports.RxSession = exports.EagerResult = exports.Result = exports.ManagedTransaction = exports.Transaction = exports.Session = exports.Driver = exports.temporal = exports.spatial = exports.graph = exports.error = exports.routing = exports.session = exports.types = exports.logging = exports.auth = exports.isRetriableError = exports.Neo4jError = exports.integer = exports.isUnboundRelationship = exports.isRelationship = exports.isPathSegment = exports.isPath = exports.isNode = exports.isDateTime = exports.isLocalDateTime = exports.isDate = exports.isTime = exports.isLocalTime = exports.isDuration = exports.isPoint = exports.isInt = exports.int = exports.authTokenManagers = void 0;
exports.clientCertificateProviders = exports.notificationFilterMinimumSeverityLevel = exports.notificationFilterDisabledClassification = exports.notificationFilterDisabledCategory = exports.notificationSeverityLevel = exports.notificationClassification = exports.notificationCategory = exports.resultTransformers = exports.bookmarkManager = exports.DateTime = exports.LocalDateTime = exports.Date = exports.Time = exports.LocalTime = exports.Duration = exports.Integer = exports.Point = void 0;
exports.driver = driver;
exports.hasReachableServer = hasReachableServer;
/**
 * 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 driver_1 = driver$1;
Object.defineProperty(exports, "Driver", { enumerable: true, get: function () { return driver_1.Driver; } });
var version_1 = __importDefault(version$1);
var neo4j_driver_core_1 = lib$1;
Object.defineProperty(exports, "authTokenManagers", { enumerable: true, get: function () { return neo4j_driver_core_1.authTokenManagers; } });
Object.defineProperty(exports, "Neo4jError", { enumerable: true, get: function () { return neo4j_driver_core_1.Neo4jError; } });
Object.defineProperty(exports, "isRetriableError", { enumerable: true, get: function () { return neo4j_driver_core_1.isRetriableError; } });
Object.defineProperty(exports, "error", { enumerable: true, get: function () { return neo4j_driver_core_1.error; } });
Object.defineProperty(exports, "Integer", { enumerable: true, get: function () { return neo4j_driver_core_1.Integer; } });
Object.defineProperty(exports, "int", { enumerable: true, get: function () { return neo4j_driver_core_1.int; } });
Object.defineProperty(exports, "isInt", { enumerable: true, get: function () { return neo4j_driver_core_1.isInt; } });
Object.defineProperty(exports, "isPoint", { enumerable: true, get: function () { return neo4j_driver_core_1.isPoint; } });
Object.defineProperty(exports, "Point", { enumerable: true, get: function () { return neo4j_driver_core_1.Point; } });
Object.defineProperty(exports, "Date", { enumerable: true, get: function () { return neo4j_driver_core_1.Date; } });
Object.defineProperty(exports, "DateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.DateTime; } });
Object.defineProperty(exports, "Duration", { enumerable: true, get: function () { return neo4j_driver_core_1.Duration; } });
Object.defineProperty(exports, "isDate", { enumerable: true, get: function () { return neo4j_driver_core_1.isDate; } });
Object.defineProperty(exports, "isDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isDateTime; } });
Object.defineProperty(exports, "isDuration", { enumerable: true, get: function () { return neo4j_driver_core_1.isDuration; } });
Object.defineProperty(exports, "isLocalDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isLocalDateTime; } });
Object.defineProperty(exports, "isLocalTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isLocalTime; } });
Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return neo4j_driver_core_1.isNode; } });
Object.defineProperty(exports, "isPath", { enumerable: true, get: function () { return neo4j_driver_core_1.isPath; } });
Object.defineProperty(exports, "isPathSegment", { enumerable: true, get: function () { return neo4j_driver_core_1.isPathSegment; } });
Object.defineProperty(exports, "isRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.isRelationship; } });
Object.defineProperty(exports, "isTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isTime; } });
Object.defineProperty(exports, "isUnboundRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.isUnboundRelationship; } });
Object.defineProperty(exports, "LocalDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.LocalDateTime; } });
Object.defineProperty(exports, "LocalTime", { enumerable: true, get: function () { return neo4j_driver_core_1.LocalTime; } });
Object.defineProperty(exports, "Time", { enumerable: true, get: function () { return neo4j_driver_core_1.Time; } });
Object.defineProperty(exports, "Node", { enumerable: true, get: function () { return neo4j_driver_core_1.Node; } });
Object.defineProperty(exports, "Path", { enumerable: true, get: function () { return neo4j_driver_core_1.Path; } });
Object.defineProperty(exports, "PathSegment", { enumerable: true, get: function () { return neo4j_driver_core_1.PathSegment; } });
Object.defineProperty(exports, "Relationship", { enumerable: true, get: function () { return neo4j_driver_core_1.Relationship; } });
Object.defineProperty(exports, "UnboundRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.UnboundRelationship; } });
Object.defineProperty(exports, "Record", { enumerable: true, get: function () { return neo4j_driver_core_1.Record; } });
Object.defineProperty(exports, "ResultSummary", { enumerable: true, get: function () { return neo4j_driver_core_1.ResultSummary; } });
Object.defineProperty(exports, "Plan", { enumerable: true, get: function () { return neo4j_driver_core_1.Plan; } });
Object.defineProperty(exports, "ProfiledPlan", { enumerable: true, get: function () { return neo4j_driver_core_1.ProfiledPlan; } });
Object.defineProperty(exports, "QueryStatistics", { enumerable: true, get: function () { return neo4j_driver_core_1.QueryStatistics; } });
Object.defineProperty(exports, "Notification", { enumerable: true, get: function () { return neo4j_driver_core_1.Notification; } });
Object.defineProperty(exports, "GqlStatusObject", { enumerable: true, get: function () { return neo4j_driver_core_1.GqlStatusObject; } });
Object.defineProperty(exports, "ServerInfo", { enumerable: true, get: function () { return neo4j_driver_core_1.ServerInfo; } });
Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return neo4j_driver_core_1.Result; } });
Object.defineProperty(exports, "EagerResult", { enumerable: true, get: function () { return neo4j_driver_core_1.EagerResult; } });
Object.defineProperty(exports, "auth", { enumerable: true, get: function () { return neo4j_driver_core_1.auth; } });
Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return neo4j_driver_core_1.Session; } });
Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return neo4j_driver_core_1.Transaction; } });
Object.defineProperty(exports, "ManagedTransaction", { enumerable: true, get: function () { return neo4j_driver_core_1.ManagedTransaction; } });
Object.defineProperty(exports, "bookmarkManager", { enumerable: true, get: function () { return neo4j_driver_core_1.bookmarkManager; } });
Object.defineProperty(exports, "routing", { enumerable: true, get: function () { return neo4j_driver_core_1.routing; } });
Object.defineProperty(exports, "resultTransformers", { enumerable: true, get: function () { return neo4j_driver_core_1.resultTransformers; } });
Object.defineProperty(exports, "notificationCategory", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationCategory; } });
Object.defineProperty(exports, "notificationClassification", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationClassification; } });
Object.defineProperty(exports, "notificationSeverityLevel", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationSeverityLevel; } });
Object.defineProperty(exports, "notificationFilterDisabledCategory", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationFilterDisabledCategory; } });
Object.defineProperty(exports, "notificationFilterDisabledClassification", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationFilterDisabledClassification; } });
Object.defineProperty(exports, "notificationFilterMinimumSeverityLevel", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationFilterMinimumSeverityLevel; } });
Object.defineProperty(exports, "clientCertificateProviders", { enumerable: true, get: function () { return neo4j_driver_core_1.clientCertificateProviders; } });
var neo4j_driver_bolt_connection_1 = lib;
var session_rx_1 = __importDefault(sessionRx);
exports.RxSession = session_rx_1.default;
var transaction_rx_1 = __importDefault(transactionRx);
exports.RxTransaction = transaction_rx_1.default;
var transaction_managed_rx_1 = __importDefault(transactionManagedRx);
exports.RxManagedTransaction = transaction_managed_rx_1.default;
var result_rx_1 = __importDefault(resultRx);
exports.RxResult = result_rx_1.default;
var _a = neo4j_driver_core_1.internal.util, ENCRYPTION_ON = _a.ENCRYPTION_ON, assertString = _a.assertString, isEmptyObjectOrNull = _a.isEmptyObjectOrNull, ServerAddress = neo4j_driver_core_1.internal.serverAddress.ServerAddress, urlUtil = neo4j_driver_core_1.internal.urlUtil;
var USER_AGENT = 'neo4j-javascript/' + version_1.default;
function isAuthTokenManager(value) {
    return typeof value === 'object' &&
        value != null &&
        'getToken' in value &&
        'handleSecurityException' in value &&
        typeof value.getToken === 'function' &&
        typeof value.handleSecurityException === 'function';
}
function createAuthManager(authTokenOrManager) {
    if (isAuthTokenManager(authTokenOrManager)) {
        return authTokenOrManager;
    }
    var authToken = authTokenOrManager;
    // Sanitize authority token. Nicer error from server when a scheme is set.
    authToken = authToken || {};
    authToken.scheme = authToken.scheme || 'none';
    return (0, neo4j_driver_core_1.staticAuthTokenManager)({ authToken: authToken });
}
/**
 * Construct a new Neo4j Driver. This is your main entry point for this
 * library.
 *
 * @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost"
 * @param {Map<string,string>} authToken Authentication credentials. See {@link auth} for helpers.
 * @param {Config} config Configuration object.
 * @returns {Driver}
 */
function driver(url, authToken, config) {
    if (config === void 0) { config = {}; }
    assertString(url, 'Bolt URL');
    var parsedUrl = urlUtil.parseDatabaseUrl(url);
    // Determine encryption/trust options from the URL.
    var routing = false;
    var encrypted = false;
    var trust;
    switch (parsedUrl.scheme) {
        case 'bolt':
            break;
        case 'bolt+s':
            encrypted = true;
            trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES';
            break;
        case 'bolt+ssc':
            encrypted = true;
            trust = 'TRUST_ALL_CERTIFICATES';
            break;
        case 'neo4j':
            routing = true;
            break;
        case 'neo4j+s':
            encrypted = true;
            trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES';
            routing = true;
            break;
        case 'neo4j+ssc':
            encrypted = true;
            trust = 'TRUST_ALL_CERTIFICATES';
            routing = true;
            break;
        default:
            throw new Error("Unknown scheme: ".concat(parsedUrl.scheme));
    }
    // Encryption enabled on URL, propagate trust to the config.
    if (encrypted) {
        // Check for configuration conflict between URL and config.
        if ('encrypted' in config || 'trust' in config) {
            throw new Error('Encryption/trust can only be configured either through URL or config, not both');
        }
        config.encrypted = ENCRYPTION_ON;
        config.trust = trust;
        config.clientCertificate = (0, neo4j_driver_core_1.resolveCertificateProvider)(config.clientCertificate);
    }
    var authTokenManager = createAuthManager(authToken);
    // Use default user agent or user agent specified by user.
    config.userAgent = config.userAgent || USER_AGENT;
    config.boltAgent = neo4j_driver_core_1.internal.boltAgent.fromVersion(version_1.default);
    var address = ServerAddress.fromUrl(parsedUrl.hostAndPort);
    var meta = {
        address: address,
        typename: routing ? 'Routing' : 'Direct',
        routing: routing
    };
    return new driver_1.Driver(meta, config, createConnectionProviderFunction());
    function createConnectionProviderFunction() {
        if (routing) {
            return function (id, config, log, hostNameResolver) {
                return new neo4j_driver_bolt_connection_1.RoutingConnectionProvider({
                    id: id,
                    config: config,
                    log: log,
                    hostNameResolver: hostNameResolver,
                    authTokenManager: authTokenManager,
                    address: address,
                    userAgent: config.userAgent,
                    boltAgent: config.boltAgent,
                    routingContext: parsedUrl.query
                });
            };
        }
        else {
            if (!isEmptyObjectOrNull(parsedUrl.query)) {
                throw new Error("Parameters are not supported with none routed scheme. Given URL: '".concat(url, "'"));
            }
            return function (id, config, log) {
                return new neo4j_driver_bolt_connection_1.DirectConnectionProvider({
                    id: id,
                    config: config,
                    log: log,
                    authTokenManager: authTokenManager,
                    address: address,
                    userAgent: config.userAgent,
                    boltAgent: config.boltAgent
                });
            };
        }
    }
}
/**
 * Verifies if the driver can reach a server at the given url.
 *
 * @experimental
 * @since 5.0.0
 * @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost"
 * @param {object} config Configuration object. See the {@link driver}
 * @returns {true} When the server is reachable
 * @throws {Error} When the server is not reachable or the url is invalid
 */
function hasReachableServer(url, config) {
    return __awaiter(this, void 0, void 0, function () {
        var nonLoggedDriver;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    nonLoggedDriver = driver(url, { scheme: 'none', principal: '', credentials: '' }, config);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, , 3, 5]);
                    return [4 /*yield*/, nonLoggedDriver.getNegotiatedProtocolVersion()];
                case 2:
                    _a.sent();
                    return [2 /*return*/, true];
                case 3: return [4 /*yield*/, nonLoggedDriver.close()];
                case 4:
                    _a.sent();
                    return [7 /*endfinally*/];
                case 5: return [2 /*return*/];
            }
        });
    });
}
/**
 * Object containing predefined logging configurations. These are expected to be used as values of the driver config's `logging` property.
 * @property {function(level: ?string): object} console the function to create a logging config that prints all messages to `console.log` with
 * timestamp, level and message. It takes an optional `level` parameter which represents the maximum log level to be logged. Default value is 'info'.
 */
var logging = {
    console: function (level) {
        return {
            level: level,
            logger: function (level, message) {
                return console.log("".concat(commonjsGlobal.Date.now(), " ").concat(level.toUpperCase(), " ").concat(message));
            }
        };
    }
};
exports.logging = logging;
/**
 * Object containing constructors for all neo4j types.
 */
var types = {
    Node: neo4j_driver_core_1.Node,
    Relationship: neo4j_driver_core_1.Relationship,
    UnboundRelationship: neo4j_driver_core_1.UnboundRelationship,
    PathSegment: neo4j_driver_core_1.PathSegment,
    Path: neo4j_driver_core_1.Path,
    Result: neo4j_driver_core_1.Result,
    EagerResult: neo4j_driver_core_1.EagerResult,
    ResultSummary: neo4j_driver_core_1.ResultSummary,
    Record: neo4j_driver_core_1.Record,
    Point: neo4j_driver_core_1.Point,
    Date: neo4j_driver_core_1.Date,
    DateTime: neo4j_driver_core_1.DateTime,
    Duration: neo4j_driver_core_1.Duration,
    LocalDateTime: neo4j_driver_core_1.LocalDateTime,
    LocalTime: neo4j_driver_core_1.LocalTime,
    Time: neo4j_driver_core_1.Time,
    Integer: neo4j_driver_core_1.Integer
};
exports.types = types;
/**
 * Object containing string constants representing session access modes.
 */
var session = {
    READ: driver_1.READ,
    WRITE: driver_1.WRITE
};
exports.session = session;
/**
 * Object containing functions to work with {@link Integer} objects.
 */
var integer = {
    toNumber: neo4j_driver_core_1.toNumber,
    toString: neo4j_driver_core_1.toString,
    inSafeRange: neo4j_driver_core_1.inSafeRange
};
exports.integer = integer;
/**
 * Object containing functions to work with spatial types, like {@link Point}.
 */
var spatial = {
    isPoint: neo4j_driver_core_1.isPoint
};
exports.spatial = spatial;
/**
 * Object containing functions to work with temporal types, like {@link Time} or {@link Duration}.
 */
var temporal = {
    isDuration: neo4j_driver_core_1.isDuration,
    isLocalTime: neo4j_driver_core_1.isLocalTime,
    isTime: neo4j_driver_core_1.isTime,
    isDate: neo4j_driver_core_1.isDate,
    isLocalDateTime: neo4j_driver_core_1.isLocalDateTime,
    isDateTime: neo4j_driver_core_1.isDateTime
};
exports.temporal = temporal;
/**
 * Object containing functions to work with graph types, like {@link Node} or {@link Relationship}.
 */
var graph = {
    isNode: neo4j_driver_core_1.isNode,
    isPath: neo4j_driver_core_1.isPath,
    isPathSegment: neo4j_driver_core_1.isPathSegment,
    isRelationship: neo4j_driver_core_1.isRelationship,
    isUnboundRelationship: neo4j_driver_core_1.isUnboundRelationship
};
exports.graph = graph;
/**
 * @private
 */
var forExport = {
    authTokenManagers: neo4j_driver_core_1.authTokenManagers,
    driver: driver,
    hasReachableServer: hasReachableServer,
    int: neo4j_driver_core_1.int,
    isInt: neo4j_driver_core_1.isInt,
    isPoint: neo4j_driver_core_1.isPoint,
    isDuration: neo4j_driver_core_1.isDuration,
    isLocalTime: neo4j_driver_core_1.isLocalTime,
    isTime: neo4j_driver_core_1.isTime,
    isDate: neo4j_driver_core_1.isDate,
    isLocalDateTime: neo4j_driver_core_1.isLocalDateTime,
    isDateTime: neo4j_driver_core_1.isDateTime,
    isNode: neo4j_driver_core_1.isNode,
    isPath: neo4j_driver_core_1.isPath,
    isPathSegment: neo4j_driver_core_1.isPathSegment,
    isRelationship: neo4j_driver_core_1.isRelationship,
    isUnboundRelationship: neo4j_driver_core_1.isUnboundRelationship,
    integer: integer,
    Neo4jError: neo4j_driver_core_1.Neo4jError,
    isRetriableError: neo4j_driver_core_1.isRetriableError,
    auth: neo4j_driver_core_1.auth,
    logging: logging,
    types: types,
    session: session,
    routing: neo4j_driver_core_1.routing,
    error: neo4j_driver_core_1.error,
    graph: graph,
    spatial: spatial,
    temporal: temporal,
    Driver: driver_1.Driver,
    Session: neo4j_driver_core_1.Session,
    Transaction: neo4j_driver_core_1.Transaction,
    ManagedTransaction: neo4j_driver_core_1.ManagedTransaction,
    Result: neo4j_driver_core_1.Result,
    EagerResult: neo4j_driver_core_1.EagerResult,
    RxSession: session_rx_1.default,
    RxTransaction: transaction_rx_1.default,
    RxManagedTransaction: transaction_managed_rx_1.default,
    RxResult: result_rx_1.default,
    ResultSummary: neo4j_driver_core_1.ResultSummary,
    Plan: neo4j_driver_core_1.Plan,
    ProfiledPlan: neo4j_driver_core_1.ProfiledPlan,
    QueryStatistics: neo4j_driver_core_1.QueryStatistics,
    Notification: neo4j_driver_core_1.Notification,
    GqlStatusObject: neo4j_driver_core_1.GqlStatusObject,
    ServerInfo: neo4j_driver_core_1.ServerInfo,
    Record: neo4j_driver_core_1.Record,
    Node: neo4j_driver_core_1.Node,
    Relationship: neo4j_driver_core_1.Relationship,
    UnboundRelationship: neo4j_driver_core_1.UnboundRelationship,
    Path: neo4j_driver_core_1.Path,
    PathSegment: neo4j_driver_core_1.PathSegment,
    Point: neo4j_driver_core_1.Point,
    Integer: neo4j_driver_core_1.Integer,
    Duration: neo4j_driver_core_1.Duration,
    LocalTime: neo4j_driver_core_1.LocalTime,
    Time: neo4j_driver_core_1.Time,
    Date: neo4j_driver_core_1.Date,
    LocalDateTime: neo4j_driver_core_1.LocalDateTime,
    DateTime: neo4j_driver_core_1.DateTime,
    bookmarkManager: neo4j_driver_core_1.bookmarkManager,
    resultTransformers: neo4j_driver_core_1.resultTransformers,
    notificationCategory: neo4j_driver_core_1.notificationCategory,
    notificationSeverityLevel: neo4j_driver_core_1.notificationSeverityLevel,
    notificationFilterDisabledCategory: neo4j_driver_core_1.notificationFilterDisabledCategory,
    notificationFilterMinimumSeverityLevel: neo4j_driver_core_1.notificationFilterMinimumSeverityLevel,
    clientCertificateProviders: neo4j_driver_core_1.clientCertificateProviders
};
exports.default = forExport;
}(lib$2));

var index = /*@__PURE__*/getDefaultExportFromCjs(lib$2);

export { index as default };
