/*!
 * NevWare21 Solutions LLC - ts-async, 0.6.1
 * https://github.com/nevware21/ts-async
 * Copyright (c) NevWare21 Solutions LLC and contributors. All rights reserved.
 * Licensed under the MIT license.
 */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.nevware21 = global.nevware21 || {}, global.nevware21["ts-async"] = {})));
})(this, (function (exports) { 'use strict';

    /*#__NO_SIDE_EFFECTS__*/
    function _pureAssign$1(func1, func2) {
        return func1 || func2;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _pureRef(value, name) {
        return value !== null && value !== undefined ? value[name] : undefined;
    }
    var UNDEF_VALUE = undefined;
    var NULL_VALUE = null;
    var EMPTY = "";
    var FUNCTION = "function";
    var OBJECT = "object";
    var PROTOTYPE = "prototype";
    var __PROTO__ = "__proto__";
    var UNDEFINED = "undefined";
    var CONSTRUCTOR = "constructor";
    var SYMBOL = "Symbol";
    var LENGTH = "length";
    var NAME = "name";
    var CALL = "call";
    var TO_STRING = "toString";
    var GET_OWN_PROPERTY_DESCRIPTOR = "getOwnPropertyDescriptor";
    var ObjClass = (/*#__PURE__*/_pureAssign$1(Object));
    var ObjProto = (/*#__PURE__*/_pureRef(ObjClass, PROTOTYPE));
    var StrCls = (/*#__PURE__*/_pureAssign$1(String));
    var MathCls = (/*#__PURE__*/_pureAssign$1(Math));
    var ArrCls = (/*#__PURE__*/_pureAssign$1(Array));
    var ArrProto = (/*#__PURE__*/_pureRef(ArrCls, PROTOTYPE));
    var ArrSlice = (/*#__PURE__*/_pureRef(ArrProto, "slice"));
    var POLYFILL_TAG = "_polyfill";
    var POLYFILL_TYPE_NAME = "__nw21$polytype__";
    function safe(func, argArray) {
        try {
            return {
                v: func.apply(this, argArray)
            };
        }
        catch (e) {
            return { e: e };
        }
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createIs(theType) {
        return function (value) {
            return typeof value === theType;
        };
    }
    /*#__NO_SIDE_EFFECTS__*/
    function objToString(value) {
        return ObjProto[TO_STRING].call(value);
    }
    /*#__NO_SIDE_EFFECTS__*/
    function isUndefined(value) {
        return typeof value === UNDEFINED || value === UNDEFINED;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function isStrictUndefined(arg) {
        return arg === UNDEF_VALUE;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function isNullOrUndefined(value) {
        return value === NULL_VALUE || isUndefined(value);
    }
    /*#__NO_SIDE_EFFECTS__*/
    function isStrictNullOrUndefined(value) {
        return value === NULL_VALUE || value === UNDEF_VALUE;
    }
    var isFunction = (/*#__PURE__*/_createIs(FUNCTION));
    /*#__NO_SIDE_EFFECTS__*/
    function isObject(value) {
        if (!value && isNullOrUndefined(value)) {
            return false;
        }
        return !!value && typeof value === OBJECT;
    }
    var isArray = (/*#__PURE__*/_pureRef(ArrCls, "isArray"));
    var isNumber = (/*#__PURE__*/_createIs("number"));
    /*#__NO_SIDE_EFFECTS__*/
    function isPromiseLike(value) {
        return !!(value && value.then && isFunction(value.then));
    }
    function _returnNothing() {
        return;
    }
    var asString = (/*#__PURE__*/_pureAssign$1(StrCls));
    var ERROR_TYPE = "[object Error]";
    /*#__NO_SIDE_EFFECTS__*/
    function dumpObj(object, format) {
        var propertyValueDump = EMPTY;
        var objType = ObjProto[TO_STRING][CALL](object);
        if (objType === ERROR_TYPE) {
            object = { stack: asString(object.stack), message: asString(object.message), name: asString(object.name) };
        }
        try {
            propertyValueDump = JSON.stringify(object, NULL_VALUE, format ? ((typeof format === "number") ? format : 4) : UNDEF_VALUE);
            propertyValueDump = (propertyValueDump ? propertyValueDump.replace(/"(\w+)"\s*:\s{0,1}/g, "$1: ") : NULL_VALUE) || asString(object);
        }
        catch (e) {
            propertyValueDump = " - " + dumpObj(e, format);
        }
        return objType + ": " + propertyValueDump;
    }
    function throwTypeError(message) {
        throw new TypeError(message);
    }
    function throwRangeError(message) {
        throw new RangeError(message);
    }
    function _throwIfNullOrUndefined(obj) {
        if (isStrictNullOrUndefined(obj)) {
            throwTypeError("Cannot convert undefined or null to object");
        }
    }
    /*#__NO_SIDE_EFFECTS__*/
    function objHasOwnProperty(obj, prop) {
        return !!obj && ObjProto.hasOwnProperty[CALL](obj, prop);
    }
    var _objGetOwnPropertyDescriptor$2 = (/*#__PURE__*/_pureAssign$1((/*#__PURE__*/_pureRef(ObjClass, GET_OWN_PROPERTY_DESCRIPTOR)), _returnNothing));
    var objHasOwn = (/*#__PURE__*/_pureAssign$1((/*#__PURE__*/_pureRef(ObjClass, "hasOwn")), polyObjHasOwn));
    /*#__NO_SIDE_EFFECTS__*/
    function polyObjHasOwn(obj, prop) {
        _throwIfNullOrUndefined(obj);
        return objHasOwnProperty(obj, prop) || !!_objGetOwnPropertyDescriptor$2(obj, prop);
    }
    function objForEachKey(theObject, callbackfn, thisArg) {
        if (theObject && (isObject(theObject) || isFunction(theObject))) {
            for (var prop in theObject) {
                if (objHasOwn(theObject, prop)) {
                    if (callbackfn[CALL](isStrictNullOrUndefined(thisArg) ? theObject : thisArg, prop, theObject[prop]) === -1) {
                        break;
                    }
                }
            }
        }
    }
    function arrForEach(theArray, callbackfn, thisArg) {
        if (theArray) {
            var len = theArray[LENGTH] >>> 0;
            for (var idx = 0; idx < len; idx++) {
                if (idx in theArray) {
                    if (callbackfn[CALL](isStrictNullOrUndefined(thisArg) ? theArray : thisArg, theArray[idx], idx, theArray) === -1) {
                        break;
                    }
                }
            }
        }
    }
    var _unwrapFunction = _unwrapFunctionWithPoly;
    /*#__NO_SIDE_EFFECTS__*/
    function _unwrapFunctionWithPoly(funcName, clsProto, polyFunc) {
        var clsFn = clsProto ? clsProto[funcName] : NULL_VALUE;
        return function (thisArg) {
            var theFunc = (thisArg ? thisArg[funcName] : NULL_VALUE) || clsFn;
            if (theFunc || polyFunc) {
                var theArgs = arguments;
                return (theFunc || polyFunc).apply(thisArg, theFunc ? ArrSlice[CALL](theArgs, 1) : theArgs);
            }
            throwTypeError("\"" + asString(funcName) + "\" not defined for " + dumpObj(thisArg));
        };
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _unwrapProp(propName) {
        return function (thisArg) {
            return thisArg[propName];
        };
    }
    var _objGetOwnPropertyDescriptor$1 = (/*#__PURE__*/_pureAssign$1((/*#__PURE__*/_pureRef(ObjClass, GET_OWN_PROPERTY_DESCRIPTOR)), _returnNothing));
    var propMap = {
        e: "enumerable",
        c: "configurable",
        v: "value",
        w: "writable",
        g: "get",
        s: "set"
    };
    /*#__NO_SIDE_EFFECTS__*/
    function _createProp(value) {
        var prop = {};
        prop[propMap["c"]] = true;
        prop[propMap["e"]] = true;
        if (value.l) {
            prop.get = function () { return value.l.v; };
            var desc = _objGetOwnPropertyDescriptor$1(value.l, "v");
            if (desc && desc.set) {
                prop.set = function (newValue) {
                    value.l.v = newValue;
                };
            }
        }
        objForEachKey(value, function (key, value) {
            prop[propMap[key]] = isStrictUndefined(value) ? prop[propMap[key]] : value;
        });
        return prop;
    }
    var objDefineProp = (/*#__PURE__*/_pureRef(ObjClass, "defineProperty"));
    var objDefineProperties = (/*#__PURE__*/_pureRef(ObjClass, "defineProperties"));
    function objDefine(target, key, propDesc) {
        return objDefineProp(target, key, _createProp(propDesc));
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createKeyValueMap(values, keyType, valueType, completeFn, writable) {
        var theMap = {};
        objForEachKey(values, function (key, value) {
            _assignMapValue(theMap, key, key);
            _assignMapValue(theMap, value, key);
        });
        return completeFn ? completeFn(theMap) : theMap;
    }
    function _assignMapValue(theMap, key, value, writable) {
        objDefineProp(theMap, key, {
            value: value,
            enumerable: true,
            writable: false
        });
    }
    var _objFreeze = (/*#__PURE__*/_pureRef(ObjClass, "freeze"));
    function _doNothing(value) {
        return value;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _getProto(value) {
        _throwIfNullOrUndefined(value);
        return value[__PROTO__] || NULL_VALUE;
    }
    var objFreeze = (/*#__PURE__*/_pureAssign$1(_objFreeze, _doNothing));
    var objGetPrototypeOf = (/*#__PURE__*/_pureAssign$1((/*#__PURE__*/_pureRef(ObjClass, "getPrototypeOf")), _getProto));
    /*#__NO_SIDE_EFFECTS__*/
    function createEnumKeyMap(values) {
        return _createKeyValueMap(values, 0 , 0 , objFreeze);
    }
    var _wellKnownSymbolMap = (/*#__PURE__*/createEnumKeyMap({
        asyncIterator: 0 ,
        hasInstance: 1 ,
        isConcatSpreadable: 2 ,
        iterator: 3 ,
        match: 4 ,
        matchAll: 5 ,
        replace: 6 ,
        search: 7 ,
        species: 8 ,
        split: 9 ,
        toPrimitive: 10 ,
        toStringTag: 11 ,
        unscopables: 12
    }));
    var GLOBAL_CONFIG_KEY = "__tsUtils$gblCfg";
    var _globalCfg;
    /*#__NO_SIDE_EFFECTS__*/
    function _getGlobalValue() {
        var result;
        if (typeof globalThis !== UNDEFINED) {
            result = globalThis;
        }
        if (!result && typeof self !== UNDEFINED) {
            result = self;
        }
        if (!result && typeof window !== UNDEFINED) {
            result = window;
        }
        if (!result && typeof global !== UNDEFINED) {
            result = global;
        }
        return result;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _getGlobalConfig() {
        if (!_globalCfg) {
            var gbl = safe(_getGlobalValue).v || {};
            _globalCfg = gbl[GLOBAL_CONFIG_KEY] = gbl[GLOBAL_CONFIG_KEY] || {};
        }
        return _globalCfg;
    }
    function _tagAsPolyfill(target, polyfillTypeName) {
        if (target) {
            safe(function () {
                target[POLYFILL_TAG] = true;
                target[POLYFILL_TYPE_NAME] = polyfillTypeName;
            });
            safe(objDefine, [target, POLYFILL_TAG, {
                    v: true,
                    w: false,
                    e: false
                }]);
            safe(objDefine, [target, POLYFILL_TYPE_NAME, {
                    v: polyfillTypeName,
                    w: false,
                    e: false
                }]);
        }
        return target;
    }
    var objCreate = (/*#__PURE__*/_pureAssign$1((/*#__PURE__*/_pureRef(ObjClass, "create")), polyObjCreate));
    /*#__NO_SIDE_EFFECTS__*/
    function polyObjCreate(obj, properties) {
        var newObj = null;
        function tempFunc() { }
        if (!isStrictNullOrUndefined(obj)) {
            var type = typeof obj;
            if (type !== OBJECT && type !== FUNCTION) {
                throwTypeError("Prototype must be an Object or function: " + dumpObj(obj));
            }
            tempFunc[PROTOTYPE] = obj;
            safe(function () {
                tempFunc[__PROTO__] = obj;
            });
            newObj = new tempFunc();
        }
        else {
            newObj = {};
        }
        if (properties) {
            safe(objDefineProperties, [newObj, properties]);
        }
        return newObj;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function utcNow() {
        return (Date.now || polyUtcNow)();
    }
    /*#__NO_SIDE_EFFECTS__*/
    function polyUtcNow() {
        return new Date().getTime();
    }
    function fnApply(fn, thisArg, argArray) {
        return fn.apply(thisArg, argArray);
    }
    function fnCall(fn, thisArg) {
        return fn.apply(thisArg, ArrSlice[CALL](arguments, 2));
    }
    var _globalLazyTestHooks;
    function _initTestHooks() {
        _globalLazyTestHooks = _getGlobalConfig();
    }
    /*#__NO_SIDE_EFFECTS__*/
    function getLazy(cb, argArray) {
        var lazyValue = {};
        !_globalLazyTestHooks && _initTestHooks();
        lazyValue.b = _globalLazyTestHooks.lzy;
        objDefineProp(lazyValue, "v", {
            configurable: true,
            get: function () {
                var result = fnApply(cb, null, argArray);
                if (!_globalLazyTestHooks.lzy) {
                    objDefineProp(lazyValue, "v", {
                        value: result
                    });
                }
                lazyValue.b = _globalLazyTestHooks.lzy;
                return result;
            }
        });
        return lazyValue;
    }
    var mathRandom = (/*#__PURE__*/_pureRef(MathCls, "random"));
    var _uniqueInstanceId = (/*#__PURE__*/getLazy(function () {
        var value = (utcNow().toString(36).slice(2));
        while (value.length < 16) {
            value += mathRandom().toString(36).slice(2);
        }
        value = value.substring(0, 16);
        return value;
    }));
    var POLY_SYM = "$nw21sym";
    var _polyId = 0;
    var _wellKnownSymbolCache;
    /*#__NO_SIDE_EFFECTS__*/
    function polyNewSymbol(description) {
        var uniqueId = "_" + _polyId++ + "_" + _uniqueInstanceId.v;
        var symString = SYMBOL + "(" + description + ")";
        function _setProp(name, value) {
            objDefine(theSymbol, name, {
                v: value,
                e: false,
                w: false
            });
        }
        var theSymbol = objCreate(null);
        _setProp("description", asString(description));
        _setProp(TO_STRING, function () { return symString + POLY_SYM + uniqueId; });
        _setProp("valueOf", function () { return theSymbol; });
        _setProp("v", symString);
        _setProp("_uid", uniqueId);
        return _tagAsPolyfill(theSymbol, "symbol");
    }
    /*#__NO_SIDE_EFFECTS__*/
    function polyGetKnownSymbol(name) {
        !_wellKnownSymbolCache && (_wellKnownSymbolCache = {});
        var result;
        var knownName = _wellKnownSymbolMap[name];
        if (knownName) {
            result = _wellKnownSymbolCache[knownName] = _wellKnownSymbolCache[knownName] || polyNewSymbol(SYMBOL + "." + knownName);
        }
        return result;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function createCachedValue(value) {
        return objDefineProp({
            toJSON: function () { return value; }
        }, "v", { value: value });
    }
    var WINDOW = "window";
    var _cachedGlobal;
    function _getGlobalInstFn(getFn, theArgs) {
        var cachedValue;
        return function () {
            !_globalLazyTestHooks && _initTestHooks();
            if (!cachedValue || _globalLazyTestHooks.lzy) {
                cachedValue = createCachedValue(safe(getFn, theArgs).v);
            }
            return cachedValue.v;
        };
    }
    function getGlobal(useCached) {
        !_globalLazyTestHooks && _initTestHooks();
        if (!_cachedGlobal || useCached === false || _globalLazyTestHooks.lzy) {
            _cachedGlobal = createCachedValue(safe(_getGlobalValue).v || NULL_VALUE);
        }
        return _cachedGlobal.v;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function getInst(name, useCached) {
        var gbl;
        if (!_cachedGlobal || useCached === false) {
            gbl = getGlobal(useCached);
        }
        else {
            gbl = _cachedGlobal.v;
        }
        if (gbl && gbl[name]) {
            return gbl[name];
        }
        if (name === WINDOW) {
            try {
                return window;
            }
            catch (e) {
            }
        }
        return NULL_VALUE;
    }
    var getDocument = (/*#__PURE__*/_getGlobalInstFn(getInst, ["document"]));
    var getWindow = (/*#__PURE__*/_getGlobalInstFn(getInst, [WINDOW]));
    var isNode = (/*#__PURE__*/_getGlobalInstFn(function () {
        return !!safe(function () {
            var processInst = getInst("process");
            return processInst && (processInst.versions || {}).node;
        }).v;
    }));
    var getQueueMicrotask = (/*#__PURE__*/_getGlobalInstFn(getInst, ["queueMicrotask"]));
    var _symbol;
    /*#__NO_SIDE_EFFECTS__*/
    function _initSymbol() {
        _symbol = (/*#__PURE__*/createCachedValue(safe((getInst), [SYMBOL]).v));
        return _symbol;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function hasSymbol() {
        return !!getSymbol();
    }
    /*#__NO_SIDE_EFFECTS__*/
    function getSymbol() {
        !_globalLazyTestHooks && _initTestHooks();
        return ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol()).v;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function getKnownSymbol(name, noPoly) {
        var knownName = _wellKnownSymbolMap[name];
        !_globalLazyTestHooks && _initTestHooks();
        var sym = ((!_globalLazyTestHooks.lzy ? _symbol : 0) || _initSymbol());
        return sym.v ? sym.v[knownName || name] : (polyGetKnownSymbol(name) );
    }
    /*#__NO_SIDE_EFFECTS__*/
    function isIterator(value) {
        return !!value && isFunction(value.next);
    }
    /*#__NO_SIDE_EFFECTS__*/
    function isIterable(value) {
        return !isStrictNullOrUndefined(value) && isFunction(value[getKnownSymbol(3 )]);
    }
    var _iterSymbol$1;
    function iterForOf(iter, callbackfn, thisArg) {
        if (iter) {
            if (!isIterator(iter)) {
                !_iterSymbol$1 && (_iterSymbol$1 = createCachedValue(getKnownSymbol(3 )));
                iter = iter[_iterSymbol$1.v] ? iter[_iterSymbol$1.v]() : NULL_VALUE;
            }
            if (isIterator(iter)) {
                var err = UNDEF_VALUE;
                var iterResult = UNDEF_VALUE;
                try {
                    var count = 0;
                    while (!(iterResult = iter.next()).done) {
                        if (callbackfn[CALL](isStrictNullOrUndefined(thisArg) ? iter : thisArg, iterResult.value, count, iter) === -1) {
                            break;
                        }
                        count++;
                    }
                }
                catch (failed) {
                    err = { e: failed };
                    if (iter.throw) {
                        iterResult = NULL_VALUE;
                        iter.throw(err);
                    }
                }
                finally {
                    try {
                        if (iterResult && !iterResult.done) {
                            iter.return && iter.return(iterResult);
                        }
                    }
                    finally {
                        if (err) {
                            throw err.e;
                        }
                    }
                }
            }
        }
    }
    var arrIndexOf = (/*#__PURE__*/_unwrapFunction("indexOf", ArrProto));
    function arrSlice(theArray, start, end) {
        return ((theArray ? theArray["slice"] : NULL_VALUE) || ArrSlice).apply(theArray, ArrSlice[CALL](arguments, 1));
    }
    var getLength = (/*#__PURE__*/_unwrapProp(LENGTH));
    var _isProtoArray;
    var objSetPrototypeOf = (/*#__PURE__*/_pureAssign$1((/*#__PURE__*/_pureRef(ObjClass, "setPrototypeOf")), _polyObjSetPrototypeOf));
    function _polyObjSetPrototypeOf(obj, proto) {
        var _a;
        !_isProtoArray && (_isProtoArray = createCachedValue((_a = {}, _a[__PROTO__] = [], _a) instanceof Array));
        _isProtoArray.v ? obj[__PROTO__] = proto : objForEachKey(proto, function (key, value) { return obj[key] = value; });
        return obj;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createCustomError(name, d, b) {
        safe(objDefine, [d, NAME, { v: name, c: true, e: false }]);
        d = objSetPrototypeOf(d, b);
        function __() {
            this[CONSTRUCTOR] = d;
            safe(objDefine, [this, NAME, { v: name, c: true, e: false }]);
        }
        d[PROTOTYPE] = b === NULL_VALUE ? objCreate(b) : (__[PROTOTYPE] = b[PROTOTYPE], new __());
        return d;
    }
    function _setName(baseClass, name) {
        name && (baseClass[NAME] = name);
    }
    /*#__NO_SIDE_EFFECTS__*/
    function createCustomError(name, constructCb, errorBase, superArgsFn) {
        var theBaseClass = Error;
        var orgName = theBaseClass[PROTOTYPE][NAME];
        var captureFn = Error.captureStackTrace;
        return _createCustomError(name, function () {
            var _this = this;
            var theArgs = arguments;
            try {
                safe(_setName, [theBaseClass, name]);
                var _self = fnApply(theBaseClass, _this, superArgsFn ? superArgsFn(theArgs) : ArrSlice[CALL](theArgs)) || _this;
                if (_self !== _this) {
                    var orgProto = objGetPrototypeOf(_this);
                    if (orgProto !== objGetPrototypeOf(_self)) {
                        objSetPrototypeOf(_self, orgProto);
                    }
                }
                captureFn && captureFn(_self, _this[CONSTRUCTOR]);
                constructCb && constructCb(_self, theArgs);
                return _self;
            }
            finally {
                safe(_setName, [theBaseClass, orgName]);
            }
        }, theBaseClass);
    }
    var _perf;
    /*#__NO_SIDE_EFFECTS__*/
    function getPerformance() {
        !_globalLazyTestHooks && _initTestHooks();
        if (!_perf || _globalLazyTestHooks.lzy) {
            _perf = createCachedValue(safe((getInst), ["performance"]).v);
        }
        return _perf.v;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function perfNow() {
        var perf = getPerformance();
        if (perf && perf.now) {
            return perf.now();
        }
        return utcNow();
    }
    /*#__NO_SIDE_EFFECTS__*/
    function elapsedTime(startTime) {
        return perfNow() - startTime;
    }
    var REF = "ref";
    var UNREF = "unref";
    var HAS_REF = "hasRef";
    var ENABLED = "enabled";
    /*#__NO_SIDE_EFFECTS__*/
    function _createTimerHandler(startTimer, refreshFn, cancelFn) {
        var ref = true;
        var timerId = startTimer ? refreshFn(NULL_VALUE) : NULL_VALUE;
        var theTimerHandler;
        function _unref() {
            ref = false;
            timerId && timerId[UNREF] && timerId[UNREF]();
            return theTimerHandler;
        }
        function _cancel() {
            timerId && cancelFn(timerId);
            timerId = NULL_VALUE;
        }
        function _refresh() {
            timerId = refreshFn(timerId);
            if (!ref) {
                _unref();
            }
            return theTimerHandler;
        }
        function _setEnabled(value) {
            !value && timerId && _cancel();
            value && !timerId && _refresh();
        }
        theTimerHandler = {
            cancel: _cancel,
            refresh: _refresh
        };
        theTimerHandler[HAS_REF] = function () {
            if (timerId && timerId[HAS_REF]) {
                return timerId[HAS_REF]();
            }
            return ref;
        };
        theTimerHandler[REF] = function () {
            ref = true;
            timerId && timerId[REF] && timerId[REF]();
            return theTimerHandler;
        };
        theTimerHandler[UNREF] = _unref;
        theTimerHandler = objDefineProp(theTimerHandler, ENABLED, {
            get: function () { return !!timerId; },
            set: _setEnabled
        });
        return {
            h: theTimerHandler,
            dn: function () {
                timerId = NULL_VALUE;
            }
        };
    }
    var _setTimeoutFn;
    var _clearTimeoutFn;
    var _microtaskCallback;
    function _resolveTimeoutFn(timeoutFn) {
        var result = isFunction(timeoutFn) ? timeoutFn : _setTimeoutFn;
        if (!result) {
            var globalOverrides = _getGlobalConfig().tmOut || [];
            if (isArray(globalOverrides) && globalOverrides.length > 0 && isFunction(globalOverrides[0])) {
                result = globalOverrides[0];
            }
        }
        return result || setTimeout;
    }
    function _resolveClearTimeoutFn(timeoutFn) {
        var result = isFunction(timeoutFn) ? timeoutFn : _clearTimeoutFn;
        if (!result) {
            var globalOverrides = _getGlobalConfig().tmOut || [];
            if (isArray(globalOverrides) && globalOverrides.length > 1 && isFunction(globalOverrides[1])) {
                result = globalOverrides[1];
            }
        }
        return result || clearTimeout;
    }
    function _createTimeoutWith(startTimer, overrideFn, theArgs) {
        var isArr = isArray(overrideFn);
        var len = isArr ? overrideFn.length : 0;
        var setFn = _resolveTimeoutFn(len > 0 ? overrideFn[0] : (!isArr ? overrideFn : UNDEF_VALUE));
        var clearFn = _resolveClearTimeoutFn(len > 1 ? overrideFn[1] : UNDEF_VALUE);
        var timerFn = theArgs[0];
        theArgs[0] = function () {
            var microTasksFn = _microtaskCallback;
            if (microTasksFn) {
                _microtaskCallback = UNDEF_VALUE;
                microTasksFn();
            }
            handler.dn();
            fnApply(timerFn, UNDEF_VALUE, ArrSlice[CALL](arguments));
        };
        var handler = _createTimerHandler(startTimer, function (timerId) {
            if (timerId) {
                if (timerId.refresh) {
                    timerId.refresh();
                    return timerId;
                }
                fnApply(clearFn, UNDEF_VALUE, [timerId]);
            }
            return fnApply(setFn, UNDEF_VALUE, theArgs);
        }, function (timerId) {
            fnApply(clearFn, UNDEF_VALUE, [timerId]);
        });
        return handler.h;
    }
    function _setMicrotaskCallback(queueFn) {
        if (!_microtaskCallback && isFunction(queueFn)) {
            _microtaskCallback = queueFn;
        }
    }
    function scheduleTimeout(callback, timeout) {
        return _createTimeoutWith(true, UNDEF_VALUE, ArrSlice[CALL](arguments));
    }
    var _defaultIdleTimeout$1 = 100;
    var _maxExecutionTime = 50;
    /*#__NO_SIDE_EFFECTS__*/
    function hasIdleCallback() {
        return !!getIdleCallback();
    }
    var getIdleCallback = (/*#__PURE__*/_getGlobalInstFn(getInst, ["requestIdleCallback"]));
    var getCancelIdleCallback = (/*#__PURE__*/_getGlobalInstFn(getInst, ["cancelIdleCallback"]));
    function scheduleIdleCallback(callback, options) {
        function _createDeadline(timedOut) {
            var startTime = perfNow();
            return {
                didTimeout: timedOut,
                timeRemaining: function () {
                    return _maxExecutionTime - elapsedTime(startTime);
                }
            };
        }
        if (hasIdleCallback()) {
            var handler_1 = _createTimerHandler(true, function (idleId) {
                idleId && getCancelIdleCallback()(idleId);
                return getIdleCallback()(function (deadline) {
                    handler_1.dn();
                    callback(deadline || _createDeadline(false));
                }, options);
            }, function (idleId) {
                getCancelIdleCallback()(idleId);
            });
            return handler_1.h;
        }
        var timeout = (options || {}).timeout;
        if (isUndefined(timeout)) {
            timeout = _defaultIdleTimeout$1;
        }
        return scheduleTimeout(function () {
            callback(_createDeadline(true));
        }, timeout);
    }
    function _createCancellableTask(callback, queueFn, maxQueuedTasks) {
        var handler;
        var currentTask = 0;
        function _scheduleTask() {
            var taskId = ++currentTask;
            var queued = queueFn(function () {
                if (taskId === currentTask) {
                    handler.dn();
                    callback();
                }
            }, maxQueuedTasks);
            if (queued === false) {
                handler.dn();
            }
            return taskId;
        }
        function _cancelTask(taskId) {
            if (taskId === currentTask) {
                currentTask++;
            }
        }
        handler = _createTimerHandler(false, _scheduleTask, _cancelTask);
        handler.h.refresh();
        return handler.h;
    }
    function _runMicroTask(callback) {
        try {
            if (callback) {
                callback();
            }
        }
        catch (e) {
            scheduleTimeout(function () {
                throw e;
            }, 0);
        }
    }
    var _taskQueues;
    function _flushQueues() {
        if (_taskQueues) {
            _taskQueues[1 ] && _flushTaskQueue(1 );
            _taskQueues[0 ] && _flushTaskQueue(0 );
        }
    }
    function _flushTaskQueue(queueType) {
        if (_taskQueues) {
            var queue = _taskQueues[queueType];
            var queueIdx = 0;
            while (queue && queue.length > queueIdx) {
                _runMicroTask(queue[queueIdx++]);
                if (queueType === 0  && _taskQueues[1 ]) {
                    _flushTaskQueue(1 );
                }
            }
            _taskQueues[queueType] = UNDEF_VALUE;
        }
    }
    function _addToQueue(queueType, callback, maxQueuedTasks) {
        var result = false;
        if (!_taskQueues) {
            _taskQueues = {};
        }
        var queue = _taskQueues[queueType];
        if (!queue) {
            queue = [];
            _taskQueues[queueType] = queue;
        }
        if (isStrictUndefined(maxQueuedTasks) || maxQueuedTasks === 0 || (queue.length < maxQueuedTasks)) {
            queue.push(callback);
            result = true;
        }
        else {
            throwRangeError("schedule" + ("Microtask" ) + "() queue depth exceeded [" + maxQueuedTasks + "]");
        }
        return result;
    }
    var _promiseCls$1;
    var _promisePending = false;
    var _pendingPromiseCls;
    var _promiseQueueFns;
    function _ensurePromiseTask(promiseCls) {
        if (_promisePending && _pendingPromiseCls !== promiseCls) {
            _promisePending = false;
        }
        if (!_promisePending) {
            _promisePending = true;
            _pendingPromiseCls = promiseCls;
            try {
                promiseCls.resolve().then(function () {
                    _promisePending = false;
                    _pendingPromiseCls = undefined;
                    _flushQueues();
                });
            }
            catch (e) {
                _promisePending = false;
                _pendingPromiseCls = undefined;
                _flushQueues();
            }
        }
    }
    function _promiseScheduleFn(promiseCls, queueType) {
        return function (callback, maxQueuedTasks) {
            var added = _addToQueue(queueType, callback, maxQueuedTasks);
            if (added) {
                _ensurePromiseTask(promiseCls);
            }
            return added;
        };
    }
    function _getPromiseQueueFn(queueType) {
        !_globalLazyTestHooks && _initTestHooks();
        if (!_promiseCls$1 || _globalLazyTestHooks.lzy) {
            var promClass = getInst("Promise");
            if (promClass && isFunction(promClass.resolve)) {
                _promiseCls$1 = createCachedValue(promClass);
                _promiseQueueFns = undefined;
            }
            else {
                _promiseCls$1 = undefined;
                _promiseQueueFns = undefined;
                _promisePending = false;
                _pendingPromiseCls = undefined;
            }
        }
        var result;
        if (_promiseCls$1 && _promiseCls$1.v) {
            !_promiseQueueFns && (_promiseQueueFns = {});
            result = _promiseQueueFns[queueType];
            if (!result) {
                result = _promiseScheduleFn(_promiseCls$1.v, queueType);
                _promiseQueueFns[queueType] = result;
            }
        }
        return result;
    }
    function _resolveScheduleFn(options, defaultOptions, taskQueueType) {
        var resolvedFn = (options && options.scheduleFn) || (defaultOptions && defaultOptions.scheduleFn);
        if (!resolvedFn) {
            var usePromise = !((options && !isStrictUndefined(options.useTimeout))
                ? options.useTimeout
                : (defaultOptions));
            if (usePromise) {
                resolvedFn = _getPromiseQueueFn(taskQueueType);
            }
        }
        return resolvedFn;
    }
    var _sharedTimer;
    var _isFlushing = false;
    function _doFlush() {
        try {
            _isFlushing = true;
            _flushQueues();
        }
        finally {
            _isFlushing = false;
        }
    }
    function _ensureSharedTimer() {
        if (_isFlushing) {
            return;
        }
        _setMicrotaskCallback(_doFlush);
        var handler = _sharedTimer;
        if (!handler) {
            _sharedTimer = scheduleTimeout(_returnNothing, 0);
        }
        else if (!handler.enabled) {
            handler.refresh();
        }
    }
    function _addMicrotaskQueue(callback, maxQueuedTasks) {
        return _addToQueueWithTimer(0 , callback, maxQueuedTasks);
    }
    function _addToQueueWithTimer(queueType, callback, maxQueuedTasks) {
        var result = _addToQueue(queueType, callback, maxQueuedTasks);
        if (result) {
            _ensureSharedTimer();
        }
        return result;
    }
    var _defaultOptions$1;
    function scheduleMicrotask(callback, argsOrOptions, options) {
        var theOptions;
        {
            theOptions = argsOrOptions;
        }
        var taskCallback = callback;
        var queueMicrotaskFn = getQueueMicrotask();
        if (!queueMicrotaskFn) {
            queueMicrotaskFn = _resolveScheduleFn(theOptions, _defaultOptions$1, 0 );
        }
        return _createCancellableTask(taskCallback, queueMicrotaskFn || _addMicrotaskQueue);
    }

    var STR_PROMISE = "Promise";
    var DONE = "done";
    var VALUE = "value";
    var RETURN = "return";
    var REJECTED = "rejected";

    function doAwaitResponse(value, cb) {
        return doAwait(value, function (value) {
            return cb ? cb({
                status: "fulfilled",
                rejected: false,
                value: value
            }) : value;
        }, function (reason) {
            return cb ? cb({
                status: REJECTED,
                rejected: true,
                reason: reason
            }) : reason;
        });
    }
    function doAwait(value, resolveFn, rejectFn, finallyFn) {
        var result = value;
        try {
            if (isPromiseLike(value)) {
                if (resolveFn || rejectFn) {
                    result = value.then(resolveFn, rejectFn);
                }
            }
            else {
                try {
                    if (resolveFn) {
                        result = resolveFn(value);
                    }
                }
                catch (err) {
                    if (rejectFn) {
                        result = rejectFn(err);
                    }
                    else {
                        throw err;
                    }
                }
            }
        }
        finally {
            if (finallyFn) {
                doFinally(result, finallyFn);
            }
        }
        return result;
    }
    function doFinally(value, finallyFn) {
        var result = value;
        if (finallyFn) {
            if (isPromiseLike(value)) {
                if (value.finally) {
                    result = value.finally(finallyFn);
                }
                else {
                    result = value.then(function (value) {
                        return doAwait(finallyFn(), function () {
                            return value;
                        });
                    }, function (reason) {
                        return doAwait(finallyFn(), function () {
                            throw reason;
                        });
                    });
                }
            }
            else {
                finallyFn();
            }
        }
        return result;
    }

    /*#__NO_SIDE_EFFECTS__*/
    function _pureAssign(func1, func2) {
        return func1 || func2;
    }

    var _debugState;
    var _debugResult;
    var _debugHandled;
    var _promiseDebugEnabled = false;
    function _addDebugState$1(thePromise, stateFn, resultFn, handledFn) {
        _debugState = _debugState || { toString: function () { return "[[PromiseState]]"; } };
        _debugResult = _debugResult || { toString: function () { return "[[PromiseResult]]"; } };
        _debugHandled = _debugHandled || { toString: function () { return "[[PromiseIsHandled]]"; } };
        var props = {};
        props[_debugState] = { get: stateFn };
        props[_debugResult] = { get: resultFn };
        props[_debugHandled] = { get: handledFn };
        objDefineProperties(thePromise, props);
    }
    function setPromiseDebugState(enabled, logger) {
        _promiseDebugEnabled = enabled;
    }

    var STRING_STATES = [
        "pending", "resolving", "resolved", REJECTED
    ];

    var DISPATCH_EVENT = "dispatchEvent";
    var _hasInitEvent;
    function _hasInitEventFn(doc) {
        var evt;
        if (doc && doc.createEvent) {
            evt = doc.createEvent("Event");
        }
        return (!!evt && evt.initEvent);
    }
    function emitEvent(target, evtName, populateEvent, useNewEvent) {
        var doc = getDocument();
        !_hasInitEvent && (_hasInitEvent = createCachedValue(!!safe(_hasInitEventFn, [doc]).v));
        var theEvt = _hasInitEvent.v ? doc.createEvent("Event") : (useNewEvent ? new Event(evtName) : {});
        populateEvent && populateEvent(theEvt);
        if (_hasInitEvent.v) {
            theEvt.initEvent(evtName, false, true);
        }
        if (theEvt && target[DISPATCH_EVENT]) {
            target[DISPATCH_EVENT](theEvt);
        }
        else {
            var handler = target["on" + evtName];
            if (handler) {
                handler(theEvt);
            }
            else {
                var theConsole = getInst("console");
                theConsole && (theConsole["error"] || theConsole["log"])(evtName, dumpObj(theEvt));
            }
        }
    }

    var NODE_UNHANDLED_REJECTION = "unhandledRejection";
    var UNHANDLED_REJECTION = NODE_UNHANDLED_REJECTION.toLowerCase();
    var _currentPromiseId = [];
    var _uniquePromiseId = 0;
    var _unhandledRejectionTimeout = 10;
    var _aggregationError;
    var _hasPromiseRejectionEvent;
    function dumpFnObj(value) {
        if (isFunction(value)) {
            return value.toString();
        }
        return dumpObj(value);
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createAggregationError(values) {
        !_aggregationError && (_aggregationError = createCachedValue(safe(getInst, ["AggregationError"]).v || createCustomError("AggregationError", function (self, args) {
            self.errors = args[0];
        })));
        return new _aggregationError.v(values);
    }
    function _createPromise(newPromise, processor, executor) {
        var additionalArgs = arrSlice(arguments, 3);
        var _state = 0 ;
        var _hasResolved = false;
        var _settledValue;
        var _queue = [];
        var _id = _uniquePromiseId++;
        var _parentId = _currentPromiseId.length > 0 ? _currentPromiseId[_currentPromiseId.length - 1] : undefined;
        var _handled = false;
        var _unHandledRejectionHandler = null;
        var _thePromise;
        function _then(onResolved, onRejected) {
            try {
                _currentPromiseId.push(_id);
                _handled = true;
                _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();
                _unHandledRejectionHandler = null;
                var thenPromise = newPromise(function (resolve, reject) {
                    _queue.push(function () {
                        try {
                            var handler = _state === 2  ? onResolved : onRejected;
                            var value = isFunction(handler) ? handler(_settledValue) : _settledValue;
                            if (isPromiseLike(value)) {
                                value.then(resolve, reject);
                            }
                            else if (isFunction(handler)) {
                                resolve(value);
                            }
                            else if (_state === 3 ) {
                                reject(value);
                            }
                            else {
                                resolve(value);
                            }
                        }
                        catch (e) {
                            reject(e);
                        }
                    });
                    if (_hasResolved) {
                        _processQueue();
                    }
                }, additionalArgs);
                return thenPromise;
            }
            finally {
                _currentPromiseId.pop();
            }
        }
        function _catch(onRejected) {
            return _then(undefined, onRejected);
        }
        function _finally(onFinally) {
            var thenFinally = onFinally;
            var catchFinally = onFinally;
            if (isFunction(onFinally)) {
                thenFinally = function (value) {
                    return doAwait(onFinally && onFinally(), function () {
                        return value;
                    });
                };
                catchFinally = function (reason) {
                    return doAwait(onFinally && onFinally(), function () {
                        throw reason;
                    });
                };
            }
            return _then(thenFinally, catchFinally);
        }
        function _strState() {
            return STRING_STATES[_state];
        }
        function _processQueue() {
            if (_queue.length > 0) {
                var pending = _queue.slice();
                _queue = [];
                _handled = true;
                _unHandledRejectionHandler && _unHandledRejectionHandler.cancel();
                _unHandledRejectionHandler = null;
                processor(pending);
            }
        }
        function _createSettleIfFn(newState, allowState) {
            return function (theValue) {
                if (_state === allowState) {
                    if (newState === 2  && isPromiseLike(theValue)) {
                        _state = 1 ;
                        theValue.then(_createSettleIfFn(2 , 1 ), _createSettleIfFn(3 , 1 ));
                        return;
                    }
                    _state = newState;
                    _hasResolved = true;
                    _settledValue = theValue;
                    _processQueue();
                    if (!_handled && newState === 3  && !_unHandledRejectionHandler) {
                        _unHandledRejectionHandler = scheduleTimeout(_notifyUnhandledRejection, _unhandledRejectionTimeout);
                    }
                }
            };
        }
        function _notifyUnhandledRejection() {
            if (!_handled) {
                _handled = true;
                if (isNode()) {
                    process.emit(NODE_UNHANDLED_REJECTION, _settledValue, _thePromise);
                }
                else {
                    var gbl = getWindow() || getGlobal();
                    !_hasPromiseRejectionEvent && (_hasPromiseRejectionEvent = createCachedValue(safe((getInst), [STR_PROMISE + "RejectionEvent"]).v));
                    emitEvent(gbl, UNHANDLED_REJECTION, function (theEvt) {
                        objDefine(theEvt, "promise", { g: function () { return _thePromise; } });
                        theEvt.reason = _settledValue;
                        return theEvt;
                    }, !!_hasPromiseRejectionEvent.v);
                }
            }
        }
        _thePromise = {
            then: _then,
            "catch": _catch,
            finally: _finally
        };
        objDefineProp(_thePromise, "state", {
            get: _strState
        });
        if (_promiseDebugEnabled) {
            _addDebugState$1(_thePromise, _strState, function () { return objToString(_settledValue); }, function () { return _handled; });
        }
        if (hasSymbol()) {
            _thePromise[getKnownSymbol(11 )] = "IPromise";
        }
        function _toString() {
            return "IPromise" + (_promiseDebugEnabled ? "[" + _id + (!isUndefined(_parentId) ? (":" + _parentId) : "") + "]" : "") + " " + _strState() + (_hasResolved ? (" - " + dumpFnObj(_settledValue)) : "") + ("");
        }
        _thePromise.toString = _toString;
        (function _initialize() {
            if (!isFunction(executor)) {
                throwTypeError(STR_PROMISE + ": executor is not a function - " + dumpFnObj(executor));
            }
            var _rejectFn = _createSettleIfFn(3 , 0 );
            try {
                executor.call(_thePromise, _createSettleIfFn(2 , 0 ), _rejectFn);
            }
            catch (e) {
                _rejectFn(e);
            }
        })();
        return _thePromise;
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createAllPromise(newPromise) {
        return function (input) {
            var additionalArgs = arrSlice(arguments, 1);
            return newPromise(function (resolve, reject) {
                try {
                    var values_1 = [];
                    var pending_1 = 1;
                    iterForOf(input, function (item, idx) {
                        if (item) {
                            pending_1++;
                            doAwait(item, function (value) {
                                values_1[idx] = value;
                                if (--pending_1 === 0) {
                                    resolve(values_1);
                                }
                            }, reject);
                        }
                    });
                    pending_1--;
                    if (pending_1 === 0) {
                        resolve(values_1);
                    }
                }
                catch (e) {
                    reject(e);
                }
            }, additionalArgs);
        };
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createResolvedPromise(newPromise) {
        return function (value) {
            var additionalArgs = arrSlice(arguments, 1);
            if (isPromiseLike(value)) {
                return value;
            }
            return newPromise(function (resolve) {
                resolve(value);
            }, additionalArgs);
        };
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createRejectedPromise(newPromise) {
        return function (reason) {
            var additionalArgs = arrSlice(arguments, 1);
            return newPromise(function (_resolve, reject) {
                reject(reason);
            }, additionalArgs);
        };
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createAllSettledPromise(newPromise) {
        return createCachedValue(function (input) {
            var additionalArgs = arrSlice(arguments, 1);
            return newPromise(function (resolve, reject) {
                var values = [];
                var pending = 1;
                function processItem(item, idx) {
                    pending++;
                    doAwaitResponse(item, function (value) {
                        if (value.rejected) {
                            values[idx] = {
                                status: REJECTED,
                                reason: value.reason
                            };
                        }
                        else {
                            values[idx] = {
                                status: "fulfilled",
                                value: value.value
                            };
                        }
                        if (--pending === 0) {
                            resolve(values);
                        }
                    });
                }
                try {
                    if (isArray(input)) {
                        arrForEach(input, processItem);
                    }
                    else if (isIterable(input)) {
                        iterForOf(input, processItem);
                    }
                    else {
                        throwTypeError("Input is not an iterable");
                    }
                    pending--;
                    if (pending === 0) {
                        resolve(values);
                    }
                }
                catch (e) {
                    reject(e);
                }
            }, additionalArgs);
        });
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createRacePromise(newPromise) {
        return createCachedValue(function (input) {
            var additionalArgs = arrSlice(arguments, 1);
            return newPromise(function (resolve, reject) {
                var isDone = false;
                function processItem(item) {
                    doAwaitResponse(item, function (value) {
                        if (!isDone) {
                            isDone = true;
                            if (value.rejected) {
                                reject(value.reason);
                            }
                            else {
                                resolve(value.value);
                            }
                        }
                    });
                }
                try {
                    if (isArray(input)) {
                        arrForEach(input, processItem);
                    }
                    else if (isIterable(input)) {
                        iterForOf(input, processItem);
                    }
                    else {
                        throwTypeError("Input is not an iterable");
                    }
                }
                catch (e) {
                    reject(e);
                }
            }, additionalArgs);
        });
    }
    /*#__NO_SIDE_EFFECTS__*/
    function _createAnyPromise(newPromise) {
        return createCachedValue(function (input) {
            var additionalArgs = arrSlice(arguments, 1);
            return newPromise(function (resolve, reject) {
                var theErros = [];
                var pending = 1;
                var isDone = false;
                function processItem(item, idx) {
                    pending++;
                    doAwaitResponse(item, function (value) {
                        if (!value.rejected) {
                            isDone = true;
                            resolve(value.value);
                            return;
                        }
                        else {
                            theErros[idx] = value.reason;
                        }
                        if (--pending === 0 && !isDone) {
                            reject(_createAggregationError(theErros));
                        }
                    });
                }
                try {
                    if (isArray(input)) {
                        arrForEach(input, processItem);
                    }
                    else if (isIterable(input)) {
                        iterForOf(input, processItem);
                    }
                    else {
                        throwTypeError("Input is not an iterable");
                    }
                    pending--;
                    if (pending === 0 && !isDone) {
                        reject(_createAggregationError(theErros));
                    }
                }
                catch (e) {
                    reject(e);
                }
            }, additionalArgs);
        });
    }

    /*#__NO_SIDE_EFFECTS__*/
    function _normalizeTimeoutValue(timeout, defaultTimeout) {
        var result = defaultTimeout;
        if (!isUndefined(timeout)) {
            if (isNumber(timeout)) {
                result = timeout;
            }
            else {
                while (!isUndefined(timeout) && isArray(timeout) && timeout.length > 0) {
                    timeout = timeout[0];
                    if (isNumber(timeout)) {
                        result = timeout;
                        break;
                    }
                }
            }
        }
        return result;
    }

    function _isFakeTimersEnabled() {
        var setTimeoutFn = setTimeout;
        return !!(setTimeoutFn && setTimeoutFn.clock);
    }
    function syncItemProcessor(pending) {
        arrForEach(pending, function (fn) {
            try {
                fn();
            }
            catch (e) {
            }
        });
    }
    function timeoutItemProcessor(timeout) {
        var timeoutValue = _normalizeTimeoutValue(timeout);
        var hasTimeout = isNumber(timeoutValue);
        var callbackTimeout = hasTimeout ? timeoutValue : 0;
        return function (pending) {
            function _processPending() {
                syncItemProcessor(pending);
            }
            if (hasTimeout && callbackTimeout > 0) {
                scheduleTimeout(_processPending, callbackTimeout);
            }
            else if (_isFakeTimersEnabled()) {
                scheduleTimeout(_processPending, 0);
            }
            else {
                scheduleMicrotask(_processPending);
            }
        };
    }

    var _allAsyncSettledCreator;
    var _raceAsyncCreator;
    var _anyAsyncCreator;
    function createAsyncPromise(executor, timeout) {
        return _createPromise(createAsyncPromise, timeoutItemProcessor(timeout), executor, timeout);
    }
    var createAsyncAllPromise = (/*#__PURE__*/_createAllPromise(createAsyncPromise));
    var createAsyncResolvedPromise = (/*#__PURE__*/_createResolvedPromise(createAsyncPromise));
    var createAsyncRejectedPromise = (/*#__PURE__*/_createRejectedPromise(createAsyncPromise));
    function createAsyncAllSettledPromise(input, timeout) {
        !_allAsyncSettledCreator && (_allAsyncSettledCreator = _createAllSettledPromise(createAsyncPromise));
        return _allAsyncSettledCreator.v(input, timeout);
    }
    function createAsyncRacePromise(values, timeout) {
        !_raceAsyncCreator && (_raceAsyncCreator = _createRacePromise(createAsyncPromise));
        return _raceAsyncCreator.v(values, timeout);
    }
    function createAsyncAnyPromise(values, timeout) {
        !_anyAsyncCreator && (_anyAsyncCreator = _createAnyPromise(createAsyncPromise));
        return _anyAsyncCreator.v(values, timeout);
    }

    var _promiseCls;
    var _allCreator;
    var _allNativeSettledCreator;
    var _raceNativeCreator;
    var _anyNativeCreator;
    /*#__NO_SIDE_EFFECTS__*/
    function _createNativePromiseHelper(name, func) {
        !_promiseCls && (_promiseCls = createCachedValue((safe(getInst, [STR_PROMISE]).v) || null));
        if (_promiseCls.v && _promiseCls.v[name]) {
            return createCachedValue(function (input, timeout) {
                return createNativePromise(function (resolve, reject) {
                    _promiseCls.v[name](input).then(resolve, reject);
                });
            });
        }
        return func();
    }
    function createNativePromise(executor, timeout) {
        !_promiseCls && (_promiseCls = createCachedValue((safe(getInst, [STR_PROMISE]).v) || null));
        var PrmCls = _promiseCls.v;
        if (!PrmCls) {
            return createAsyncPromise(executor);
        }
        if (!isFunction(executor)) {
            throwTypeError(STR_PROMISE + ": executor is not a function - " + dumpObj(executor));
        }
        var _state = 0 ;
        function _strState() {
            return STRING_STATES[_state];
        }
        var thePromise = new PrmCls(function (resolve, reject) {
            function _resolve(value) {
                _state = 2 ;
                resolve(value);
            }
            function _reject(reason) {
                _state = 3 ;
                reject(reason);
            }
            executor(_resolve, _reject);
        });
        objDefineProp(thePromise, "state", {
            get: _strState
        });
        return thePromise;
    }
    function createNativeAllPromise(input, timeout) {
        !_allCreator && (_allCreator = _createNativePromiseHelper("all", function () { return createCachedValue(_createAllPromise(createNativePromise)); }));
        return _allCreator.v(input, timeout);
    }
    var createNativeResolvedPromise = (/*#__PURE__*/_createResolvedPromise(createNativePromise));
    var createNativeRejectedPromise = (/*#__PURE__*/_createRejectedPromise(createNativePromise));
    function createNativeAllSettledPromise(input, timeout) {
        !_allNativeSettledCreator && (_allNativeSettledCreator = _createNativePromiseHelper("allSettled", function () { return _createAllSettledPromise(createNativePromise); }));
        return _allNativeSettledCreator.v(input, timeout);
    }
    function createNativeRacePromise(values, timeout) {
        !_raceNativeCreator && (_raceNativeCreator = _createNativePromiseHelper("race", function () { return _createRacePromise(createNativePromise); }));
        return _raceNativeCreator.v(values, timeout);
    }
    function createNativeAnyPromise(values, timeout) {
        !_anyNativeCreator && (_anyNativeCreator = _createNativePromiseHelper("any", function () { return _createAnyPromise(createNativePromise); }));
        return _anyNativeCreator.v(values, timeout);
    }

    var _allSyncSettledCreator;
    var _raceSyncCreator;
    var _anySyncCreator;
    function createSyncPromise(executor) {
        return _createPromise(createSyncPromise, syncItemProcessor, executor);
    }
    var createSyncAllPromise = (/*#__PURE__*/_createAllPromise(createSyncPromise));
    var createSyncResolvedPromise = (/*#__PURE__*/_createResolvedPromise(createSyncPromise));
    var createSyncRejectedPromise = (/*#__PURE__*/_createRejectedPromise(createSyncPromise));
    function createSyncAllSettledPromise(input, timeout) {
        !_allSyncSettledCreator && (_allSyncSettledCreator = _createAllSettledPromise(createSyncPromise));
        return _allSyncSettledCreator.v(input, timeout);
    }
    function createSyncRacePromise(values, timeout) {
        !_raceSyncCreator && (_raceSyncCreator = _createRacePromise(createSyncPromise));
        return _raceSyncCreator.v(values, timeout);
    }
    function createSyncAnyPromise(values, timeout) {
        !_anySyncCreator && (_anySyncCreator = _createAnyPromise(createSyncPromise));
        return _anySyncCreator.v(values, timeout);
    }

    var _defaultIdleTimeout;
    var _allIdleSettledCreator;
    var _raceIdleCreator;
    var _anyIdleCreator;
    function setDefaultIdlePromiseTimeout(idleDeadline) {
        _defaultIdleTimeout = idleDeadline;
    }
    var setDefaultIdleTimeout = (/*#__PURE__*/_pureAssign(setDefaultIdlePromiseTimeout));
    function createIdlePromise(executor, timeout) {
        var options;
        var theTimeout = _normalizeTimeoutValue(timeout, _defaultIdleTimeout);
        if (isNumber(theTimeout) && theTimeout >= 0) {
            options = {
                timeout: theTimeout
            };
        }
        var processor = function (pending) {
            scheduleIdleCallback(function (deadline) {
                syncItemProcessor(pending);
            }, options);
        };
        return _createPromise(createIdlePromise, processor, executor, theTimeout);
    }
    var createIdleAllPromise = (/*#__PURE__*/_createAllPromise(createIdlePromise));
    var createIdleResolvedPromise = (/*#__PURE__*/_createResolvedPromise(createIdlePromise));
    var createIdleRejectedPromise = (/*#__PURE__*/_createRejectedPromise(createIdlePromise));
    function createIdleAllSettledPromise(input, timeout) {
        !_allIdleSettledCreator && (_allIdleSettledCreator = _createAllSettledPromise(createIdlePromise));
        return _allIdleSettledCreator.v(input, timeout);
    }
    function createIdleRacePromise(values, timeout) {
        !_raceIdleCreator && (_raceIdleCreator = _createRacePromise(createIdlePromise));
        return _raceIdleCreator.v(values, timeout);
    }
    function createIdleAnyPromise(values, timeout) {
        !_anyIdleCreator && (_anyIdleCreator = _createAnyPromise(createIdlePromise));
        return _anyIdleCreator.v(values, timeout);
    }

    var _promiseCreator;
    var _allSettledCreator;
    var _raceCreator;
    var _anyCreator;
    function setCreatePromiseImpl(creator) {
        _promiseCreator = creator ? createCachedValue(creator) : null;
    }
    function createPromise(executor, timeout) {
        !_promiseCreator && (_promiseCreator = createCachedValue(createNativePromise));
        return _promiseCreator.v.call(this, executor, timeout);
    }
    var createAllPromise = (/*#__PURE__*/_createAllPromise(createPromise));
    var createResolvedPromise = (/*#__PURE__*/_createResolvedPromise(createPromise));
    var createRejectedPromise = (/*#__PURE__*/_createRejectedPromise(createPromise));
    function createAllSettledPromise(input, timeout) {
        !_allSettledCreator && (_allSettledCreator = _createAllSettledPromise(createPromise));
        return _allSettledCreator.v(input, timeout);
    }
    function createRacePromise(values, timeout) {
        !_raceCreator && (_raceCreator = _createRacePromise(createPromise));
        return _raceCreator.v(values, timeout);
    }
    function createAnyPromise(values, timeout) {
        !_anyCreator && (_anyCreator = _createAnyPromise(createPromise));
        return _anyCreator.v(values, timeout);
    }

    function createTimeoutPromise(timeout, resolveReject, message) {
        return createPromise(function (resolve, reject) {
            scheduleTimeout(function () {
                (resolveReject ? resolve : reject)(!isUndefined(message) ? message : "Timeout of " + timeout + "ms exceeded");
            }, timeout);
        });
    }

    function _doneChk(isDone, state, value, thisArg) {
        var result = isDone;
        state.res = value;
        if (!result) {
            if (state.isDone && isFunction(state.isDone)) {
                return doAwait(state.isDone.call(thisArg, state), function (done) {
                    state.iter++;
                    return !!done;
                });
            }
            else {
                result = !!state.isDone;
            }
        }
        state.iter++;
        return result;
    }
    function doWhileAsync(callbackFn, isDoneFn, thisArg) {
        var promise;
        var resolve;
        var reject = function (reason) {
            isDone = true;
            throw reason;
        };
        var isDone = false;
        var state = {
            st: utcNow(),
            iter: 0,
            isDone: isDoneFn || false
        };
        if (callbackFn) {
            var _createPromise_1 = function () {
                return createPromise(function (res, rej) {
                    resolve = res;
                    reject = rej;
                });
            };
            var _handleAsyncDone_1 = function (done) {
                isDone = !!done;
                if (!isDone) {
                    _processNext_1();
                }
                else {
                    resolve(state.res);
                }
            };
            var _processNext_1 = function () {
                while (!isDone) {
                    try {
                        var cbResult = callbackFn.call(thisArg, state);
                        if (isPromiseLike(cbResult)) {
                            promise = promise || _createPromise_1();
                            doAwait(cbResult, function (res) {
                                try {
                                    doAwait(_doneChk(isDone, state, res, thisArg), _handleAsyncDone_1, reject);
                                }
                                catch (e) {
                                    reject(e);
                                }
                            }, reject);
                            return promise;
                        }
                        else {
                            var dnRes = _doneChk(isDone, state, cbResult, thisArg);
                            if (isPromiseLike(dnRes)) {
                                promise = promise || _createPromise_1();
                                doAwait(dnRes, _handleAsyncDone_1, reject);
                                return promise;
                            }
                            else {
                                isDone = !!dnRes;
                            }
                        }
                    }
                    catch (e) {
                        reject(e);
                        return promise;
                    }
                }
                if (isDone && resolve) {
                    resolve(state.res);
                }
                return promise || state.res;
            };
            return _processNext_1();
        }
    }

    function arrForEachAsync(theArray, callbackFn, thisArg) {
        if (theArray) {
            var len_1 = getLength(theArray);
            if (len_1) {
                var isDone = function (state) {
                    if (state.iter >= len_1 || state.res === -1) {
                        return true;
                    }
                };
                return doWhileAsync(function (state) {
                    var idx = state.iter;
                    if (idx in theArray) {
                        return callbackFn.call(thisArg || theArray, theArray[idx], idx, theArray);
                    }
                }, isDone);
            }
        }
    }

    var _iterSymbol;
    var _iterAsyncSymbol;
    function iterForOfAsync(iter, callbackFn, thisArg) {
        var err;
        var iterResult;
        var theIter = iter;
        function onFailed(failed) {
            err = { e: failed };
            if (theIter.throw) {
                iterResult = null;
                theIter.throw(err);
            }
            throw failed;
        }
        function onFinally() {
            try {
                if (iterResult && !iterResult[DONE]) {
                    theIter[RETURN] && theIter[RETURN](iterResult);
                }
            }
            finally {
                if (err) {
                    throw err.e;
                }
            }
        }
        if (iter) {
            if (!isIterator(iter)) {
                !_iterAsyncSymbol && (_iterAsyncSymbol = createCachedValue(getKnownSymbol(0 )));
                theIter = iter[_iterAsyncSymbol.v] ? iter[_iterAsyncSymbol.v]() : null;
                if (!theIter) {
                    !_iterSymbol && (_iterSymbol = createCachedValue(getKnownSymbol(3 )));
                    theIter = iter[_iterSymbol.v] ? iter[_iterSymbol.v]() : null;
                }
            }
            if (theIter && isIterator(theIter)) {
                var result = void 0;
                try {
                    result = doWhileAsync(function (state) {
                        return doAwait(theIter.next(), function (res) {
                            iterResult = res;
                            if (!res[DONE]) {
                                return fnCall(callbackFn, thisArg || theIter, iterResult[VALUE], state.iter, theIter);
                            }
                        }, function (reason) {
                            state.isDone = true;
                            onFailed(reason);
                        });
                    }, function (state) {
                        if (!iterResult || iterResult[DONE] || state.res === -1) {
                            onFinally();
                            return true;
                        }
                    }, thisArg || theIter);
                    if (isPromiseLike(result)) {
                        result = doFinally(result.catch(onFailed), onFinally);
                    }
                    return result;
                }
                catch (failed) {
                    onFailed(failed);
                }
                finally {
                    if (result && !isPromiseLike(result)) {
                        onFinally();
                    }
                }
            }
        }
    }

    var REJECT = "reject";
    var REJECTED_ERROR = "Rejected";
    var _schedulerId = 0;
    var _debugName;
    var _debugIntState;
    var _customErrors = {};
    function _rejectDone() {
    }
    function _createError(type, evt, message) {
        !_customErrors[type] && (_customErrors[type] = createCustomError(type));
        var now = utcNow();
        return new (_customErrors[type])("Task [".concat(evt.id, "] ").concat(message || "", "- ").concat((evt.st ? "Running" : "Waiting"), ": ").concat(_calcTime(now, evt.st || evt.cr)));
    }
    function _calcTime(now, start) {
        return ((now - start) || "0") + " ms";
    }
    function _abortStaleTasks(taskQueue, staleTimeoutPeriod) {
        var now = utcNow();
        var expired = now - staleTimeoutPeriod;
        arrForEach(taskQueue, function (evt) {
            if (evt && !evt.rj && (evt.st && evt.st < expired) || (!evt.st && evt.cr && evt.cr < expired)) {
                evt && evt[REJECT](evt.rj || _createError("Aborted", evt, "Stale "));
            }
        });
    }
    function _removeTask(queue, taskDetail) {
        var idx = arrIndexOf(queue, taskDetail);
        if (idx !== -1) {
            queue.splice(idx, 1);
        }
    }
    function _addDebugState(theScheduler, nameFn, stateFn) {
        _debugName = _debugName || { toString: function () { return "[[SchedulerName]]"; } };
        _debugIntState = _debugIntState || { toString: function () { return "[[SchedulerState]]"; } };
        objDefineProp(theScheduler, _debugName, { get: nameFn });
        objDefineProp(theScheduler, _debugIntState, { get: stateFn });
    }
    function createTaskScheduler(newPromise, name) {
        var _theTask;
        var _running = [];
        var _waiting = [];
        var _staleTimeoutPeriod = 600000;
        var _staleTimeoutCheckPeriod = _staleTimeoutPeriod / 10;
        var _taskCount = 0;
        var _schedulerName = (name ? (name + ".") : "") + _schedulerId++;
        var _blockedTimer;
        newPromise = newPromise || createPromise;
        var _startBlockedTimer = function () {
            var hasTasks = (getLength(_running) + getLength(_waiting)) > 0;
            if (_staleTimeoutPeriod > 0) {
                if (!_blockedTimer) {
                    _blockedTimer = scheduleTimeout(function () {
                        _abortStaleTasks(_running, _staleTimeoutPeriod);
                        _abortStaleTasks(_waiting, _staleTimeoutPeriod);
                        _blockedTimer && (_blockedTimer.enabled = ((getLength(_running) + getLength(_waiting)) > 0));
                    }, _staleTimeoutCheckPeriod);
                    _blockedTimer.unref();
                }
                _blockedTimer && (_blockedTimer.enabled = hasTasks);
            }
        };
        var _queueTask = function (startAction, taskName, timeout) {
            var _a;
            var taskId = _schedulerName + "." + _taskCount++;
            if (taskName) {
                taskId += "-(" + taskName + ")";
            }
            var newTask = (_a = {
                    id: taskId,
                    cr: utcNow(),
                    to: timeout
                },
                _a[REJECT] = function (reason) {
                    newTask.rj = reason || _createError(REJECTED_ERROR, newTask);
                    newTask[REJECT] = _rejectDone;
                },
                _a);
            if (!_theTask) {
                newTask.p = newPromise(_runTask(newTask, startAction));
            }
            else {
                newTask.p = _waitForPreviousTask(newTask, _theTask, startAction);
            }
            _theTask = newTask;
            return newTask.p;
        };
        var _runTask = function (taskDetail, startAction) {
            taskDetail.st = utcNow();
            _running.push(taskDetail);
            _startBlockedTimer();
            return function (onTaskResolve, onTaskReject) {
                var _promiseReject = function (reason) {
                    taskDetail.rj = taskDetail.rj || reason || _createError(REJECTED_ERROR, taskDetail);
                    taskDetail[REJECT] = _rejectDone;
                    _doCleanup(taskDetail);
                    onTaskResolve = null;
                    onTaskReject && onTaskReject(reason);
                    onTaskReject = null;
                };
                var taskId = taskDetail.id;
                if (taskDetail.rj) {
                    _promiseReject(taskDetail.rj);
                }
                else {
                    taskDetail[REJECT] = _promiseReject;
                    try {
                        var startResult = startAction(taskId);
                        if (taskDetail.to && isPromiseLike(startResult)) {
                            taskDetail.t = scheduleTimeout(function () {
                                _promiseReject(_createError("Timeout", taskDetail));
                            }, taskDetail.to);
                        }
                        doAwait(startResult, function (theResult) {
                            _doCleanup(taskDetail);
                            try {
                                onTaskResolve && onTaskResolve(theResult);
                            }
                            catch (e) {
                                onTaskReject && onTaskReject(e);
                            }
                            onTaskReject = null;
                            onTaskResolve = null;
                        }, _promiseReject);
                    }
                    catch (e) {
                        _promiseReject(e);
                    }
                }
            };
        };
        var _waitForPreviousTask = function (taskDetail, prevTask, startAction) {
            _waiting.push(taskDetail);
            _startBlockedTimer();
            return newPromise(function (onWaitResolve, onWaitReject) {
                doAwaitResponse(prevTask.p, function () {
                    _removeTask(_waiting, taskDetail);
                    _runTask(taskDetail, startAction)(onWaitResolve, onWaitReject);
                });
            });
        };
        var _doCleanup = function (taskDetail) {
            _removeTask(_running, taskDetail);
            _removeTask(_waiting, taskDetail);
            taskDetail.t && taskDetail.t.cancel();
            taskDetail.t = null;
            if (_theTask && _theTask === taskDetail) {
                _theTask = null;
                if (getLength(_running) + getLength(_waiting) === 0) {
                    _blockedTimer && _blockedTimer.cancel();
                    _blockedTimer = null;
                }
            }
        };
        var theScheduler = {
            idle: true,
            queue: _queueTask,
            setStaleTimeout: function (staleTimeout, staleCheckPeriod) {
                _blockedTimer && _blockedTimer.cancel();
                _blockedTimer = null;
                _staleTimeoutPeriod = staleTimeout;
                _staleTimeoutCheckPeriod = staleCheckPeriod || staleTimeout / 10;
                _startBlockedTimer();
            }
        };
        objDefine(theScheduler, "idle", {
            g: function () {
                return getLength(_running) + getLength(_waiting) === 0;
            }
        });
        _addDebugState(theScheduler, function () { return _schedulerName; }, function () {
            return {
                l: _theTask,
                r: _running,
                w: _waiting
            };
        });
        return theScheduler;
    }

    var toStringTagSymbol = getKnownSymbol(11 );
    var PolyPromise = (/*#__PURE__*/(function () {
        function PolyPromiseImpl(executor) {
            this._$ = createAsyncPromise(executor);
            if (toStringTagSymbol) {
                this[toStringTagSymbol] = "Promise";
            }
            objDefineProp(this, "state", {
                get: function () {
                    return this._$.state;
                }
            });
        }
        PolyPromiseImpl.all = createAsyncAllPromise;
        PolyPromiseImpl.race = createAsyncRacePromise;
        PolyPromiseImpl.any = createAsyncAnyPromise;
        PolyPromiseImpl.reject = createAsyncRejectedPromise;
        PolyPromiseImpl.resolve = createAsyncResolvedPromise;
        PolyPromiseImpl.allSettled = createAsyncAllSettledPromise;
        var theProto = PolyPromiseImpl.prototype;
        theProto.then = function (onResolved, onRejected) {
            return this._$.then(onResolved, onRejected);
        };
        theProto.catch = function (onRejected) {
            return this._$.catch(onRejected);
        };
        theProto.finally = function (onfinally) {
            return this._$.finally(onfinally);
        };
        return PolyPromiseImpl;
    }()));

    exports.PolyPromise = PolyPromise;
    exports.arrForEachAsync = arrForEachAsync;
    exports.createAllPromise = createAllPromise;
    exports.createAllSettledPromise = createAllSettledPromise;
    exports.createAnyPromise = createAnyPromise;
    exports.createAsyncAllPromise = createAsyncAllPromise;
    exports.createAsyncAllSettledPromise = createAsyncAllSettledPromise;
    exports.createAsyncAnyPromise = createAsyncAnyPromise;
    exports.createAsyncPromise = createAsyncPromise;
    exports.createAsyncRacePromise = createAsyncRacePromise;
    exports.createAsyncRejectedPromise = createAsyncRejectedPromise;
    exports.createAsyncResolvedPromise = createAsyncResolvedPromise;
    exports.createIdleAllPromise = createIdleAllPromise;
    exports.createIdleAllSettledPromise = createIdleAllSettledPromise;
    exports.createIdleAnyPromise = createIdleAnyPromise;
    exports.createIdlePromise = createIdlePromise;
    exports.createIdleRacePromise = createIdleRacePromise;
    exports.createIdleRejectedPromise = createIdleRejectedPromise;
    exports.createIdleResolvedPromise = createIdleResolvedPromise;
    exports.createNativeAllPromise = createNativeAllPromise;
    exports.createNativeAllSettledPromise = createNativeAllSettledPromise;
    exports.createNativeAnyPromise = createNativeAnyPromise;
    exports.createNativePromise = createNativePromise;
    exports.createNativeRacePromise = createNativeRacePromise;
    exports.createNativeRejectedPromise = createNativeRejectedPromise;
    exports.createNativeResolvedPromise = createNativeResolvedPromise;
    exports.createPromise = createPromise;
    exports.createRacePromise = createRacePromise;
    exports.createRejectedPromise = createRejectedPromise;
    exports.createResolvedPromise = createResolvedPromise;
    exports.createSyncAllPromise = createSyncAllPromise;
    exports.createSyncAllSettledPromise = createSyncAllSettledPromise;
    exports.createSyncAnyPromise = createSyncAnyPromise;
    exports.createSyncPromise = createSyncPromise;
    exports.createSyncRacePromise = createSyncRacePromise;
    exports.createSyncRejectedPromise = createSyncRejectedPromise;
    exports.createSyncResolvedPromise = createSyncResolvedPromise;
    exports.createTaskScheduler = createTaskScheduler;
    exports.createTimeoutPromise = createTimeoutPromise;
    exports.doAwait = doAwait;
    exports.doAwaitResponse = doAwaitResponse;
    exports.doFinally = doFinally;
    exports.doWhileAsync = doWhileAsync;
    exports.iterForOfAsync = iterForOfAsync;
    exports.setCreatePromiseImpl = setCreatePromiseImpl;
    exports.setDefaultIdlePromiseTimeout = setDefaultIdlePromiseTimeout;
    exports.setDefaultIdleTimeout = setDefaultIdleTimeout;
    exports.setPromiseDebugState = setPromiseDebugState;

}));
//# sourceMappingURL=ts-async.js.map
