UNPKG

contentful-management

Version:
26,518 lines 1.02 MB
var contentfulManagement = (function (exports) {
    'use strict';

    var toStringFunction = Function.prototype.toString;
    var create$Q = Object.create;
    var toStringObject = Object.prototype.toString;
    /**
     * @classdesc Fallback cache for when WeakMap is not natively supported
     */
    var LegacyCache = /** @class */ (function () {
        function LegacyCache() {
            this._keys = [];
            this._values = [];
        }
        LegacyCache.prototype.has = function (key) {
            return !!~this._keys.indexOf(key);
        };
        LegacyCache.prototype.get = function (key) {
            return this._values[this._keys.indexOf(key)];
        };
        LegacyCache.prototype.set = function (key, value) {
            this._keys.push(key);
            this._values.push(value);
        };
        return LegacyCache;
    }());
    function createCacheLegacy() {
        return new LegacyCache();
    }
    function createCacheModern() {
        return new WeakMap();
    }
    /**
     * Get a new cache object to prevent circular references.
     */
    var createCache = typeof WeakMap !== 'undefined' ? createCacheModern : createCacheLegacy;
    /**
     * Get an empty version of the object with the same prototype it has.
     */
    function getCleanClone(prototype) {
        if (!prototype) {
            return create$Q(null);
        }
        var Constructor = prototype.constructor;
        if (Constructor === Object) {
            return prototype === Object.prototype ? {} : create$Q(prototype);
        }
        if (Constructor &&
            ~toStringFunction.call(Constructor).indexOf('[native code]')) {
            try {
                return new Constructor();
            }
            catch (_a) { }
        }
        return create$Q(prototype);
    }
    function getRegExpFlagsLegacy(regExp) {
        var flags = '';
        if (regExp.global) {
            flags += 'g';
        }
        if (regExp.ignoreCase) {
            flags += 'i';
        }
        if (regExp.multiline) {
            flags += 'm';
        }
        if (regExp.unicode) {
            flags += 'u';
        }
        if (regExp.sticky) {
            flags += 'y';
        }
        return flags;
    }
    function getRegExpFlagsModern(regExp) {
        return regExp.flags;
    }
    /**
     * Get the flags to apply to the copied regexp.
     */
    var getRegExpFlags = /test/g.flags === 'g' ? getRegExpFlagsModern : getRegExpFlagsLegacy;
    function getTagLegacy(value) {
        var type = toStringObject.call(value);
        return type.substring(8, type.length - 1);
    }
    function getTagModern(value) {
        return value[Symbol.toStringTag] || getTagLegacy(value);
    }
    /**
     * Get the tag of the value passed, so that the correct copier can be used.
     */
    var getTag = typeof Symbol !== 'undefined' ? getTagModern : getTagLegacy;

    var defineProperty = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols = Object.getOwnPropertySymbols;
    var _a = Object.prototype, hasOwnProperty$1 = _a.hasOwnProperty, propertyIsEnumerable = _a.propertyIsEnumerable;
    var SUPPORTS_SYMBOL = typeof getOwnPropertySymbols === 'function';
    function getStrictPropertiesModern(object) {
        return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));
    }
    /**
     * Get the properites used when copying objects strictly. This includes both keys and symbols.
     */
    var getStrictProperties = SUPPORTS_SYMBOL
        ? getStrictPropertiesModern
        : getOwnPropertyNames;
    /**
     * Striclty copy all properties contained on the object.
     */
    function copyOwnPropertiesStrict(value, clone, state) {
        var properties = getStrictProperties(value);
        for (var index = 0, length_1 = properties.length, property = void 0, descriptor = void 0; index < length_1; ++index) {
            property = properties[index];
            if (property === 'callee' || property === 'caller') {
                continue;
            }
            descriptor = getOwnPropertyDescriptor(value, property);
            if (!descriptor) {
                // In extra edge cases where the property descriptor cannot be retrived, fall back to
                // the loose assignment.
                clone[property] = state.copier(value[property], state);
                continue;
            }
            // Only clone the value if actually a value, not a getter / setter.
            if (!descriptor.get && !descriptor.set) {
                descriptor.value = state.copier(descriptor.value, state);
            }
            try {
                defineProperty(clone, property, descriptor);
            }
            catch (error) {
                // Tee above can fail on node in edge cases, so fall back to the loose assignment.
                clone[property] = descriptor.value;
            }
        }
        return clone;
    }
    /**
     * Deeply copy the indexed values in the array.
     */
    function copyArrayLoose(array, state) {
        var clone = new state.Constructor();
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(array, clone);
        for (var index = 0, length_2 = array.length; index < length_2; ++index) {
            clone[index] = state.copier(array[index], state);
        }
        return clone;
    }
    /**
     * Deeply copy the indexed values in the array, as well as any custom properties.
     */
    function copyArrayStrict(array, state) {
        var clone = new state.Constructor();
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(array, clone);
        return copyOwnPropertiesStrict(array, clone, state);
    }
    /**
     * Copy the contents of the ArrayBuffer.
     */
    function copyArrayBuffer(arrayBuffer, _state) {
        return arrayBuffer.slice(0);
    }
    /**
     * Create a new Blob with the contents of the original.
     */
    function copyBlob(blob, _state) {
        return blob.slice(0, blob.size, blob.type);
    }
    /**
     * Create a new DataView with the contents of the original.
     */
    function copyDataView(dataView, state) {
        return new state.Constructor(copyArrayBuffer(dataView.buffer));
    }
    /**
     * Create a new Date based on the time of the original.
     */
    function copyDate(date, state) {
        return new state.Constructor(date.getTime());
    }
    /**
     * Deeply copy the keys and values of the original.
     */
    function copyMapLoose(map, state) {
        var clone = new state.Constructor();
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(map, clone);
        map.forEach(function (value, key) {
            clone.set(key, state.copier(value, state));
        });
        return clone;
    }
    /**
     * Deeply copy the keys and values of the original, as well as any custom properties.
     */
    function copyMapStrict(map, state) {
        return copyOwnPropertiesStrict(map, copyMapLoose(map, state), state);
    }
    function copyObjectLooseLegacy(object, state) {
        var clone = getCleanClone(state.prototype);
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(object, clone);
        for (var key in object) {
            if (hasOwnProperty$1.call(object, key)) {
                clone[key] = state.copier(object[key], state);
            }
        }
        return clone;
    }
    function copyObjectLooseModern(object, state) {
        var clone = getCleanClone(state.prototype);
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(object, clone);
        for (var key in object) {
            if (hasOwnProperty$1.call(object, key)) {
                clone[key] = state.copier(object[key], state);
            }
        }
        var symbols = getOwnPropertySymbols(object);
        for (var index = 0, length_3 = symbols.length, symbol = void 0; index < length_3; ++index) {
            symbol = symbols[index];
            if (propertyIsEnumerable.call(object, symbol)) {
                clone[symbol] = state.copier(object[symbol], state);
            }
        }
        return clone;
    }
    /**
     * Deeply copy the properties (keys and symbols) and values of the original.
     */
    var copyObjectLoose = SUPPORTS_SYMBOL
        ? copyObjectLooseModern
        : copyObjectLooseLegacy;
    /**
     * Deeply copy the properties (keys and symbols) and values of the original, as well
     * as any hidden or non-enumerable properties.
     */
    function copyObjectStrict(object, state) {
        var clone = getCleanClone(state.prototype);
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(object, clone);
        return copyOwnPropertiesStrict(object, clone, state);
    }
    /**
     * Create a new primitive wrapper from the value of the original.
     */
    function copyPrimitiveWrapper(primitiveObject, state) {
        return new state.Constructor(primitiveObject.valueOf());
    }
    /**
     * Create a new RegExp based on the value and flags of the original.
     */
    function copyRegExp(regExp, state) {
        var clone = new state.Constructor(regExp.source, getRegExpFlags(regExp));
        clone.lastIndex = regExp.lastIndex;
        return clone;
    }
    /**
     * Return the original value (an identity function).
     *
     * @note
     * THis is used for objects that cannot be copied, such as WeakMap.
     */
    function copySelf(value, _state) {
        return value;
    }
    /**
     * Deeply copy the values of the original.
     */
    function copySetLoose(set, state) {
        var clone = new state.Constructor();
        // set in the cache immediately to be able to reuse the object recursively
        state.cache.set(set, clone);
        set.forEach(function (value) {
            clone.add(state.copier(value, state));
        });
        return clone;
    }
    /**
     * Deeply copy the values of the original, as well as any custom properties.
     */
    function copySetStrict(set, state) {
        return copyOwnPropertiesStrict(set, copySetLoose(set, state), state);
    }

    var isArray$1 = Array.isArray;
    var assign = Object.assign;
    var getPrototypeOf = Object.getPrototypeOf || (function (obj) { return obj.__proto__; });
    var DEFAULT_LOOSE_OPTIONS = {
        array: copyArrayLoose,
        arrayBuffer: copyArrayBuffer,
        blob: copyBlob,
        dataView: copyDataView,
        date: copyDate,
        error: copySelf,
        map: copyMapLoose,
        object: copyObjectLoose,
        regExp: copyRegExp,
        set: copySetLoose,
    };
    var DEFAULT_STRICT_OPTIONS = assign({}, DEFAULT_LOOSE_OPTIONS, {
        array: copyArrayStrict,
        map: copyMapStrict,
        object: copyObjectStrict,
        set: copySetStrict,
    });
    /**
     * Get the copiers used for each specific object tag.
     */
    function getTagSpecificCopiers(options) {
        return {
            Arguments: options.object,
            Array: options.array,
            ArrayBuffer: options.arrayBuffer,
            Blob: options.blob,
            Boolean: copyPrimitiveWrapper,
            DataView: options.dataView,
            Date: options.date,
            Error: options.error,
            Float32Array: options.arrayBuffer,
            Float64Array: options.arrayBuffer,
            Int8Array: options.arrayBuffer,
            Int16Array: options.arrayBuffer,
            Int32Array: options.arrayBuffer,
            Map: options.map,
            Number: copyPrimitiveWrapper,
            Object: options.object,
            Promise: copySelf,
            RegExp: options.regExp,
            Set: options.set,
            String: copyPrimitiveWrapper,
            WeakMap: copySelf,
            WeakSet: copySelf,
            Uint8Array: options.arrayBuffer,
            Uint8ClampedArray: options.arrayBuffer,
            Uint16Array: options.arrayBuffer,
            Uint32Array: options.arrayBuffer,
            Uint64Array: options.arrayBuffer,
        };
    }
    /**
     * Create a custom copier based on the object-specific copy methods passed.
     */
    function createCopier(options) {
        var normalizedOptions = assign({}, DEFAULT_LOOSE_OPTIONS, options);
        var tagSpecificCopiers = getTagSpecificCopiers(normalizedOptions);
        var array = tagSpecificCopiers.Array, object = tagSpecificCopiers.Object;
        function copier(value, state) {
            state.prototype = state.Constructor = undefined;
            if (!value || typeof value !== 'object') {
                return value;
            }
            if (state.cache.has(value)) {
                return state.cache.get(value);
            }
            state.prototype = getPrototypeOf(value);
            state.Constructor = state.prototype && state.prototype.constructor;
            // plain objects
            if (!state.Constructor || state.Constructor === Object) {
                return object(value, state);
            }
            // arrays
            if (isArray$1(value)) {
                return array(value, state);
            }
            var tagSpecificCopier = tagSpecificCopiers[getTag(value)];
            if (tagSpecificCopier) {
                return tagSpecificCopier(value, state);
            }
            return typeof value.then === 'function' ? value : object(value, state);
        }
        return function copy(value) {
            return copier(value, {
                Constructor: undefined,
                cache: createCache(),
                copier: copier,
                prototype: undefined,
            });
        };
    }
    /**
     * Create a custom copier based on the object-specific copy methods passed, defaulting to the
     * same internals as `copyStrict`.
     */
    function createStrictCopier(options) {
        return createCopier(assign({}, DEFAULT_STRICT_OPTIONS, options));
    }
    /**
     * Copy an value deeply as much as possible, where strict recreation of object properties
     * are maintained. All properties (including non-enumerable ones) are copied with their
     * original property descriptors on both objects and arrays.
     */
    createStrictCopier({});
    /**
     * Copy an value deeply as much as possible.
     */
    var index$2 = createCopier({});

    function asyncToken(instance, getToken) {
        instance.interceptors.request.use(function (config) {
            return getToken().then((accessToken) => {
                config.headers.set('Authorization', `Bearer ${accessToken}`);
                return config;
            });
        });
    }

    function getDefaultExportFromCjs (x) {
    	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
    }

    function getDefaultExportFromNamespaceIfNotNamed (n) {
    	return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
    }

    var browser = {exports: {}};

    var hasRequiredBrowser;

    function requireBrowser () {
    	if (hasRequiredBrowser) return browser.exports;
    	hasRequiredBrowser = 1;
    	// shim for using process in browser
    	var process = browser.exports = {};

    	// cached from whatever global is present so that test runners that stub it
    	// don't break things.  But we need to wrap it in a try catch in case it is
    	// wrapped in strict mode code which doesn't define any globals.  It's inside a
    	// function because try/catches deoptimize in certain engines.

    	var cachedSetTimeout;
    	var cachedClearTimeout;

    	function defaultSetTimout() {
    	    throw new Error('setTimeout has not been defined');
    	}
    	function defaultClearTimeout () {
    	    throw new Error('clearTimeout has not been defined');
    	}
    	(function () {
    	    try {
    	        if (typeof setTimeout === 'function') {
    	            cachedSetTimeout = setTimeout;
    	        } else {
    	            cachedSetTimeout = defaultSetTimout;
    	        }
    	    } catch (e) {
    	        cachedSetTimeout = defaultSetTimout;
    	    }
    	    try {
    	        if (typeof clearTimeout === 'function') {
    	            cachedClearTimeout = clearTimeout;
    	        } else {
    	            cachedClearTimeout = defaultClearTimeout;
    	        }
    	    } catch (e) {
    	        cachedClearTimeout = defaultClearTimeout;
    	    }
    	} ());
    	function runTimeout(fun) {
    	    if (cachedSetTimeout === setTimeout) {
    	        //normal enviroments in sane situations
    	        return setTimeout(fun, 0);
    	    }
    	    // if setTimeout wasn't available but was latter defined
    	    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
    	        cachedSetTimeout = setTimeout;
    	        return setTimeout(fun, 0);
    	    }
    	    try {
    	        // when when somebody has screwed with setTimeout but no I.E. maddness
    	        return cachedSetTimeout(fun, 0);
    	    } catch(e){
    	        try {
    	            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
    	            return cachedSetTimeout.call(null, fun, 0);
    	        } catch(e){
    	            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
    	            return cachedSetTimeout.call(this, fun, 0);
    	        }
    	    }


    	}
    	function runClearTimeout(marker) {
    	    if (cachedClearTimeout === clearTimeout) {
    	        //normal enviroments in sane situations
    	        return clearTimeout(marker);
    	    }
    	    // if clearTimeout wasn't available but was latter defined
    	    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
    	        cachedClearTimeout = clearTimeout;
    	        return clearTimeout(marker);
    	    }
    	    try {
    	        // when when somebody has screwed with setTimeout but no I.E. maddness
    	        return cachedClearTimeout(marker);
    	    } catch (e){
    	        try {
    	            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
    	            return cachedClearTimeout.call(null, marker);
    	        } catch (e){
    	            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
    	            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
    	            return cachedClearTimeout.call(this, marker);
    	        }
    	    }



    	}
    	var queue = [];
    	var draining = false;
    	var currentQueue;
    	var queueIndex = -1;

    	function cleanUpNextTick() {
    	    if (!draining || !currentQueue) {
    	        return;
    	    }
    	    draining = false;
    	    if (currentQueue.length) {
    	        queue = currentQueue.concat(queue);
    	    } else {
    	        queueIndex = -1;
    	    }
    	    if (queue.length) {
    	        drainQueue();
    	    }
    	}

    	function drainQueue() {
    	    if (draining) {
    	        return;
    	    }
    	    var timeout = runTimeout(cleanUpNextTick);
    	    draining = true;

    	    var len = queue.length;
    	    while(len) {
    	        currentQueue = queue;
    	        queue = [];
    	        while (++queueIndex < len) {
    	            if (currentQueue) {
    	                currentQueue[queueIndex].run();
    	            }
    	        }
    	        queueIndex = -1;
    	        len = queue.length;
    	    }
    	    currentQueue = null;
    	    draining = false;
    	    runClearTimeout(timeout);
    	}

    	process.nextTick = function (fun) {
    	    var args = new Array(arguments.length - 1);
    	    if (arguments.length > 1) {
    	        for (var i = 1; i < arguments.length; i++) {
    	            args[i - 1] = arguments[i];
    	        }
    	    }
    	    queue.push(new Item(fun, args));
    	    if (queue.length === 1 && !draining) {
    	        runTimeout(drainQueue);
    	    }
    	};

    	// v8 likes predictible objects
    	function Item(fun, array) {
    	    this.fun = fun;
    	    this.array = array;
    	}
    	Item.prototype.run = function () {
    	    this.fun.apply(null, this.array);
    	};
    	process.title = 'browser';
    	process.browser = true;
    	process.env = {};
    	process.argv = [];
    	process.version = ''; // empty string to avoid regexp issues
    	process.versions = {};

    	function noop() {}

    	process.on = noop;
    	process.addListener = noop;
    	process.once = noop;
    	process.off = noop;
    	process.removeListener = noop;
    	process.removeAllListeners = noop;
    	process.emit = noop;
    	process.prependListener = noop;
    	process.prependOnceListener = noop;

    	process.listeners = function (name) { return [] };

    	process.binding = function (name) {
    	    throw new Error('process.binding is not supported');
    	};

    	process.cwd = function () { return '/' };
    	process.chdir = function (dir) {
    	    throw new Error('process.chdir is not supported');
    	};
    	process.umask = function() { return 0; };
    	return browser.exports;
    }

    var browserExports = requireBrowser();
    var process$1 = /*@__PURE__*/getDefaultExportFromCjs(browserExports);

    function isNode() {
        /**
         * Polyfills of 'process' might set process.browser === true
         *
         * See:
         * https://github.com/webpack/node-libs-browser/blob/master/mock/process.js#L8
         * https://github.com/defunctzombie/node-process/blob/master/browser.js#L156
         **/
        return typeof process$1 !== 'undefined' && !process$1.browser;
    }
    function isReactNative() {
        return (typeof window !== 'undefined' &&
            'navigator' in window &&
            'product' in window.navigator &&
            window.navigator.product === 'ReactNative');
    }
    function getNodeVersion() {
        return process$1.versions && process$1.versions.node ? `v${process$1.versions.node}` : process$1.version;
    }
    function getWindow() {
        return window;
    }
    function noop() {
        return undefined;
    }

    const delay = (ms) => new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
    const defaultWait = (attempts) => {
        return Math.pow(Math.SQRT2, attempts);
    };
    function rateLimit(instance, maxRetry = 5) {
        const { responseLogger = noop, requestLogger = noop } = instance.defaults;
        instance.interceptors.request.use(function (config) {
            requestLogger(config);
            return config;
        }, function (error) {
            requestLogger(error);
            return Promise.reject(error);
        });
        instance.interceptors.response.use(function (response) {
            // we don't need to do anything here
            responseLogger(response);
            return response;
        }, async function (error) {
            const { response } = error;
            const { config } = error;
            responseLogger(error);
            // Do not retry if it is disabled or no request config exists (not an axios error)
            if (!config || !instance.defaults.retryOnError) {
                return Promise.reject(error);
            }
            // Retried already for max attempts
            const doneAttempts = config.attempts || 1;
            if (doneAttempts > maxRetry) {
                error.attempts = config.attempts;
                return Promise.reject(error);
            }
            let retryErrorType = null;
            let wait = defaultWait(doneAttempts);
            // Errors without response did not receive anything from the server
            if (!response) {
                retryErrorType = 'Connection';
            }
            else if (response.status >= 500 && response.status < 600) {
                // 5** errors are server related
                retryErrorType = `Server ${response.status}`;
            }
            else if (response.status === 429) {
                // 429 errors are exceeded rate limit exceptions
                retryErrorType = 'Rate limit';
                // all headers are lowercased by axios https://github.com/mzabriskie/axios/issues/413
                if (response.headers && error.response.headers['x-contentful-ratelimit-reset']) {
                    wait = response.headers['x-contentful-ratelimit-reset'];
                }
            }
            if (retryErrorType) {
                // convert to ms and add jitter
                wait = Math.floor(wait * 1000 + Math.random() * 200 + 500);
                instance.defaults.logHandler('warning', `${retryErrorType} error occurred. Waiting for ${wait} ms before retrying...`);
                // increase attempts counter
                config.attempts = doneAttempts + 1;
                /* Somehow between the interceptor and retrying the request the httpAgent/httpsAgent gets transformed from an Agent-like object
                 to a regular object, causing failures on retries after rate limits. Removing these properties here fixes the error, but retry
                 requests still use the original http/httpsAgent property */
                delete config.httpAgent;
                delete config.httpsAgent;
                return delay(wait).then(() => instance(config));
            }
            return Promise.reject(error);
        });
    }

    /** Detect free variable `global` from Node.js. */

    var _freeGlobal;
    var hasRequired_freeGlobal;

    function require_freeGlobal () {
    	if (hasRequired_freeGlobal) return _freeGlobal;
    	hasRequired_freeGlobal = 1;
    	var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

    	_freeGlobal = freeGlobal;
    	return _freeGlobal;
    }

    var _root;
    var hasRequired_root;

    function require_root () {
    	if (hasRequired_root) return _root;
    	hasRequired_root = 1;
    	var freeGlobal = require_freeGlobal();

    	/** Detect free variable `self`. */
    	var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

    	/** Used as a reference to the global object. */
    	var root = freeGlobal || freeSelf || Function('return this')();

    	_root = root;
    	return _root;
    }

    var _Symbol;
    var hasRequired_Symbol;

    function require_Symbol () {
    	if (hasRequired_Symbol) return _Symbol;
    	hasRequired_Symbol = 1;
    	var root = require_root();

    	/** Built-in value references. */
    	var Symbol = root.Symbol;

    	_Symbol = Symbol;
    	return _Symbol;
    }

    var _getRawTag;
    var hasRequired_getRawTag;

    function require_getRawTag () {
    	if (hasRequired_getRawTag) return _getRawTag;
    	hasRequired_getRawTag = 1;
    	var Symbol = require_Symbol();

    	/** Used for built-in method references. */
    	var objectProto = Object.prototype;

    	/** Used to check objects for own properties. */
    	var hasOwnProperty = objectProto.hasOwnProperty;

    	/**
    	 * Used to resolve the
    	 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
    	 * of values.
    	 */
    	var nativeObjectToString = objectProto.toString;

    	/** Built-in value references. */
    	var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

    	/**
    	 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
    	 *
    	 * @private
    	 * @param {*} value The value to query.
    	 * @returns {string} Returns the raw `toStringTag`.
    	 */
    	function getRawTag(value) {
    	  var isOwn = hasOwnProperty.call(value, symToStringTag),
    	      tag = value[symToStringTag];

    	  try {
    	    value[symToStringTag] = undefined;
    	    var unmasked = true;
    	  } catch (e) {}

    	  var result = nativeObjectToString.call(value);
    	  if (unmasked) {
    	    if (isOwn) {
    	      value[symToStringTag] = tag;
    	    } else {
    	      delete value[symToStringTag];
    	    }
    	  }
    	  return result;
    	}

    	_getRawTag = getRawTag;
    	return _getRawTag;
    }

    /** Used for built-in method references. */

    var _objectToString;
    var hasRequired_objectToString;

    function require_objectToString () {
    	if (hasRequired_objectToString) return _objectToString;
    	hasRequired_objectToString = 1;
    	var objectProto = Object.prototype;

    	/**
    	 * Used to resolve the
    	 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
    	 * of values.
    	 */
    	var nativeObjectToString = objectProto.toString;

    	/**
    	 * Converts `value` to a string using `Object.prototype.toString`.
    	 *
    	 * @private
    	 * @param {*} value The value to convert.
    	 * @returns {string} Returns the converted string.
    	 */
    	function objectToString(value) {
    	  return nativeObjectToString.call(value);
    	}

    	_objectToString = objectToString;
    	return _objectToString;
    }

    var _baseGetTag;
    var hasRequired_baseGetTag;

    function require_baseGetTag () {
    	if (hasRequired_baseGetTag) return _baseGetTag;
    	hasRequired_baseGetTag = 1;
    	var Symbol = require_Symbol(),
    	    getRawTag = require_getRawTag(),
    	    objectToString = require_objectToString();

    	/** `Object#toString` result references. */
    	var nullTag = '[object Null]',
    	    undefinedTag = '[object Undefined]';

    	/** Built-in value references. */
    	var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

    	/**
    	 * The base implementation of `getTag` without fallbacks for buggy environments.
    	 *
    	 * @private
    	 * @param {*} value The value to query.
    	 * @returns {string} Returns the `toStringTag`.
    	 */
    	function baseGetTag(value) {
    	  if (value == null) {
    	    return value === undefined ? undefinedTag : nullTag;
    	  }
    	  return (symToStringTag && symToStringTag in Object(value))
    	    ? getRawTag(value)
    	    : objectToString(value);
    	}

    	_baseGetTag = baseGetTag;
    	return _baseGetTag;
    }

    /**
     * Checks if `value` is classified as an `Array` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array, else `false`.
     * @example
     *
     * _.isArray([1, 2, 3]);
     * // => true
     *
     * _.isArray(document.body.children);
     * // => false
     *
     * _.isArray('abc');
     * // => false
     *
     * _.isArray(_.noop);
     * // => false
     */

    var isArray_1;
    var hasRequiredIsArray;

    function requireIsArray () {
    	if (hasRequiredIsArray) return isArray_1;
    	hasRequiredIsArray = 1;
    	var isArray = Array.isArray;

    	isArray_1 = isArray;
    	return isArray_1;
    }

    /**
     * Checks if `value` is object-like. A value is object-like if it's not `null`
     * and has a `typeof` result of "object".
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
     * @example
     *
     * _.isObjectLike({});
     * // => true
     *
     * _.isObjectLike([1, 2, 3]);
     * // => true
     *
     * _.isObjectLike(_.noop);
     * // => false
     *
     * _.isObjectLike(null);
     * // => false
     */

    var isObjectLike_1;
    var hasRequiredIsObjectLike;

    function requireIsObjectLike () {
    	if (hasRequiredIsObjectLike) return isObjectLike_1;
    	hasRequiredIsObjectLike = 1;
    	function isObjectLike(value) {
    	  return value != null && typeof value == 'object';
    	}

    	isObjectLike_1 = isObjectLike;
    	return isObjectLike_1;
    }

    var isString_1;
    var hasRequiredIsString;

    function requireIsString () {
    	if (hasRequiredIsString) return isString_1;
    	hasRequiredIsString = 1;
    	var baseGetTag = require_baseGetTag(),
    	    isArray = requireIsArray(),
    	    isObjectLike = requireIsObjectLike();

    	/** `Object#toString` result references. */
    	var stringTag = '[object String]';

    	/**
    	 * Checks if `value` is classified as a `String` primitive or object.
    	 *
    	 * @static
    	 * @since 0.1.0
    	 * @memberOf _
    	 * @category Lang
    	 * @param {*} value The value to check.
    	 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
    	 * @example
    	 *
    	 * _.isString('abc');
    	 * // => true
    	 *
    	 * _.isString(1);
    	 * // => false
    	 */
    	function isString(value) {
    	  return typeof value == 'string' ||
    	    (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
    	}

    	isString_1 = isString;
    	return isString_1;
    }

    var isStringExports = requireIsString();
    var isString$1 = /*@__PURE__*/getDefaultExportFromCjs(isStringExports);

    class AbortError extends Error {
        name = 'AbortError';
        constructor() {
            super('Throttled function aborted');
        }
    }
    /**
     * Throttle promise-returning/async/normal functions.
     *
     * It rate-limits function calls without discarding them, making it ideal for external API interactions where avoiding call loss is crucial.
     *
     * @returns A throttle function.
     *
     * Both the `limit` and `interval` options must be specified.
     *
     * @example
     * ```
     * import pThrottle from './PThrottle';
     *
     * const now = Date.now();
     *
     * const throttle = pThrottle({
     *   limit: 2,
     *   interval: 1000
     * });
     *
     * const throttled = throttle(async index => {
     *   const secDiff = ((Date.now() - now) / 1000).toFixed();
     *   return `${index}: ${secDiff}s`;
     * });
     *
     * for (let index = 1; index <= 6; index++) {
     *   (async () => {
     *     console.log(await throttled(index));
     *   })();
     * }
     * //=> 1: 0s
     * //=> 2: 0s
     * //=> 3: 1s
     * //=> 4: 1s
     * //=> 5: 2s
     * //=> 6: 2s
     * ```
     */
    function pThrottle({ limit, interval, strict, onDelay }) {
        if (!Number.isFinite(limit)) {
            throw new TypeError('Expected `limit` to be a finite number');
        }
        if (!Number.isFinite(interval)) {
            throw new TypeError('Expected `interval` to be a finite number');
        }
        const queue = new Map();
        let currentTick = 0;
        let activeCount = 0;
        function windowedDelay() {
            const now = Date.now();
            if (now - currentTick > interval) {
                activeCount = 1;
                currentTick = now;
                return 0;
            }
            if (activeCount < limit) {
                activeCount++;
            }
            else {
                currentTick += interval;
                activeCount = 1;
            }
            return currentTick - now;
        }
        const getDelay = windowedDelay;
        return function (function_) {
            const throttled = function (...arguments_) {
                if (!throttled.isEnabled) {
                    return (async () => function_.apply(this, arguments_))();
                }
                let timeoutId;
                return new Promise((resolve, reject) => {
                    const execute = () => {
                        resolve(function_.apply(this, arguments_));
                        queue.delete(timeoutId);
                    };
                    const delay = getDelay();
                    if (delay > 0) {
                        timeoutId = setTimeout(execute, delay);
                        queue.set(timeoutId, reject);
                        onDelay?.();
                    }
                    else {
                        execute();
                    }
                });
            };
            throttled.abort = () => {
                for (const timeout of queue.keys()) {
                    clearTimeout(timeout);
                    queue.get(timeout)(new AbortError());
                }
                queue.clear();
            };
            throttled.isEnabled = true;
            Object.defineProperty(throttled, 'queueSize', {
                get() {
                    return queue.size;
                },
            });
            return throttled;
        };
    }

    const PERCENTAGE_REGEX = /(?<value>\d+)(%)/;
    function calculateLimit(type, max = 7) {
        let limit = max;
        if (PERCENTAGE_REGEX.test(type)) {
            const groups = type.match(PERCENTAGE_REGEX)?.groups;
            if (groups && groups.value) {
                const percentage = parseInt(groups.value) / 100;
                limit = Math.round(max * percentage);
            }
        }
        return Math.min(30, Math.max(1, limit));
    }
    function createThrottle(limit, logger) {
        logger('info', `Throttle request to ${limit}/s`);
        return pThrottle({
            limit,
            interval: 1000,
            strict: false,
        });
    }
    var rateLimitThrottle = (axiosInstance, type = 'auto') => {
        const { logHandler = noop } = axiosInstance.defaults;
        let limit = isString$1(type) ? calculateLimit(type) : calculateLimit('auto', type);
        let throttle = createThrottle(limit, logHandler);
        let isCalculated = false;
        let requestInterceptorId = axiosInstance.interceptors.request.use((config) => {
            return throttle(() => config)();
        }, function (error) {
            return Promise.reject(error);
        });
        const responseInterceptorId = axiosInstance.interceptors.response.use((response) => {
            if (!isCalculated &&
                isString$1(type) &&
                (type === 'auto' || PERCENTAGE_REGEX.test(type)) &&
                response.headers &&
                response.headers['x-contentful-ratelimit-second-limit']) {
                const rawLimit = parseInt(response.headers['x-contentful-ratelimit-second-limit']);
                const nextLimit = calculateLimit(type, rawLimit);
                if (nextLimit !== limit) {
                    if (requestInterceptorId) {
                        axiosInstance.interceptors.request.eject(requestInterceptorId);
                    }
                    limit = nextLimit;
                    throttle = createThrottle(nextLimit, logHandler);
                    requestInterceptorId = axiosInstance.interceptors.request.use((config) => {
                        return throttle(() => config)();
                    }, function (error) {
                        return Promise.reject(error);
                    });
                }
                isCalculated = true;
            }
            return response;
        }, function (error) {
            return Promise.reject(error);
        });
        return () => {
            axiosInstance.interceptors.request.eject(requestInterceptorId);
            axiosInstance.interceptors.response.eject(responseInterceptorId);
        };
    };

    var type;
    var hasRequiredType;

    function requireType () {
    	if (hasRequiredType) return type;
    	hasRequiredType = 1;

    	/** @type {import('./type')} */
    	type = TypeError;
    	return type;
    }

    var inherits;
    if (typeof Object.create === 'function'){
      inherits = function inherits(ctor, superCtor) {
        // implementation from standard node.js 'util' module
        ctor.super_ = superCtor;
        ctor.prototype = Object.create(superCtor.prototype, {
          constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
          }
        });
      };
    } else {
      inherits = function inherits(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function () {};
        TempCtor.prototype = superCtor.prototype;
        ctor.prototype = new TempCtor();
        ctor.prototype.constructor = ctor;
      };
    }

    // Copyright Joyent, Inc. and other Node contributors.
    //
    // Permission is hereby granted, free of charge, to any person obtaining a
    // copy of this software and associated documentation files (the
    // "Software"), to deal in the Software without restriction, including
    // without limitation the rights to use, copy, modify, merge, publish,
    // distribute, sublicense, and/or sell copies of the Software, and to permit
    // persons to whom the Software is furnished to do so, subject to the
    // following conditions:
    //
    // The above copyright notice and this permission notice shall be included
    // in all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
    // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    // USE OR OTHER DEALINGS IN THE SOFTWARE.

    var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
      function getOwnPropertyDescriptors(obj) {
        var keys = Object.keys(obj);
        var descriptors = {};
        for (var i = 0; i < keys.length; i++) {
          descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
        }
        return descriptors;
      };

    var formatRegExp = /%[sdj%]/g;
    function format(f) {
      if (!isString(f)) {
        var objects = [];
        for (var i = 0; i < arguments.length; i++) {
          objects.push(inspect(arguments[i]));
        }
        return objects.join(' ');
      }

      var i = 1;
      var args = arguments;
      var len = args.length;
      var str = String(f).replace(formatRegExp, function(x) {
        if (x === '%%') return '%';
        if (i >= len) return x;
        switch (x) {
          case '%s': return String(args[i++]);
          case '%d': return Number(args[i++]);
          case '%j':
            try {
              return JSON.stringify(args[i++]);
            } catch (_) {
              return '[Circular]';
            }
          default:
            return x;
        }
      });
      for (var x = args[i]; i < len; x = args[++i]) {
        if (isNull(x) || !isObject(x)) {
          str += ' ' + x;
        } else {
          str += ' ' + inspect(x);
        }
      }
      return str;
    }

    // Mark that a method should not be used.
    // Returns a modified function which warns once by default.
    // If --no-deprecation is set, then it is a no-op.
    function deprecate(fn, msg) {
      // Allow for deprecating things in the process of starting up.
      if (isUndefined(global.process)) {
        return function() {
          return deprecate(fn, msg).apply(this, arguments);
        };
      }

      if (process$1.noDeprecation === true) {
        return fn;
      }

      var warned = false;
      function deprecated() {
        if (!warned) {
          if (process$1.throwDeprecation) {
            throw new Error(msg);
          } else if (process$1.traceDeprecation) {
            console.trace(msg);
          } else {
            console.error(msg);
          }
          warned = true;
        }
        return fn.apply(this, arguments);
      }

      return deprecated;
    }

    var debugs = {};
    var debugEnviron;
    function debuglog(set) {
      if (isUndefined(debugEnviron))
        debugEnviron = process$1.env.NODE_DEBUG || '';
      set = set.toUpperCase();
      if (!debugs[set]) {
        if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
          var pid = 0;
          debugs[set] = function() {
            var msg = format.apply(null, arguments);
            console.error('%s %d: %s', set, pid, msg);
          };
        } else {
          debugs[set] = function() {};
        }
      }
      return debugs[set];
    }

    /**
     * Echos the value of a value. Trys to print the value out
     * in the best way possible given the different types.
     *
     * @param {Object} obj The object to print out.
     * @param {Object} opts Optional options object that alters the output.
     */
    /* legacy: obj, showHidden, depth, colors*/
    function inspect(obj, opts) {
      // default options
      var ctx = {
        seen: [],
        stylize: stylizeNoColor
      };
      // legacy...
      if (arguments.length >= 3) ctx.depth = arguments[2];
      if (arguments.length >= 4) ctx.colors = arguments[3];
      if (isBoolean(opts)) {
        // legacy...
        ctx.showHidden = opts;
      } else if (opts) {
        // got an "options" object
        _extend(ctx, opts);
      }
      // set default options
      if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
      if (isUndefined(ctx.depth)) ctx.depth = 2;
      if (isUndefined(ctx.colors)) ctx.colors = false;
      if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
      if (ctx.colors) ctx.stylize = stylizeWithColor;
      return formatValue(ctx, obj, ctx.depth);
    }

    // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
    inspect.colors = {
      'bold' : [1, 22],
      'italic' : [3, 23],
      'underline' : [4, 24],
      'inverse' : [7, 27],
      'white' : [37, 39],
      'grey' : [90, 39],
      'black' : [30, 39],
      'blue' : [34, 39],
      'cyan' : [36, 39],
      'green' : [32, 39],
      'magenta' : [35, 39],
      'red' : [31, 39],
      'yellow' : [33, 39]
    };

    // Don't use 'blue' not visible on cmd.exe
    inspect.styles = {
      'special': 'cyan',
      'number': 'yellow',
      'boolean': 'yellow',
      'undefined': 'grey',
      'null': 'bold',
      'string': 'green',
      'date': 'magenta',
      // "name": intentionally not styling
      'regexp': 'red'
    };


    function stylizeWithColor(str, styleType) {
      var style = inspect.styles[styleType];

      if (style) {
        return '\u001b[' + inspect.colors[style][0] + 'm' + str +
               '\u001b[' + inspect.colors[style][1] + 'm';
      } else {
        return str;
      }
    }


    function stylizeNoColor(str, styleType) {
      return str;
    }


    function arrayToHash(array) {
      var hash = {};

      array.forEach(function(val, idx) {
        hash[val] = true;
      });

      return hash;
    }


    function formatValue(ctx, value, recurseTimes) {
      // Provide a hook for user-specified inspect functions.
      // Check that value is an object with an inspect function on it
      if (ctx.customInspect &&
          value &&
          isFunction(value.inspect) &&
          // Filter out the util module, it's inspect function is special
          value.inspect !== inspect &&
          // Also filter out any prototype objects using the circular check.
          !(value.constructor && value.constructor.prototype === value)) {
        var ret = value.inspect(recurseTimes, ctx);
        if (!isString(ret)) {
          ret = formatValue(ctx, ret, recurseTimes);
        }
        return ret;
      }

      // Primitive types cannot have properties
      var primitive = formatPrimitive(ctx, value);
      if (primitive) {
        return primitive;
      }

      // Look up the keys of the object.
      var keys = Object.keys(value);
      var visibleKeys = arrayToHash(keys);

      if (ctx.showHidden) {
        keys = Object.getOwnPropertyNames(value);
      }

      // IE doesn't make error fields non-enumerable
      // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
      if (isError(value)
          && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
        return formatError(value);
      }

      // Some type of object without properties can be shortcutted.
      if (keys.length === 0) {
        if (isFunction(value)) {
          var name = value.name ? ': ' + value.name : '';
          return ctx.stylize('[Function' + name + ']', 'special');
        }
        if (isRegExp(value)) {
          return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
        }
        if (isDate(value)) {
          return ctx.stylize(Date.prototype.toString.call(value), 'date');
        }
        if (isError(value)) {
          return formatError(value);
        }
      }

      var base = '', array = false, braces = ['{', '}'];

      // Make Array say that they are Array
      if (isArray(value)) {
        array = true;
        braces = ['[', ']'];
      }

      // Make functions say that they are functions
      if (isFunction(value)) {
        var n = value.name ? ': ' + value.name : '';
        base = ' [Function' + n + ']';
      }

      // Make RegExps say that they are RegExps
      if (isRegExp(value)) {
        base = ' ' + RegExp.prototype.toString.call(value);
      }

      // Make dates with properties first say the date
      if (isDate(value)) {
        base = ' ' + Date.prototype.toUTCString.call(value);
      }

      // Make error with message first say the error
      if (isError(value)) {
        base = ' ' + formatError(value);
      }

      if (keys.length === 0 && (!array || value.length == 0)) {
        return braces[0] + base + braces[1];
      }

      if (recurseTimes < 0) {
        if (isRegExp(value)) {
          return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
        } else {
          return ctx.stylize('[Object]', 'special');
        }
      }

      ctx.seen.push(value);

      var output;
      if (array) {
        output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
      } else {
        output = keys.map(function(key) {
          return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
        });
      }

      ctx.seen.pop();

      return reduceToSingleString(output, base, braces);
    }


    function formatPrimitive(ctx, value) {
      if (isUndefined(value))
        return ctx.stylize('undefined', 'undefined');
      if (isString(value)) {
        var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                                 .replace(/'/g, "\\'")
                                                 .replace(/\\"/g, '"') + '\'';
        return ctx.stylize(simple, 'string');
      }
      if (isNumber(value))
        return ctx.stylize('' + value, 'number');
      if (isBoolean(value))
        return ctx.stylize('' + value, 'boolean');
      // For some reason typeof null is "object", so special case here.
      if (isNull(value))
        return ctx.stylize('null', 'null');
    }


    function formatError(value) {
      return '[' + Error.prototype.toString.call(value) + ']';
    }


    function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
      var output = [];
      for (var i = 0, l = value.length; i < l; ++i) {
        if (hasOwnProperty(value, String(i))) {
          output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
              String(i), true));
        } else {
          output.push('');
        }
      }
      keys.forEach(function(key) {
        if (!key.match(/^\d+$/)) {
          output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
              key, true));
        }
      });
      return output;
    }


    function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
      var name, str, desc;
      desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
      if (desc.get) {
        if (desc.set) {
          str = ctx.stylize('[Getter/Setter]', 'special');
        } else {
          str = ctx.stylize('[Getter]', 'special');
        }
      } else {
        if (desc.set) {
          str = ctx.stylize('[Setter]', 'special');
        }
      }
      if (!hasOwnProperty(visibleKeys, key)) {
        name = '[' + key + ']';
      }
      if (!str) {
        if (ctx.seen.indexOf(desc.value) < 0) {
          if (isNull(recurseTimes)) {
            str = formatValue(ctx, desc.value, null);
          } else {
            str = formatValue(ctx, desc.value, recurseTimes - 1);
          }
          if (str.indexOf('\n') > -1) {
            if (array) {
              str = str.split('\n').map(function(line) {
                return '  ' + line;
              }).join('\n').substr(2);
            } else {
              str = '\n' + str.split('\n').map(function(line) {
                return '   ' + line;
              }).join('\n');
            }
          }
        } else {
          str = ctx.stylize('[Circular]', 'special');
        }
      }
      if (isUndefined(name)) {
        if (array && key.match(/^\d+$/)) {
          return str;
        }
        name = JSON.stringify('' + key);
        if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
          name = name.substr(1, name.length - 2);
          name = ctx.stylize(name, 'name');
        } else {
          name = name.replace(/'/g, "\\'")
                     .replace(/\\"/g, '"')
                     .replace(/(^"|"$)/g, "'");
          name = ctx.stylize(name, 'string');
        }
      }

      return name + ': ' + str;
    }


    function reduceToSingleString(output, base, braces) {
      var length = output.reduce(function(prev, cur) {
        if (cur.indexOf('\n') >= 0) ;
        return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
      }, 0);

      if (length > 60) {
        return braces[0] +
               (base === '' ? '' : base + '\n ') +
               ' ' +
               output.join(',\n  ') +
               ' ' +
               braces[1];
      }

      return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
    }


    // NOTE: These type checking functions intentionally don't use `instanceof`
    // because it is fragile and can be easily faked with `Object.create()`.
    function isArray(ar) {
      return Array.isArray(ar);
    }

    function isBoolean(arg) {
      return typeof arg === 'boolean';
    }

    function isNull(arg) {
      return arg === null;
    }

    function isNullOrUndefined(arg) {
      return arg == null;
    }

    function isNumber(arg) {
      return typeof arg === 'number';
    }

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

    function isSymbol(arg) {
      return typeof arg === 'symbol';
    }

    function isUndefined(arg) {
      return arg === void 0;
    }

    function isRegExp(re) {
      return isObject(re) && objectToString(re) === '[object RegExp]';
    }

    function isObject(arg) {
      return typeof arg === 'object' && arg !== null;
    }

    function isDate(d) {
      return isObject(d) && objectToString(d) === '[object Date]';
    }

    function isError(e) {
      return isObject(e) &&
          (objectToString(e) === '[object Error]' || e instanceof Error);
    }

    function isFunction(arg) {
      return typeof arg === 'function';
    }

    function isPrimitive(arg) {
      return arg === null ||
             typeof arg === 'boolean' ||
             typeof arg === 'number' ||
             typeof arg === 'string' ||
             typeof arg === 'symbol' ||  // ES6 symbol
             typeof arg === 'undefined';
    }

    function isBuffer(maybeBuf) {
      return Buffer.isBuffer(maybeBuf);
    }

    function objectToString(o) {
      return Object.prototype.toString.call(o);
    }


    function pad(n) {
      return n < 10 ? '0' + n.toString(10) : n.toString(10);
    }


    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                  'Oct', 'Nov', 'Dec'];

    // 26 Feb 16:19:34
    function timestamp() {
      var d = new Date();
      var time = [pad(d.getHours()),
                  pad(d.getMinutes()),
                  pad(d.getSeconds())].join(':');
      return [d.getDate(), months[d.getMonth()], time].join(' ');
    }


    // log is just a thin wrapper to console.log that prepends a timestamp
    function log() {
      console.log('%s - %s', timestamp(), format.apply(null, arguments));
    }

    function _extend(origin, add) {
      // Don't do anything if add isn't an object
      if (!add || !isObject(add)) return origin;

      var keys = Object.keys(add);
      var i = keys.length;
      while (i--) {
        origin[keys[i]] = add[keys[i]];
      }
      return origin;
    }
    function hasOwnProperty(obj, prop) {
      return Object.prototype.hasOwnProperty.call(obj, prop);
    }

    var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;

    function promisify(original) {
      if (typeof original !== 'function')
        throw new TypeError('The "original" argument must be of type Function');

      if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
        var fn = original[kCustomPromisifiedSymbol];
        if (typeof fn !== 'function') {
          throw new TypeError('The "util.promisify.custom" argument must be of type Function');
        }
        Object.defineProperty(fn, kCustomPromisifiedSymbol, {
          value: fn, enumerable: false, writable: false, configurable: true
        });
        return fn;
      }

      function fn() {
        var promiseResolve, promiseReject;
        var promise = new Promise(function (resolve, reject) {
          promiseResolve = resolve;
          promiseReject = reject;
        });

        var args = [];
        for (var i = 0; i < arguments.length; i++) {
          args.push(arguments[i]);
        }
        args.push(function (err, value) {
          if (err) {
            promiseReject(err);
          } else {
            promiseResolve(value);
          }
        });

        try {
          original.apply(this, args);
        } catch (err) {
          promiseReject(err);
        }

        return promise;
      }

      Object.setPrototypeOf(fn, Object.getPrototypeOf(original));

      if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
        value: fn, enumerable: false, writable: false, configurable: true
      });
      return Object.defineProperties(
        fn,
        getOwnPropertyDescriptors(original)
      );
    }

    promisify.custom = kCustomPromisifiedSymbol;

    function callbackifyOnRejected(reason, cb) {
      // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
      // Because `null` is a special error value in callbacks which means "no error
      // occurred", we error-wrap so the callback consumer can distinguish between
      // "the promise rejected with null" or "the promise fulfilled with undefined".
      if (!reason) {
        var newReason = new Error('Promise was rejected with a falsy value');
        newReason.reason = reason;
        reason = newReason;
      }
      return cb(reason);
    }

    function callbackify(original) {
      if (typeof original !== 'function') {
        throw new TypeError('The "original" argument must be of type Function');
      }

      // We DO NOT return the promise as it gives the user a false sense that
      // the promise is actually somehow related to the callback's execution
      // and that the callback throwing will reject the promise.
      function callbackified() {
        var args = [];
        for (var i = 0; i < arguments.length; i++) {
          args.push(arguments[i]);
        }

        var maybeCb = args.pop();
        if (typeof maybeCb !== 'function') {
          throw new TypeError('The last argument must be of type Function');
        }
        var self = this;
        var cb = function() {
          return maybeCb.apply(self, arguments);
        };
        // In true node style we process the callback on `nextTick` with all the
        // implications (stack, `uncaughtException`, `async_hooks`)
        original.apply(this, args)
          .then(function(ret) { process$1.nextTick(cb.bind(null, null, ret)); },
            function(rej) { process$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); });
      }

      Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
      Object.defineProperties(callbackified, getOwnPropertyDescriptors(original));
      return callbackified;
    }

    var _polyfillNode_util = {
      inherits: inherits,
      _extend: _extend,
      log: log,
      isBuffer: isBuffer,
      isPrimitive: isPrimitive,
      isFunction: isFunction,
      isError: isError,
      isDate: isDate,
      isObject: isObject,
      isRegExp: isRegExp,
      isUndefined: isUndefined,
      isSymbol: isSymbol,
      isString: isString,
      isNumber: isNumber,
      isNullOrUndefined: isNullOrUndefined,
      isNull: isNull,
      isBoolean: isBoolean,
      isArray: isArray,
      inspect: inspect,
      deprecate: deprecate,
      format: format,
      debuglog: debuglog,
      promisify: promisify,
      callbackify: callbackify,
    };

    var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        _extend: _extend,
        callbackify: callbackify,
        debuglog: debuglog,
        default: _polyfillNode_util,
        deprecate: deprecate,
        format: format,
        inherits: inherits,
        inspect: inspect,
        isArray: isArray,
        isBoolean: isBoolean,
        isBuffer: isBuffer,
        isDate: isDate,
        isError: isError,
        isFunction: isFunction,
        isNull: isNull,
        isNullOrUndefined: isNullOrUndefined,
        isNumber: isNumber,
        isObject: isObject,
        isPrimitive: isPrimitive,
        isRegExp: isRegExp,
        isString: isString,
        isSymbol: isSymbol,
        isUndefined: isUndefined,
        log: log,
        promisify: promisify
    });

    var require$$0 = /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(_polyfillNode_util$1);

    var util_inspect;
    var hasRequiredUtil_inspect;

    function requireUtil_inspect () {
    	if (hasRequiredUtil_inspect) return util_inspect;
    	hasRequiredUtil_inspect = 1;
    	util_inspect = require$$0.inspect;
    	return util_inspect;
    }

    var objectInspect;
    var hasRequiredObjectInspect;

    function requireObjectInspect () {
    	if (hasRequiredObjectInspect) return objectInspect;
    	hasRequiredObjectInspect = 1;
    	var hasMap = typeof Map === 'function' && Map.prototype;
    	var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
    	var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
    	var mapForEach = hasMap && Map.prototype.forEach;
    	var hasSet = typeof Set === 'function' && Set.prototype;
    	var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
    	var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
    	var setForEach = hasSet && Set.prototype.forEach;
    	var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
    	var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
    	var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
    	var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
    	var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
    	var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
    	var booleanValueOf = Boolean.prototype.valueOf;
    	var objectToString = Object.prototype.toString;
    	var functionToString = Function.prototype.toString;
    	var $match = String.prototype.match;
    	var $slice = String.prototype.slice;
    	var $replace = String.prototype.replace;
    	var $toUpperCase = String.prototype.toUpperCase;
    	var $toLowerCase = String.prototype.toLowerCase;
    	var $test = RegExp.prototype.test;
    	var $concat = Array.prototype.concat;
    	var $join = Array.prototype.join;
    	var $arrSlice = Array.prototype.slice;
    	var $floor = Math.floor;
    	var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
    	var gOPS = Object.getOwnPropertySymbols;
    	var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
    	var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
    	// ie, `has-tostringtag/shams
    	var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
    	    ? Symbol.toStringTag
    	    : null;
    	var isEnumerable = Object.prototype.propertyIsEnumerable;

    	var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
    	    [].__proto__ === Array.prototype // eslint-disable-line no-proto
    	        ? function (O) {
    	            return O.__proto__; // eslint-disable-line no-proto
    	        }
    	        : null
    	);

    	function addNumericSeparator(num, str) {
    	    if (
    	        num === Infinity
    	        || num === -Infinity
    	        || num !== num
    	        || (num && num > -1e3 && num < 1000)
    	        || $test.call(/e/, str)
    	    ) {
    	        return str;
    	    }
    	    var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
    	    if (typeof num === 'number') {
    	        var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
    	        if (int !== num) {
    	            var intStr = String(int);
    	            var dec = $slice.call(str, intStr.length + 1);
    	            return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
    	        }
    	    }
    	    return $replace.call(str, sepRegex, '$&_');
    	}

    	var utilInspect = /*@__PURE__*/ requireUtil_inspect();
    	var inspectCustom = utilInspect.custom;
    	var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;

    	var quotes = {
    	    __proto__: null,
    	    'double': '"',
    	    single: "'"
    	};
    	var quoteREs = {
    	    __proto__: null,
    	    'double': /(["\\])/g,
    	    single: /(['\\])/g
    	};

    	objectInspect = function inspect_(obj, options, depth, seen) {
    	    var opts = options || {};

    	    if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) {
    	        throw new TypeError('option "quoteStyle" must be "single" or "double"');
    	    }
    	    if (
    	        has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
    	            ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
    	            : opts.maxStringLength !== null
    	        )
    	    ) {
    	        throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
    	    }
    	    var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
    	    if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
    	        throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
    	    }

    	    if (
    	        has(opts, 'indent')
    	        && opts.indent !== null
    	        && opts.indent !== '\t'
    	        && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
    	    ) {
    	        throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
    	    }
    	    if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
    	        throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
    	    }
    	    var numericSeparator = opts.numericSeparator;

    	    if (typeof obj === 'undefined') {
    	        return 'undefined';
    	    }
    	    if (obj === null) {
    	        return 'null';
    	    }
    	    if (typeof obj === 'boolean') {
    	        return obj ? 'true' : 'false';
    	    }

    	    if (typeof obj === 'string') {
    	        return inspectString(obj, opts);
    	    }
    	    if (typeof obj === 'number') {
    	        if (obj === 0) {
    	            return Infinity / obj > 0 ? '0' : '-0';
    	        }
    	        var str = String(obj);
    	        return numericSeparator ? addNumericSeparator(obj, str) : str;
    	    }
    	    if (typeof obj === 'bigint') {
    	        var bigIntStr = String(obj) + 'n';
    	        return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
    	    }

    	    var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
    	    if (typeof depth === 'undefined') { depth = 0; }
    	    if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
    	        return isArray(obj) ? '[Array]' : '[Object]';
    	    }

    	    var indent = getIndent(opts, depth);

    	    if (typeof seen === 'undefined') {
    	        seen = [];
    	    } else if (indexOf(seen, obj) >= 0) {
    	        return '[Circular]';
    	    }

    	    function inspect(value, from, noIndent) {
    	        if (from) {
    	            seen = $arrSlice.call(seen);
    	            seen.push(from);
    	        }
    	        if (noIndent) {
    	            var newOpts = {
    	                depth: opts.depth
    	            };
    	            if (has(opts, 'quoteStyle')) {
    	                newOpts.quoteStyle = opts.quoteStyle;
    	            }
    	            return inspect_(value, newOpts, depth + 1, seen);
    	        }
    	        return inspect_(value, opts, depth + 1, seen);
    	    }

    	    if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
    	        var name = nameOf(obj);
    	        var keys = arrObjKeys(obj, inspect);
    	        return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
    	    }
    	    if (isSymbol(obj)) {
    	        var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
    	        return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
    	    }
    	    if (isElement(obj)) {
    	        var s = '<' + $toLowerCase.call(String(obj.nodeName));
    	        var attrs = obj.attributes || [];
    	        for (var i = 0; i < attrs.length; i++) {
    	            s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
    	        }
    	        s += '>';
    	        if (obj.childNodes && obj.childNodes.length) { s += '...'; }
    	        s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
    	        return s;
    	    }
    	    if (isArray(obj)) {
    	        if (obj.length === 0) { return '[]'; }
    	        var xs = arrObjKeys(obj, inspect);
    	        if (indent && !singleLineValues(xs)) {
    	            return '[' + indentedJoin(xs, indent) + ']';
    	        }
    	        return '[ ' + $join.call(xs, ', ') + ' ]';
    	    }
    	    if (isError(obj)) {
    	        var parts = arrObjKeys(obj, inspect);
    	        if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
    	            return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
    	        }
    	        if (parts.length === 0) { return '[' + String(obj) + ']'; }
    	        return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
    	    }
    	    if (typeof obj === 'object' && customInspect) {
    	        if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
    	            return utilInspect(obj, { depth: maxDepth - depth });
    	        } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
    	            return obj.inspect();
    	        }
    	    }
    	    if (isMap(obj)) {
    	        var mapParts = [];
    	        if (mapForEach) {
    	            mapForEach.call(obj, function (value, key) {
    	                mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
    	            });
    	        }
    	        return collectionOf('Map', mapSize.call(obj), mapParts, indent);
    	    }
    	    if (isSet(obj)) {
    	        var setParts = [];
    	        if (setForEach) {
    	            setForEach.call(obj, function (value) {
    	                setParts.push(inspect(value, obj));
    	            });
    	        }
    	        return collectionOf('Set', setSize.call(obj), setParts, indent);
    	    }
    	    if (isWeakMap(obj)) {
    	        return weakCollectionOf('WeakMap');
    	    }
    	    if (isWeakSet(obj)) {
    	        return weakCollectionOf('WeakSet');
    	    }
    	    if (isWeakRef(obj)) {
    	        return weakCollectionOf('WeakRef');
    	    }
    	    if (isNumber(obj)) {
    	        return markBoxed(inspect(Number(obj)));
    	    }
    	    if (isBigInt(obj)) {
    	        return markBoxed(inspect(bigIntValueOf.call(obj)));
    	    }
    	    if (isBoolean(obj)) {
    	        return markBoxed(booleanValueOf.call(obj));
    	    }
    	    if (isString(obj)) {
    	        return markBoxed(inspect(String(obj)));
    	    }
    	    // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other
    	    /* eslint-env browser */
    	    if (typeof window !== 'undefined' && obj === window) {
    	        return '{ [object Window] }';
    	    }
    	    if (
    	        (typeof globalThis !== 'undefined' && obj === globalThis)
    	        || (typeof global !== 'undefined' && obj === global)
    	    ) {
    	        return '{ [object globalThis] }';
    	    }
    	    if (!isDate(obj) && !isRegExp(obj)) {
    	        var ys = arrObjKeys(obj, inspect);
    	        var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
    	        var protoTag = obj instanceof Object ? '' : 'null prototype';
    	        var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
    	        var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
    	        var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
    	        if (ys.length === 0) { return tag + '{}'; }
    	        if (indent) {
    	            return tag + '{' + indentedJoin(ys, indent) + '}';
    	        }
    	        return tag + '{ ' + $join.call(ys, ', ') + ' }';
    	    }
    	    return String(obj);
    	};

    	function wrapQuotes(s, defaultStyle, opts) {
    	    var style = opts.quoteStyle || defaultStyle;
    	    var quoteChar = quotes[style];
    	    return quoteChar + s + quoteChar;
    	}

    	function quote(s) {
    	    return $replace.call(String(s), /"/g, '&quot;');
    	}

    	function canTrustToString(obj) {
    	    return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined'));
    	}
    	function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); }
    	function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); }
    	function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); }
    	function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); }
    	function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); }
    	function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); }
    	function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); }

    	// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
    	function isSymbol(obj) {
    	    if (hasShammedSymbols) {
    	        return obj && typeof obj === 'object' && obj instanceof Symbol;
    	    }
    	    if (typeof obj === 'symbol') {
    	        return true;
    	    }
    	    if (!obj || typeof obj !== 'object' || !symToString) {
    	        return false;
    	    }
    	    try {
    	        symToString.call(obj);
    	        return true;
    	    } catch (e) {}
    	    return false;
    	}

    	function isBigInt(obj) {
    	    if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
    	        return false;
    	    }
    	    try {
    	        bigIntValueOf.call(obj);
    	        return true;
    	    } catch (e) {}
    	    return false;
    	}

    	var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
    	function has(obj, key) {
    	    return hasOwn.call(obj, key);
    	}

    	function toStr(obj) {
    	    return objectToString.call(obj);
    	}

    	function nameOf(f) {
    	    if (f.name) { return f.name; }
    	    var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
    	    if (m) { return m[1]; }
    	    return null;
    	}

    	function indexOf(xs, x) {
    	    if (xs.indexOf) { return xs.indexOf(x); }
    	    for (var i = 0, l = xs.length; i < l; i++) {
    	        if (xs[i] === x) { return i; }
    	    }
    	    return -1;
    	}

    	function isMap(x) {
    	    if (!mapSize || !x || typeof x !== 'object') {
    	        return false;
    	    }
    	    try {
    	        mapSize.call(x);
    	        try {
    	            setSize.call(x);
    	        } catch (s) {
    	            return true;
    	        }
    	        return x instanceof Map; // core-js workaround, pre-v2.5.0
    	    } catch (e) {}
    	    return false;
    	}

    	function isWeakMap(x) {
    	    if (!weakMapHas || !x || typeof x !== 'object') {
    	        return false;
    	    }
    	    try {
    	        weakMapHas.call(x, weakMapHas);
    	        try {
    	            weakSetHas.call(x, weakSetHas);
    	        } catch (s) {
    	            return true;
    	        }
    	        return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
    	    } catch (e) {}
    	    return false;
    	}

    	function isWeakRef(x) {
    	    if (!weakRefDeref || !x || typeof x !== 'object') {
    	        return false;
    	    }
    	    try {
    	        weakRefDeref.call(x);
    	        return true;
    	    } catch (e) {}
    	    return false;
    	}

    	function isSet(x) {
    	    if (!setSize || !x || typeof x !== 'object') {
    	        return false;
    	    }
    	    try {
    	        setSize.call(x);
    	        try {
    	            mapSize.call(x);
    	        } catch (m) {
    	            return true;
    	        }
    	        return x instanceof Set; // core-js workaround, pre-v2.5.0
    	    } catch (e) {}
    	    return false;
    	}

    	function isWeakSet(x) {
    	    if (!weakSetHas || !x || typeof x !== 'object') {
    	        return false;
    	    }
    	    try {
    	        weakSetHas.call(x, weakSetHas);
    	        try {
    	            weakMapHas.call(x, weakMapHas);
    	        } catch (s) {
    	            return true;
    	        }
    	        return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
    	    } catch (e) {}
    	    return false;
    	}

    	function isElement(x) {
    	    if (!x || typeof x !== 'object') { return false; }
    	    if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
    	        return true;
    	    }
    	    return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
    	}

    	function inspectString(str, opts) {
    	    if (str.length > opts.maxStringLength) {
    	        var remaining = str.length - opts.maxStringLength;
    	        var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
    	        return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
    	    }
    	    var quoteRE = quoteREs[opts.quoteStyle || 'single'];
    	    quoteRE.lastIndex = 0;
    	    // eslint-disable-next-line no-control-regex
    	    var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte);
    	    return wrapQuotes(s, 'single', opts);
    	}

    	function lowbyte(c) {
    	    var n = c.charCodeAt(0);
    	    var x = {
    	        8: 'b',
    	        9: 't',
    	        10: 'n',
    	        12: 'f',
    	        13: 'r'
    	    }[n];
    	    if (x) { return '\\' + x; }
    	    return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
    	}

    	function markBoxed(str) {
    	    return 'Object(' + str + ')';
    	}

    	function weakCollectionOf(type) {
    	    return type + ' { ? }';
    	}

    	function collectionOf(type, size, entries, indent) {
    	    var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
    	    return type + ' (' + size + ') {' + joinedEntries + '}';
    	}

    	function singleLineValues(xs) {
    	    for (var i = 0; i < xs.length; i++) {
    	        if (indexOf(xs[i], '\n') >= 0) {
    	            return false;
    	        }
    	    }
    	    return true;
    	}

    	function getIndent(opts, depth) {
    	    var baseIndent;
    	    if (opts.indent === '\t') {
    	        baseIndent = '\t';
    	    } else if (typeof opts.indent === 'number' && opts.indent > 0) {
    	        baseIndent = $join.call(Array(opts.indent + 1), ' ');
    	    } else {
    	        return null;
    	    }
    	    return {
    	        base: baseIndent,
    	        prev: $join.call(Array(depth + 1), baseIndent)
    	    };
    	}

    	function indentedJoin(xs, indent) {
    	    if (xs.length === 0) { return ''; }
    	    var lineJoiner = '\n' + indent.prev + indent.base;
    	    return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
    	}

    	function arrObjKeys(obj, inspect) {
    	    var isArr = isArray(obj);
    	    var xs = [];
    	    if (isArr) {
    	        xs.length = obj.length;
    	        for (var i = 0; i < obj.length; i++) {
    	            xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
    	        }
    	    }
    	    var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
    	    var symMap;
    	    if (hasShammedSymbols) {
    	        symMap = {};
    	        for (var k = 0; k < syms.length; k++) {
    	            symMap['$' + syms[k]] = syms[k];
    	        }
    	    }

    	    for (var key in obj) { // eslint-disable-line no-restricted-syntax
    	        if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
    	        if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
    	        if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
    	            // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
    	            continue; // eslint-disable-line no-restricted-syntax, no-continue
    	        } else if ($test.call(/[^\w$]/, key)) {
    	            xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
    	        } else {
    	            xs.push(key + ': ' + inspect(obj[key], obj));
    	        }
    	    }
    	    if (typeof gOPS === 'function') {
    	        for (var j = 0; j < syms.length; j++) {
    	            if (isEnumerable.call(obj, syms[j])) {
    	                xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
    	            }
    	        }
    	    }
    	    return xs;
    	}
    	return objectInspect;
    }

    var sideChannelList;
    var hasRequiredSideChannelList;

    function requireSideChannelList () {
    	if (hasRequiredSideChannelList) return sideChannelList;
    	hasRequiredSideChannelList = 1;

    	var inspect = /*@__PURE__*/ requireObjectInspect();

    	var $TypeError = /*@__PURE__*/ requireType();

    	/*
    	* This function traverses the list returning the node corresponding to the given key.
    	*
    	* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list.
    	* By doing so, all the recently used nodes can be accessed relatively quickly.
    	*/
    	/** @type {import('./list.d.ts').listGetNode} */
    	// eslint-disable-next-line consistent-return
    	var listGetNode = function (list, key, isDelete) {
    		/** @type {typeof list | NonNullable<(typeof list)['next']>} */
    		var prev = list;
    		/** @type {(typeof list)['next']} */
    		var curr;
    		// eslint-disable-next-line eqeqeq
    		for (; (curr = prev.next) != null; prev = curr) {
    			if (curr.key === key) {
    				prev.next = curr.next;
    				if (!isDelete) {
    					// eslint-disable-next-line no-extra-parens
    					curr.next = /** @type {NonNullable<typeof list.next>} */ (list.next);
    					list.next = curr; // eslint-disable-line no-param-reassign
    				}
    				return curr;
    			}
    		}
    	};

    	/** @type {import('./list.d.ts').listGet} */
    	var listGet = function (objects, key) {
    		if (!objects) {
    			return void undefined;
    		}
    		var node = listGetNode(objects, key);
    		return node && node.value;
    	};
    	/** @type {import('./list.d.ts').listSet} */
    	var listSet = function (objects, key, value) {
    		var node = listGetNode(objects, key);
    		if (node) {
    			node.value = value;
    		} else {
    			// Prepend the new node to the beginning of the list
    			objects.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens
    				key: key,
    				next: objects.next,
    				value: value
    			});
    		}
    	};
    	/** @type {import('./list.d.ts').listHas} */
    	var listHas = function (objects, key) {
    		if (!objects) {
    			return false;
    		}
    		return !!listGetNode(objects, key);
    	};
    	/** @type {import('./list.d.ts').listDelete} */
    	// eslint-disable-next-line consistent-return
    	var listDelete = function (objects, key) {
    		if (objects) {
    			return listGetNode(objects, key, true);
    		}
    	};

    	/** @type {import('.')} */
    	sideChannelList = function getSideChannelList() {
    		/** @typedef {ReturnType<typeof getSideChannelList>} Channel */
    		/** @typedef {Parameters<Channel['get']>[0]} K */
    		/** @typedef {Parameters<Channel['set']>[1]} V */

    		/** @type {import('./list.d.ts').RootNode<V, K> | undefined} */ var $o;

    		/** @type {Channel} */
    		var channel = {
    			assert: function (key) {
    				if (!channel.has(key)) {
    					throw new $TypeError('Side channel does not contain ' + inspect(key));
    				}
    			},
    			'delete': function (key) {
    				var root = $o && $o.next;
    				var deletedNode = listDelete($o, key);
    				if (deletedNode && root && root === deletedNode) {
    					$o = void undefined;
    				}
    				return !!deletedNode;
    			},
    			get: function (key) {
    				return listGet($o, key);
    			},
    			has: function (key) {
    				return listHas($o, key);
    			},
    			set: function (key, value) {
    				if (!$o) {
    					// Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head
    					$o = {
    						next: void undefined
    					};
    				}
    				// eslint-disable-next-line no-extra-parens
    				listSet(/** @type {NonNullable<typeof $o>} */ ($o), key, value);
    			}
    		};
    		// @ts-expect-error TODO: figure out why this is erroring
    		return channel;
    	};
    	return sideChannelList;
    }

    var esObjectAtoms;
    var hasRequiredEsObjectAtoms;

    function requireEsObjectAtoms () {
    	if (hasRequiredEsObjectAtoms) return esObjectAtoms;
    	hasRequiredEsObjectAtoms = 1;

    	/** @type {import('.')} */
    	esObjectAtoms = Object;
    	return esObjectAtoms;
    }

    var esErrors;
    var hasRequiredEsErrors;

    function requireEsErrors () {
    	if (hasRequiredEsErrors) return esErrors;
    	hasRequiredEsErrors = 1;

    	/** @type {import('.')} */
    	esErrors = Error;
    	return esErrors;
    }

    var _eval;
    var hasRequired_eval;

    function require_eval () {
    	if (hasRequired_eval) return _eval;
    	hasRequired_eval = 1;

    	/** @type {import('./eval')} */
    	_eval = EvalError;
    	return _eval;
    }

    var range$1;
    var hasRequiredRange;

    function requireRange () {
    	if (hasRequiredRange) return range$1;
    	hasRequiredRange = 1;

    	/** @type {import('./range')} */
    	range$1 = RangeError;
    	return range$1;
    }

    var ref;
    var hasRequiredRef;

    function requireRef () {
    	if (hasRequiredRef) return ref;
    	hasRequiredRef = 1;

    	/** @type {import('./ref')} */
    	ref = ReferenceError;
    	return ref;
    }

    var syntax;
    var hasRequiredSyntax;

    function requireSyntax () {
    	if (hasRequiredSyntax) return syntax;
    	hasRequiredSyntax = 1;

    	/** @type {import('./syntax')} */
    	syntax = SyntaxError;
    	return syntax;
    }

    var uri;
    var hasRequiredUri;

    function requireUri () {
    	if (hasRequiredUri) return uri;
    	hasRequiredUri = 1;

    	/** @type {import('./uri')} */
    	uri = URIError;
    	return uri;
    }

    var abs;
    var hasRequiredAbs;

    function requireAbs () {
    	if (hasRequiredAbs) return abs;
    	hasRequiredAbs = 1;

    	/** @type {import('./abs')} */
    	abs = Math.abs;
    	return abs;
    }

    var floor;
    var hasRequiredFloor;

    function requireFloor () {
    	if (hasRequiredFloor) return floor;
    	hasRequiredFloor = 1;

    	/** @type {import('./floor')} */
    	floor = Math.floor;
    	return floor;
    }

    var max;
    var hasRequiredMax;

    function requireMax () {
    	if (hasRequiredMax) return max;
    	hasRequiredMax = 1;

    	/** @type {import('./max')} */
    	max = Math.max;
    	return max;
    }

    var min;
    var hasRequiredMin;

    function requireMin () {
    	if (hasRequiredMin) return min;
    	hasRequiredMin = 1;

    	/** @type {import('./min')} */
    	min = Math.min;
    	return min;
    }

    var pow;
    var hasRequiredPow;

    function requirePow () {
    	if (hasRequiredPow) return pow;
    	hasRequiredPow = 1;

    	/** @type {import('./pow')} */
    	pow = Math.pow;
    	return pow;
    }

    var round;
    var hasRequiredRound;

    function requireRound () {
    	if (hasRequiredRound) return round;
    	hasRequiredRound = 1;

    	/** @type {import('./round')} */
    	round = Math.round;
    	return round;
    }

    var _isNaN;
    var hasRequired_isNaN;

    function require_isNaN () {
    	if (hasRequired_isNaN) return _isNaN;
    	hasRequired_isNaN = 1;

    	/** @type {import('./isNaN')} */
    	_isNaN = Number.isNaN || function isNaN(a) {
    		return a !== a;
    	};
    	return _isNaN;
    }

    var sign;
    var hasRequiredSign;

    function requireSign () {
    	if (hasRequiredSign) return sign;
    	hasRequiredSign = 1;

    	var $isNaN = /*@__PURE__*/ require_isNaN();

    	/** @type {import('./sign')} */
    	sign = function sign(number) {
    		if ($isNaN(number) || number === 0) {
    			return number;
    		}
    		return number < 0 ? -1 : 1;
    	};
    	return sign;
    }

    var gOPD;
    var hasRequiredGOPD;

    function requireGOPD () {
    	if (hasRequiredGOPD) return gOPD;
    	hasRequiredGOPD = 1;

    	/** @type {import('./gOPD')} */
    	gOPD = Object.getOwnPropertyDescriptor;
    	return gOPD;
    }

    var gopd;
    var hasRequiredGopd;

    function requireGopd () {
    	if (hasRequiredGopd) return gopd;
    	hasRequiredGopd = 1;

    	/** @type {import('.')} */
    	var $gOPD = /*@__PURE__*/ requireGOPD();

    	if ($gOPD) {
    		try {
    			$gOPD([], 'length');
    		} catch (e) {
    			// IE 8 has a broken gOPD
    			$gOPD = null;
    		}
    	}

    	gopd = $gOPD;
    	return gopd;
    }

    var esDefineProperty;
    var hasRequiredEsDefineProperty;

    function requireEsDefineProperty () {
    	if (hasRequiredEsDefineProperty) return esDefineProperty;
    	hasRequiredEsDefineProperty = 1;

    	/** @type {import('.')} */
    	var $defineProperty = Object.defineProperty || false;
    	if ($defineProperty) {
    		try {
    			$defineProperty({}, 'a', { value: 1 });
    		} catch (e) {
    			// IE 8 has a broken defineProperty
    			$defineProperty = false;
    		}
    	}

    	esDefineProperty = $defineProperty;
    	return esDefineProperty;
    }

    var shams;
    var hasRequiredShams;

    function requireShams () {
    	if (hasRequiredShams) return shams;
    	hasRequiredShams = 1;

    	/** @type {import('./shams')} */
    	/* eslint complexity: [2, 18], max-statements: [2, 33] */
    	shams = function hasSymbols() {
    		if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
    		if (typeof Symbol.iterator === 'symbol') { return true; }

    		/** @type {{ [k in symbol]?: unknown }} */
    		var obj = {};
    		var sym = Symbol('test');
    		var symObj = Object(sym);
    		if (typeof sym === 'string') { return false; }

    		if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
    		if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }

    		// temp disabled per https://github.com/ljharb/object.assign/issues/17
    		// if (sym instanceof Symbol) { return false; }
    		// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
    		// if (!(symObj instanceof Symbol)) { return false; }

    		// if (typeof Symbol.prototype.toString !== 'function') { return false; }
    		// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }

    		var symVal = 42;
    		obj[sym] = symVal;
    		for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
    		if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }

    		if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }

    		var syms = Object.getOwnPropertySymbols(obj);
    		if (syms.length !== 1 || syms[0] !== sym) { return false; }

    		if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }

    		if (typeof Object.getOwnPropertyDescriptor === 'function') {
    			// eslint-disable-next-line no-extra-parens
    			var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym));
    			if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
    		}

    		return true;
    	};
    	return shams;
    }

    var hasSymbols;
    var hasRequiredHasSymbols;

    function requireHasSymbols () {
    	if (hasRequiredHasSymbols) return hasSymbols;
    	hasRequiredHasSymbols = 1;

    	var origSymbol = typeof Symbol !== 'undefined' && Symbol;
    	var hasSymbolSham = requireShams();

    	/** @type {import('.')} */
    	hasSymbols = function hasNativeSymbols() {
    		if (typeof origSymbol !== 'function') { return false; }
    		if (typeof Symbol !== 'function') { return false; }
    		if (typeof origSymbol('foo') !== 'symbol') { return false; }
    		if (typeof Symbol('bar') !== 'symbol') { return false; }

    		return hasSymbolSham();
    	};
    	return hasSymbols;
    }

    var Reflect_getPrototypeOf;
    var hasRequiredReflect_getPrototypeOf;

    function requireReflect_getPrototypeOf () {
    	if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf;
    	hasRequiredReflect_getPrototypeOf = 1;

    	/** @type {import('./Reflect.getPrototypeOf')} */
    	Reflect_getPrototypeOf = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null;
    	return Reflect_getPrototypeOf;
    }

    var Object_getPrototypeOf;
    var hasRequiredObject_getPrototypeOf;

    function requireObject_getPrototypeOf () {
    	if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf;
    	hasRequiredObject_getPrototypeOf = 1;

    	var $Object = /*@__PURE__*/ requireEsObjectAtoms();

    	/** @type {import('./Object.getPrototypeOf')} */
    	Object_getPrototypeOf = $Object.getPrototypeOf || null;
    	return Object_getPrototypeOf;
    }

    var implementation;
    var hasRequiredImplementation;

    function requireImplementation () {
    	if (hasRequiredImplementation) return implementation;
    	hasRequiredImplementation = 1;

    	/* eslint no-invalid-this: 1 */

    	var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
    	var toStr = Object.prototype.toString;
    	var max = Math.max;
    	var funcType = '[object Function]';

    	var concatty = function concatty(a, b) {
    	    var arr = [];

    	    for (var i = 0; i < a.length; i += 1) {
    	        arr[i] = a[i];
    	    }
    	    for (var j = 0; j < b.length; j += 1) {
    	        arr[j + a.length] = b[j];
    	    }

    	    return arr;
    	};

    	var slicy = function slicy(arrLike, offset) {
    	    var arr = [];
    	    for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) {
    	        arr[j] = arrLike[i];
    	    }
    	    return arr;
    	};

    	var joiny = function (arr, joiner) {
    	    var str = '';
    	    for (var i = 0; i < arr.length; i += 1) {
    	        str += arr[i];
    	        if (i + 1 < arr.length) {
    	            str += joiner;
    	        }
    	    }
    	    return str;
    	};

    	implementation = function bind(that) {
    	    var target = this;
    	    if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
    	        throw new TypeError(ERROR_MESSAGE + target);
    	    }
    	    var args = slicy(arguments, 1);

    	    var bound;
    	    var binder = function () {
    	        if (this instanceof bound) {
    	            var result = target.apply(
    	                this,
    	                concatty(args, arguments)
    	            );
    	            if (Object(result) === result) {
    	                return result;
    	            }
    	            return this;
    	        }
    	        return target.apply(
    	            that,
    	            concatty(args, arguments)
    	        );

    	    };

    	    var boundLength = max(0, target.length - args.length);
    	    var boundArgs = [];
    	    for (var i = 0; i < boundLength; i++) {
    	        boundArgs[i] = '$' + i;
    	    }

    	    bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);

    	    if (target.prototype) {
    	        var Empty = function Empty() {};
    	        Empty.prototype = target.prototype;
    	        bound.prototype = new Empty();
    	        Empty.prototype = null;
    	    }

    	    return bound;
    	};
    	return implementation;
    }

    var functionBind;
    var hasRequiredFunctionBind;

    function requireFunctionBind () {
    	if (hasRequiredFunctionBind) return functionBind;
    	hasRequiredFunctionBind = 1;

    	var implementation = requireImplementation();

    	functionBind = Function.prototype.bind || implementation;
    	return functionBind;
    }

    var functionCall;
    var hasRequiredFunctionCall;

    function requireFunctionCall () {
    	if (hasRequiredFunctionCall) return functionCall;
    	hasRequiredFunctionCall = 1;

    	/** @type {import('./functionCall')} */
    	functionCall = Function.prototype.call;
    	return functionCall;
    }

    var functionApply;
    var hasRequiredFunctionApply;

    function requireFunctionApply () {
    	if (hasRequiredFunctionApply) return functionApply;
    	hasRequiredFunctionApply = 1;

    	/** @type {import('./functionApply')} */
    	functionApply = Function.prototype.apply;
    	return functionApply;
    }

    var reflectApply;
    var hasRequiredReflectApply;

    function requireReflectApply () {
    	if (hasRequiredReflectApply) return reflectApply;
    	hasRequiredReflectApply = 1;

    	/** @type {import('./reflectApply')} */
    	reflectApply = typeof Reflect !== 'undefined' && Reflect && Reflect.apply;
    	return reflectApply;
    }

    var actualApply;
    var hasRequiredActualApply;

    function requireActualApply () {
    	if (hasRequiredActualApply) return actualApply;
    	hasRequiredActualApply = 1;

    	var bind = requireFunctionBind();

    	var $apply = requireFunctionApply();
    	var $call = requireFunctionCall();
    	var $reflectApply = requireReflectApply();

    	/** @type {import('./actualApply')} */
    	actualApply = $reflectApply || bind.call($call, $apply);
    	return actualApply;
    }

    var callBindApplyHelpers;
    var hasRequiredCallBindApplyHelpers;

    function requireCallBindApplyHelpers () {
    	if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers;
    	hasRequiredCallBindApplyHelpers = 1;

    	var bind = requireFunctionBind();
    	var $TypeError = /*@__PURE__*/ requireType();

    	var $call = requireFunctionCall();
    	var $actualApply = requireActualApply();

    	/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */
    	callBindApplyHelpers = function callBindBasic(args) {
    		if (args.length < 1 || typeof args[0] !== 'function') {
    			throw new $TypeError('a function is required');
    		}
    		return $actualApply(bind, $call, args);
    	};
    	return callBindApplyHelpers;
    }

    var get$1g;
    var hasRequiredGet;

    function requireGet () {
    	if (hasRequiredGet) return get$1g;
    	hasRequiredGet = 1;

    	var callBind = requireCallBindApplyHelpers();
    	var gOPD = /*@__PURE__*/ requireGopd();

    	var hasProtoAccessor;
    	try {
    		// eslint-disable-next-line no-extra-parens, no-proto
    		hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype;
    	} catch (e) {
    		if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') {
    			throw e;
    		}
    	}

    	// eslint-disable-next-line no-extra-parens
    	var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__'));

    	var $Object = Object;
    	var $getPrototypeOf = $Object.getPrototypeOf;

    	/** @type {import('./get')} */
    	get$1g = desc && typeof desc.get === 'function'
    		? callBind([desc.get])
    		: typeof $getPrototypeOf === 'function'
    			? /** @type {import('./get')} */ function getDunder(value) {
    				// eslint-disable-next-line eqeqeq
    				return $getPrototypeOf(value == null ? value : $Object(value));
    			}
    			: false;
    	return get$1g;
    }

    var getProto;
    var hasRequiredGetProto;

    function requireGetProto () {
    	if (hasRequiredGetProto) return getProto;
    	hasRequiredGetProto = 1;

    	var reflectGetProto = requireReflect_getPrototypeOf();
    	var originalGetProto = requireObject_getPrototypeOf();

    	var getDunderProto = /*@__PURE__*/ requireGet();

    	/** @type {import('.')} */
    	getProto = reflectGetProto
    		? function getProto(O) {
    			// @ts-expect-error TS can't narrow inside a closure, for some reason
    			return reflectGetProto(O);
    		}
    		: originalGetProto
    			? function getProto(O) {
    				if (!O || (typeof O !== 'object' && typeof O !== 'function')) {
    					throw new TypeError('getProto: not an object');
    				}
    				// @ts-expect-error TS can't narrow inside a closure, for some reason
    				return originalGetProto(O);
    			}
    			: getDunderProto
    				? function getProto(O) {
    					// @ts-expect-error TS can't narrow inside a closure, for some reason
    					return getDunderProto(O);
    				}
    				: null;
    	return getProto;
    }

    var hasown;
    var hasRequiredHasown;

    function requireHasown () {
    	if (hasRequiredHasown) return hasown;
    	hasRequiredHasown = 1;

    	var call = Function.prototype.call;
    	var $hasOwn = Object.prototype.hasOwnProperty;
    	var bind = requireFunctionBind();

    	/** @type {import('.')} */
    	hasown = bind.call(call, $hasOwn);
    	return hasown;
    }

    var getIntrinsic;
    var hasRequiredGetIntrinsic;

    function requireGetIntrinsic () {
    	if (hasRequiredGetIntrinsic) return getIntrinsic;
    	hasRequiredGetIntrinsic = 1;

    	var undefined$1;

    	var $Object = /*@__PURE__*/ requireEsObjectAtoms();

    	var $Error = /*@__PURE__*/ requireEsErrors();
    	var $EvalError = /*@__PURE__*/ require_eval();
    	var $RangeError = /*@__PURE__*/ requireRange();
    	var $ReferenceError = /*@__PURE__*/ requireRef();
    	var $SyntaxError = /*@__PURE__*/ requireSyntax();
    	var $TypeError = /*@__PURE__*/ requireType();
    	var $URIError = /*@__PURE__*/ requireUri();

    	var abs = /*@__PURE__*/ requireAbs();
    	var floor = /*@__PURE__*/ requireFloor();
    	var max = /*@__PURE__*/ requireMax();
    	var min = /*@__PURE__*/ requireMin();
    	var pow = /*@__PURE__*/ requirePow();
    	var round = /*@__PURE__*/ requireRound();
    	var sign = /*@__PURE__*/ requireSign();

    	var $Function = Function;

    	// eslint-disable-next-line consistent-return
    	var getEvalledConstructor = function (expressionSyntax) {
    		try {
    			return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
    		} catch (e) {}
    	};

    	var $gOPD = /*@__PURE__*/ requireGopd();
    	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

    	var throwTypeError = function () {
    		throw new $TypeError();
    	};
    	var ThrowTypeError = $gOPD
    		? (function () {
    			try {
    				// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
    				arguments.callee; // IE 8 does not throw here
    				return throwTypeError;
    			} catch (calleeThrows) {
    				try {
    					// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
    					return $gOPD(arguments, 'callee').get;
    				} catch (gOPDthrows) {
    					return throwTypeError;
    				}
    			}
    		}())
    		: throwTypeError;

    	var hasSymbols = requireHasSymbols()();

    	var getProto = requireGetProto();
    	var $ObjectGPO = requireObject_getPrototypeOf();
    	var $ReflectGPO = requireReflect_getPrototypeOf();

    	var $apply = requireFunctionApply();
    	var $call = requireFunctionCall();

    	var needsEval = {};

    	var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined$1 : getProto(Uint8Array);

    	var INTRINSICS = {
    		__proto__: null,
    		'%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
    		'%Array%': Array,
    		'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
    		'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined$1,
    		'%AsyncFromSyncIteratorPrototype%': undefined$1,
    		'%AsyncFunction%': needsEval,
    		'%AsyncGenerator%': needsEval,
    		'%AsyncGeneratorFunction%': needsEval,
    		'%AsyncIteratorPrototype%': needsEval,
    		'%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
    		'%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
    		'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined$1 : BigInt64Array,
    		'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined$1 : BigUint64Array,
    		'%Boolean%': Boolean,
    		'%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
    		'%Date%': Date,
    		'%decodeURI%': decodeURI,
    		'%decodeURIComponent%': decodeURIComponent,
    		'%encodeURI%': encodeURI,
    		'%encodeURIComponent%': encodeURIComponent,
    		'%Error%': $Error,
    		'%eval%': eval, // eslint-disable-line no-eval
    		'%EvalError%': $EvalError,
    		'%Float16Array%': typeof Float16Array === 'undefined' ? undefined$1 : Float16Array,
    		'%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
    		'%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
    		'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
    		'%Function%': $Function,
    		'%GeneratorFunction%': needsEval,
    		'%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
    		'%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
    		'%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
    		'%isFinite%': isFinite,
    		'%isNaN%': isNaN,
    		'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
    		'%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
    		'%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
    		'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
    		'%Math%': Math,
    		'%Number%': Number,
    		'%Object%': $Object,
    		'%Object.getOwnPropertyDescriptor%': $gOPD,
    		'%parseFloat%': parseFloat,
    		'%parseInt%': parseInt,
    		'%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
    		'%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
    		'%RangeError%': $RangeError,
    		'%ReferenceError%': $ReferenceError,
    		'%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
    		'%RegExp%': RegExp,
    		'%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
    		'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
    		'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
    		'%String%': String,
    		'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined$1,
    		'%Symbol%': hasSymbols ? Symbol : undefined$1,
    		'%SyntaxError%': $SyntaxError,
    		'%ThrowTypeError%': ThrowTypeError,
    		'%TypedArray%': TypedArray,
    		'%TypeError%': $TypeError,
    		'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
    		'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
    		'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
    		'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
    		'%URIError%': $URIError,
    		'%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
    		'%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
    		'%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet,

    		'%Function.prototype.call%': $call,
    		'%Function.prototype.apply%': $apply,
    		'%Object.defineProperty%': $defineProperty,
    		'%Object.getPrototypeOf%': $ObjectGPO,
    		'%Math.abs%': abs,
    		'%Math.floor%': floor,
    		'%Math.max%': max,
    		'%Math.min%': min,
    		'%Math.pow%': pow,
    		'%Math.round%': round,
    		'%Math.sign%': sign,
    		'%Reflect.getPrototypeOf%': $ReflectGPO
    	};

    	if (getProto) {
    		try {
    			null.error; // eslint-disable-line no-unused-expressions
    		} catch (e) {
    			// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
    			var errorProto = getProto(getProto(e));
    			INTRINSICS['%Error.prototype%'] = errorProto;
    		}
    	}

    	var doEval = function doEval(name) {
    		var value;
    		if (name === '%AsyncFunction%') {
    			value = getEvalledConstructor('async function () {}');
    		} else if (name === '%GeneratorFunction%') {
    			value = getEvalledConstructor('function* () {}');
    		} else if (name === '%AsyncGeneratorFunction%') {
    			value = getEvalledConstructor('async function* () {}');
    		} else if (name === '%AsyncGenerator%') {
    			var fn = doEval('%AsyncGeneratorFunction%');
    			if (fn) {
    				value = fn.prototype;
    			}
    		} else if (name === '%AsyncIteratorPrototype%') {
    			var gen = doEval('%AsyncGenerator%');
    			if (gen && getProto) {
    				value = getProto(gen.prototype);
    			}
    		}

    		INTRINSICS[name] = value;

    		return value;
    	};

    	var LEGACY_ALIASES = {
    		__proto__: null,
    		'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
    		'%ArrayPrototype%': ['Array', 'prototype'],
    		'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
    		'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
    		'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
    		'%ArrayProto_values%': ['Array', 'prototype', 'values'],
    		'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
    		'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
    		'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
    		'%BooleanPrototype%': ['Boolean', 'prototype'],
    		'%DataViewPrototype%': ['DataView', 'prototype'],
    		'%DatePrototype%': ['Date', 'prototype'],
    		'%ErrorPrototype%': ['Error', 'prototype'],
    		'%EvalErrorPrototype%': ['EvalError', 'prototype'],
    		'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
    		'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
    		'%FunctionPrototype%': ['Function', 'prototype'],
    		'%Generator%': ['GeneratorFunction', 'prototype'],
    		'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
    		'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
    		'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
    		'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
    		'%JSONParse%': ['JSON', 'parse'],
    		'%JSONStringify%': ['JSON', 'stringify'],
    		'%MapPrototype%': ['Map', 'prototype'],
    		'%NumberPrototype%': ['Number', 'prototype'],
    		'%ObjectPrototype%': ['Object', 'prototype'],
    		'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
    		'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
    		'%PromisePrototype%': ['Promise', 'prototype'],
    		'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
    		'%Promise_all%': ['Promise', 'all'],
    		'%Promise_reject%': ['Promise', 'reject'],
    		'%Promise_resolve%': ['Promise', 'resolve'],
    		'%RangeErrorPrototype%': ['RangeError', 'prototype'],
    		'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
    		'%RegExpPrototype%': ['RegExp', 'prototype'],
    		'%SetPrototype%': ['Set', 'prototype'],
    		'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
    		'%StringPrototype%': ['String', 'prototype'],
    		'%SymbolPrototype%': ['Symbol', 'prototype'],
    		'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
    		'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
    		'%TypeErrorPrototype%': ['TypeError', 'prototype'],
    		'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
    		'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
    		'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
    		'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
    		'%URIErrorPrototype%': ['URIError', 'prototype'],
    		'%WeakMapPrototype%': ['WeakMap', 'prototype'],
    		'%WeakSetPrototype%': ['WeakSet', 'prototype']
    	};

    	var bind = requireFunctionBind();
    	var hasOwn = /*@__PURE__*/ requireHasown();
    	var $concat = bind.call($call, Array.prototype.concat);
    	var $spliceApply = bind.call($apply, Array.prototype.splice);
    	var $replace = bind.call($call, String.prototype.replace);
    	var $strSlice = bind.call($call, String.prototype.slice);
    	var $exec = bind.call($call, RegExp.prototype.exec);

    	/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
    	var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
    	var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
    	var stringToPath = function stringToPath(string) {
    		var first = $strSlice(string, 0, 1);
    		var last = $strSlice(string, -1);
    		if (first === '%' && last !== '%') {
    			throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
    		} else if (last === '%' && first !== '%') {
    			throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
    		}
    		var result = [];
    		$replace(string, rePropName, function (match, number, quote, subString) {
    			result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
    		});
    		return result;
    	};
    	/* end adaptation */

    	var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
    		var intrinsicName = name;
    		var alias;
    		if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
    			alias = LEGACY_ALIASES[intrinsicName];
    			intrinsicName = '%' + alias[0] + '%';
    		}

    		if (hasOwn(INTRINSICS, intrinsicName)) {
    			var value = INTRINSICS[intrinsicName];
    			if (value === needsEval) {
    				value = doEval(intrinsicName);
    			}
    			if (typeof value === 'undefined' && !allowMissing) {
    				throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
    			}

    			return {
    				alias: alias,
    				name: intrinsicName,
    				value: value
    			};
    		}

    		throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
    	};

    	getIntrinsic = function GetIntrinsic(name, allowMissing) {
    		if (typeof name !== 'string' || name.length === 0) {
    			throw new $TypeError('intrinsic name must be a non-empty string');
    		}
    		if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
    			throw new $TypeError('"allowMissing" argument must be a boolean');
    		}

    		if ($exec(/^%?[^%]*%?$/, name) === null) {
    			throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
    		}
    		var parts = stringToPath(name);
    		var intrinsicBaseName = parts.length > 0 ? parts[0] : '';

    		var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
    		var intrinsicRealName = intrinsic.name;
    		var value = intrinsic.value;
    		var skipFurtherCaching = false;

    		var alias = intrinsic.alias;
    		if (alias) {
    			intrinsicBaseName = alias[0];
    			$spliceApply(parts, $concat([0, 1], alias));
    		}

    		for (var i = 1, isOwn = true; i < parts.length; i += 1) {
    			var part = parts[i];
    			var first = $strSlice(part, 0, 1);
    			var last = $strSlice(part, -1);
    			if (
    				(
    					(first === '"' || first === "'" || first === '`')
    					|| (last === '"' || last === "'" || last === '`')
    				)
    				&& first !== last
    			) {
    				throw new $SyntaxError('property names with quotes must have matching quotes');
    			}
    			if (part === 'constructor' || !isOwn) {
    				skipFurtherCaching = true;
    			}

    			intrinsicBaseName += '.' + part;
    			intrinsicRealName = '%' + intrinsicBaseName + '%';

    			if (hasOwn(INTRINSICS, intrinsicRealName)) {
    				value = INTRINSICS[intrinsicRealName];
    			} else if (value != null) {
    				if (!(part in value)) {
    					if (!allowMissing) {
    						throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
    					}
    					return void undefined$1;
    				}
    				if ($gOPD && (i + 1) >= parts.length) {
    					var desc = $gOPD(value, part);
    					isOwn = !!desc;

    					// By convention, when a data property is converted to an accessor
    					// property to emulate a data property that does not suffer from
    					// the override mistake, that accessor's getter is marked with
    					// an `originalValue` property. Here, when we detect this, we
    					// uphold the illusion by pretending to see that original data
    					// property, i.e., returning the value rather than the getter
    					// itself.
    					if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
    						value = desc.get;
    					} else {
    						value = value[part];
    					}
    				} else {
    					isOwn = hasOwn(value, part);
    					value = value[part];
    				}

    				if (isOwn && !skipFurtherCaching) {
    					INTRINSICS[intrinsicRealName] = value;
    				}
    			}
    		}
    		return value;
    	};
    	return getIntrinsic;
    }

    var callBound;
    var hasRequiredCallBound;

    function requireCallBound () {
    	if (hasRequiredCallBound) return callBound;
    	hasRequiredCallBound = 1;

    	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();

    	var callBindBasic = requireCallBindApplyHelpers();

    	/** @type {(thisArg: string, searchString: string, position?: number) => number} */
    	var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]);

    	/** @type {import('.')} */
    	callBound = function callBoundIntrinsic(name, allowMissing) {
    		/* eslint no-extra-parens: 0 */

    		var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing));
    		if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
    			return callBindBasic(/** @type {const} */ ([intrinsic]));
    		}
    		return intrinsic;
    	};
    	return callBound;
    }

    var sideChannelMap;
    var hasRequiredSideChannelMap;

    function requireSideChannelMap () {
    	if (hasRequiredSideChannelMap) return sideChannelMap;
    	hasRequiredSideChannelMap = 1;

    	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();
    	var callBound = /*@__PURE__*/ requireCallBound();
    	var inspect = /*@__PURE__*/ requireObjectInspect();

    	var $TypeError = /*@__PURE__*/ requireType();
    	var $Map = GetIntrinsic('%Map%', true);

    	/** @type {<K, V>(thisArg: Map<K, V>, key: K) => V} */
    	var $mapGet = callBound('Map.prototype.get', true);
    	/** @type {<K, V>(thisArg: Map<K, V>, key: K, value: V) => void} */
    	var $mapSet = callBound('Map.prototype.set', true);
    	/** @type {<K, V>(thisArg: Map<K, V>, key: K) => boolean} */
    	var $mapHas = callBound('Map.prototype.has', true);
    	/** @type {<K, V>(thisArg: Map<K, V>, key: K) => boolean} */
    	var $mapDelete = callBound('Map.prototype.delete', true);
    	/** @type {<K, V>(thisArg: Map<K, V>) => number} */
    	var $mapSize = callBound('Map.prototype.size', true);

    	/** @type {import('.')} */
    	sideChannelMap = !!$Map && /** @type {Exclude<import('.'), false>} */ function getSideChannelMap() {
    		/** @typedef {ReturnType<typeof getSideChannelMap>} Channel */
    		/** @typedef {Parameters<Channel['get']>[0]} K */
    		/** @typedef {Parameters<Channel['set']>[1]} V */

    		/** @type {Map<K, V> | undefined} */ var $m;

    		/** @type {Channel} */
    		var channel = {
    			assert: function (key) {
    				if (!channel.has(key)) {
    					throw new $TypeError('Side channel does not contain ' + inspect(key));
    				}
    			},
    			'delete': function (key) {
    				if ($m) {
    					var result = $mapDelete($m, key);
    					if ($mapSize($m) === 0) {
    						$m = void undefined;
    					}
    					return result;
    				}
    				return false;
    			},
    			get: function (key) { // eslint-disable-line consistent-return
    				if ($m) {
    					return $mapGet($m, key);
    				}
    			},
    			has: function (key) {
    				if ($m) {
    					return $mapHas($m, key);
    				}
    				return false;
    			},
    			set: function (key, value) {
    				if (!$m) {
    					// @ts-expect-error TS can't handle narrowing a variable inside a closure
    					$m = new $Map();
    				}
    				$mapSet($m, key, value);
    			}
    		};

    		// @ts-expect-error TODO: figure out why TS is erroring here
    		return channel;
    	};
    	return sideChannelMap;
    }

    var sideChannelWeakmap;
    var hasRequiredSideChannelWeakmap;

    function requireSideChannelWeakmap () {
    	if (hasRequiredSideChannelWeakmap) return sideChannelWeakmap;
    	hasRequiredSideChannelWeakmap = 1;

    	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();
    	var callBound = /*@__PURE__*/ requireCallBound();
    	var inspect = /*@__PURE__*/ requireObjectInspect();
    	var getSideChannelMap = requireSideChannelMap();

    	var $TypeError = /*@__PURE__*/ requireType();
    	var $WeakMap = GetIntrinsic('%WeakMap%', true);

    	/** @type {<K extends object, V>(thisArg: WeakMap<K, V>, key: K) => V} */
    	var $weakMapGet = callBound('WeakMap.prototype.get', true);
    	/** @type {<K extends object, V>(thisArg: WeakMap<K, V>, key: K, value: V) => void} */
    	var $weakMapSet = callBound('WeakMap.prototype.set', true);
    	/** @type {<K extends object, V>(thisArg: WeakMap<K, V>, key: K) => boolean} */
    	var $weakMapHas = callBound('WeakMap.prototype.has', true);
    	/** @type {<K extends object, V>(thisArg: WeakMap<K, V>, key: K) => boolean} */
    	var $weakMapDelete = callBound('WeakMap.prototype.delete', true);

    	/** @type {import('.')} */
    	sideChannelWeakmap = $WeakMap
    		? /** @type {Exclude<import('.'), false>} */ function getSideChannelWeakMap() {
    			/** @typedef {ReturnType<typeof getSideChannelWeakMap>} Channel */
    			/** @typedef {Parameters<Channel['get']>[0]} K */
    			/** @typedef {Parameters<Channel['set']>[1]} V */

    			/** @type {WeakMap<K & object, V> | undefined} */ var $wm;
    			/** @type {Channel | undefined} */ var $m;

    			/** @type {Channel} */
    			var channel = {
    				assert: function (key) {
    					if (!channel.has(key)) {
    						throw new $TypeError('Side channel does not contain ' + inspect(key));
    					}
    				},
    				'delete': function (key) {
    					if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
    						if ($wm) {
    							return $weakMapDelete($wm, key);
    						}
    					} else if (getSideChannelMap) {
    						if ($m) {
    							return $m['delete'](key);
    						}
    					}
    					return false;
    				},
    				get: function (key) {
    					if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
    						if ($wm) {
    							return $weakMapGet($wm, key);
    						}
    					}
    					return $m && $m.get(key);
    				},
    				has: function (key) {
    					if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
    						if ($wm) {
    							return $weakMapHas($wm, key);
    						}
    					}
    					return !!$m && $m.has(key);
    				},
    				set: function (key, value) {
    					if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
    						if (!$wm) {
    							$wm = new $WeakMap();
    						}
    						$weakMapSet($wm, key, value);
    					} else if (getSideChannelMap) {
    						if (!$m) {
    							$m = getSideChannelMap();
    						}
    						// eslint-disable-next-line no-extra-parens
    						/** @type {NonNullable<typeof $m>} */ ($m).set(key, value);
    					}
    				}
    			};

    			// @ts-expect-error TODO: figure out why this is erroring
    			return channel;
    		}
    		: getSideChannelMap;
    	return sideChannelWeakmap;
    }

    var sideChannel;
    var hasRequiredSideChannel;

    function requireSideChannel () {
    	if (hasRequiredSideChannel) return sideChannel;
    	hasRequiredSideChannel = 1;

    	var $TypeError = /*@__PURE__*/ requireType();
    	var inspect = /*@__PURE__*/ requireObjectInspect();
    	var getSideChannelList = requireSideChannelList();
    	var getSideChannelMap = requireSideChannelMap();
    	var getSideChannelWeakMap = requireSideChannelWeakmap();

    	var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList;

    	/** @type {import('.')} */
    	sideChannel = function getSideChannel() {
    		/** @typedef {ReturnType<typeof getSideChannel>} Channel */

    		/** @type {Channel | undefined} */ var $channelData;

    		/** @type {Channel} */
    		var channel = {
    			assert: function (key) {
    				if (!channel.has(key)) {
    					throw new $TypeError('Side channel does not contain ' + inspect(key));
    				}
    			},
    			'delete': function (key) {
    				return !!$channelData && $channelData['delete'](key);
    			},
    			get: function (key) {
    				return $channelData && $channelData.get(key);
    			},
    			has: function (key) {
    				return !!$channelData && $channelData.has(key);
    			},
    			set: function (key, value) {
    				if (!$channelData) {
    					$channelData = makeChannel();
    				}

    				$channelData.set(key, value);
    			}
    		};
    		// @ts-expect-error TODO: figure out why this is erroring
    		return channel;
    	};
    	return sideChannel;
    }

    var formats;
    var hasRequiredFormats;

    function requireFormats () {
    	if (hasRequiredFormats) return formats;
    	hasRequiredFormats = 1;

    	var replace = String.prototype.replace;
    	var percentTwenties = /%20/g;

    	var Format = {
    	    RFC1738: 'RFC1738',
    	    RFC3986: 'RFC3986'
    	};

    	formats = {
    	    'default': Format.RFC3986,
    	    formatters: {
    	        RFC1738: function (value) {
    	            return replace.call(value, percentTwenties, '+');
    	        },
    	        RFC3986: function (value) {
    	            return String(value);
    	        }
    	    },
    	    RFC1738: Format.RFC1738,
    	    RFC3986: Format.RFC3986
    	};
    	return formats;
    }

    var utils;
    var hasRequiredUtils;

    function requireUtils () {
    	if (hasRequiredUtils) return utils;
    	hasRequiredUtils = 1;

    	var formats = /*@__PURE__*/ requireFormats();
    	var getSideChannel = requireSideChannel();

    	var has = Object.prototype.hasOwnProperty;
    	var isArray = Array.isArray;

    	// Track objects created from arrayLimit overflow using side-channel
    	// Stores the current max numeric index for O(1) lookup
    	var overflowChannel = getSideChannel();

    	var markOverflow = function markOverflow(obj, maxIndex) {
    	    overflowChannel.set(obj, maxIndex);
    	    return obj;
    	};

    	var isOverflow = function isOverflow(obj) {
    	    return overflowChannel.has(obj);
    	};

    	var getMaxIndex = function getMaxIndex(obj) {
    	    return overflowChannel.get(obj);
    	};

    	var setMaxIndex = function setMaxIndex(obj, maxIndex) {
    	    overflowChannel.set(obj, maxIndex);
    	};

    	var hexTable = (function () {
    	    var array = [];
    	    for (var i = 0; i < 256; ++i) {
    	        array[array.length] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
    	    }

    	    return array;
    	}());

    	var compactQueue = function compactQueue(queue) {
    	    while (queue.length > 1) {
    	        var item = queue.pop();
    	        var obj = item.obj[item.prop];

    	        if (isArray(obj)) {
    	            var compacted = [];

    	            for (var j = 0; j < obj.length; ++j) {
    	                if (typeof obj[j] !== 'undefined') {
    	                    compacted[compacted.length] = obj[j];
    	                }
    	            }

    	            item.obj[item.prop] = compacted;
    	        }
    	    }
    	};

    	var arrayToObject = function arrayToObject(source, options) {
    	    var obj = options && options.plainObjects ? { __proto__: null } : {};
    	    for (var i = 0; i < source.length; ++i) {
    	        if (typeof source[i] !== 'undefined') {
    	            obj[i] = source[i];
    	        }
    	    }

    	    return obj;
    	};

    	var merge = function merge(target, source, options) {
    	    /* eslint no-param-reassign: 0 */
    	    if (!source) {
    	        return target;
    	    }

    	    if (typeof source !== 'object' && typeof source !== 'function') {
    	        if (isArray(target)) {
    	            var nextIndex = target.length;
    	            if (options && typeof options.arrayLimit === 'number' && nextIndex > options.arrayLimit) {
    	                return markOverflow(arrayToObject(target.concat(source), options), nextIndex);
    	            }
    	            target[nextIndex] = source;
    	        } else if (target && typeof target === 'object') {
    	            if (isOverflow(target)) {
    	                // Add at next numeric index for overflow objects
    	                var newIndex = getMaxIndex(target) + 1;
    	                target[newIndex] = source;
    	                setMaxIndex(target, newIndex);
    	            } else if (options && options.strictMerge) {
    	                return [target, source];
    	            } else if (
    	                (options && (options.plainObjects || options.allowPrototypes))
    	                || !has.call(Object.prototype, source)
    	            ) {
    	                target[source] = true;
    	            }
    	        } else {
    	            return [target, source];
    	        }

    	        return target;
    	    }

    	    if (!target || typeof target !== 'object') {
    	        if (isOverflow(source)) {
    	            // Create new object with target at 0, source values shifted by 1
    	            var sourceKeys = Object.keys(source);
    	            var result = options && options.plainObjects
    	                ? { __proto__: null, 0: target }
    	                : { 0: target };
    	            for (var m = 0; m < sourceKeys.length; m++) {
    	                var oldKey = parseInt(sourceKeys[m], 10);
    	                result[oldKey + 1] = source[sourceKeys[m]];
    	            }
    	            return markOverflow(result, getMaxIndex(source) + 1);
    	        }
    	        var combined = [target].concat(source);
    	        if (options && typeof options.arrayLimit === 'number' && combined.length > options.arrayLimit) {
    	            return markOverflow(arrayToObject(combined, options), combined.length - 1);
    	        }
    	        return combined;
    	    }

    	    var mergeTarget = target;
    	    if (isArray(target) && !isArray(source)) {
    	        mergeTarget = arrayToObject(target, options);
    	    }

    	    if (isArray(target) && isArray(source)) {
    	        source.forEach(function (item, i) {
    	            if (has.call(target, i)) {
    	                var targetItem = target[i];
    	                if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
    	                    target[i] = merge(targetItem, item, options);
    	                } else {
    	                    target[target.length] = item;
    	                }
    	            } else {
    	                target[i] = item;
    	            }
    	        });
    	        return target;
    	    }

    	    return Object.keys(source).reduce(function (acc, key) {
    	        var value = source[key];

    	        if (has.call(acc, key)) {
    	            acc[key] = merge(acc[key], value, options);
    	        } else {
    	            acc[key] = value;
    	        }

    	        if (isOverflow(source) && !isOverflow(acc)) {
    	            markOverflow(acc, getMaxIndex(source));
    	        }
    	        if (isOverflow(acc)) {
    	            var keyNum = parseInt(key, 10);
    	            if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) {
    	                setMaxIndex(acc, keyNum);
    	            }
    	        }

    	        return acc;
    	    }, mergeTarget);
    	};

    	var assign = function assignSingleSource(target, source) {
    	    return Object.keys(source).reduce(function (acc, key) {
    	        acc[key] = source[key];
    	        return acc;
    	    }, target);
    	};

    	var decode = function (str, defaultDecoder, charset) {
    	    var strWithoutPlus = str.replace(/\+/g, ' ');
    	    if (charset === 'iso-8859-1') {
    	        // unescape never throws, no try...catch needed:
    	        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
    	    }
    	    // utf-8
    	    try {
    	        return decodeURIComponent(strWithoutPlus);
    	    } catch (e) {
    	        return strWithoutPlus;
    	    }
    	};

    	var limit = 1024;

    	/* eslint operator-linebreak: [2, "before"] */

    	var encode = function encode(str, defaultEncoder, charset, kind, format) {
    	    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
    	    // It has been adapted here for stricter adherence to RFC 3986
    	    if (str.length === 0) {
    	        return str;
    	    }

    	    var string = str;
    	    if (typeof str === 'symbol') {
    	        string = Symbol.prototype.toString.call(str);
    	    } else if (typeof str !== 'string') {
    	        string = String(str);
    	    }

    	    if (charset === 'iso-8859-1') {
    	        return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
    	            return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
    	        });
    	    }

    	    var out = '';
    	    for (var j = 0; j < string.length; j += limit) {
    	        var segment = string.length >= limit ? string.slice(j, j + limit) : string;
    	        var arr = [];

    	        for (var i = 0; i < segment.length; ++i) {
    	            var c = segment.charCodeAt(i);
    	            if (
    	                c === 0x2D // -
    	                || c === 0x2E // .
    	                || c === 0x5F // _
    	                || c === 0x7E // ~
    	                || (c >= 0x30 && c <= 0x39) // 0-9
    	                || (c >= 0x41 && c <= 0x5A) // a-z
    	                || (c >= 0x61 && c <= 0x7A) // A-Z
    	                || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
    	            ) {
    	                arr[arr.length] = segment.charAt(i);
    	                continue;
    	            }

    	            if (c < 0x80) {
    	                arr[arr.length] = hexTable[c];
    	                continue;
    	            }

    	            if (c < 0x800) {
    	                arr[arr.length] = hexTable[0xC0 | (c >> 6)]
    	                    + hexTable[0x80 | (c & 0x3F)];
    	                continue;
    	            }

    	            if (c < 0xD800 || c >= 0xE000) {
    	                arr[arr.length] = hexTable[0xE0 | (c >> 12)]
    	                    + hexTable[0x80 | ((c >> 6) & 0x3F)]
    	                    + hexTable[0x80 | (c & 0x3F)];
    	                continue;
    	            }

    	            i += 1;
    	            c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF));

    	            arr[arr.length] = hexTable[0xF0 | (c >> 18)]
    	                + hexTable[0x80 | ((c >> 12) & 0x3F)]
    	                + hexTable[0x80 | ((c >> 6) & 0x3F)]
    	                + hexTable[0x80 | (c & 0x3F)];
    	        }

    	        out += arr.join('');
    	    }

    	    return out;
    	};

    	var compact = function compact(value) {
    	    var queue = [{ obj: { o: value }, prop: 'o' }];
    	    var refs = [];

    	    for (var i = 0; i < queue.length; ++i) {
    	        var item = queue[i];
    	        var obj = item.obj[item.prop];

    	        var keys = Object.keys(obj);
    	        for (var j = 0; j < keys.length; ++j) {
    	            var key = keys[j];
    	            var val = obj[key];
    	            if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
    	                queue[queue.length] = { obj: obj, prop: key };
    	                refs[refs.length] = val;
    	            }
    	        }
    	    }

    	    compactQueue(queue);

    	    return value;
    	};

    	var isRegExp = function isRegExp(obj) {
    	    return Object.prototype.toString.call(obj) === '[object RegExp]';
    	};

    	var isBuffer = function isBuffer(obj) {
    	    if (!obj || typeof obj !== 'object') {
    	        return false;
    	    }

    	    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
    	};

    	var combine = function combine(a, b, arrayLimit, plainObjects) {
    	    // If 'a' is already an overflow object, add to it
    	    if (isOverflow(a)) {
    	        var newIndex = getMaxIndex(a) + 1;
    	        a[newIndex] = b;
    	        setMaxIndex(a, newIndex);
    	        return a;
    	    }

    	    var result = [].concat(a, b);
    	    if (result.length > arrayLimit) {
    	        return markOverflow(arrayToObject(result, { plainObjects: plainObjects }), result.length - 1);
    	    }
    	    return result;
    	};

    	var maybeMap = function maybeMap(val, fn) {
    	    if (isArray(val)) {
    	        var mapped = [];
    	        for (var i = 0; i < val.length; i += 1) {
    	            mapped[mapped.length] = fn(val[i]);
    	        }
    	        return mapped;
    	    }
    	    return fn(val);
    	};

    	utils = {
    	    arrayToObject: arrayToObject,
    	    assign: assign,
    	    combine: combine,
    	    compact: compact,
    	    decode: decode,
    	    encode: encode,
    	    isBuffer: isBuffer,
    	    isOverflow: isOverflow,
    	    isRegExp: isRegExp,
    	    markOverflow: markOverflow,
    	    maybeMap: maybeMap,
    	    merge: merge
    	};
    	return utils;
    }

    var stringify_1;
    var hasRequiredStringify;

    function requireStringify () {
    	if (hasRequiredStringify) return stringify_1;
    	hasRequiredStringify = 1;

    	var getSideChannel = requireSideChannel();
    	var utils = /*@__PURE__*/ requireUtils();
    	var formats = /*@__PURE__*/ requireFormats();
    	var has = Object.prototype.hasOwnProperty;

    	var arrayPrefixGenerators = {
    	    brackets: function brackets(prefix) {
    	        return prefix + '[]';
    	    },
    	    comma: 'comma',
    	    indices: function indices(prefix, key) {
    	        return prefix + '[' + key + ']';
    	    },
    	    repeat: function repeat(prefix) {
    	        return prefix;
    	    }
    	};

    	var isArray = Array.isArray;
    	var push = Array.prototype.push;
    	var pushToArray = function (arr, valueOrArray) {
    	    push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
    	};

    	var toISO = Date.prototype.toISOString;

    	var defaultFormat = formats['default'];
    	var defaults = {
    	    addQueryPrefix: false,
    	    allowDots: false,
    	    allowEmptyArrays: false,
    	    arrayFormat: 'indices',
    	    charset: 'utf-8',
    	    charsetSentinel: false,
    	    commaRoundTrip: false,
    	    delimiter: '&',
    	    encode: true,
    	    encodeDotInKeys: false,
    	    encoder: utils.encode,
    	    encodeValuesOnly: false,
    	    filter: void undefined,
    	    format: defaultFormat,
    	    formatter: formats.formatters[defaultFormat],
    	    // deprecated
    	    indices: false,
    	    serializeDate: function serializeDate(date) {
    	        return toISO.call(date);
    	    },
    	    skipNulls: false,
    	    strictNullHandling: false
    	};

    	var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
    	    return typeof v === 'string'
    	        || typeof v === 'number'
    	        || typeof v === 'boolean'
    	        || typeof v === 'symbol'
    	        || typeof v === 'bigint';
    	};

    	var sentinel = {};

    	var stringify = function stringify(
    	    object,
    	    prefix,
    	    generateArrayPrefix,
    	    commaRoundTrip,
    	    allowEmptyArrays,
    	    strictNullHandling,
    	    skipNulls,
    	    encodeDotInKeys,
    	    encoder,
    	    filter,
    	    sort,
    	    allowDots,
    	    serializeDate,
    	    format,
    	    formatter,
    	    encodeValuesOnly,
    	    charset,
    	    sideChannel
    	) {
    	    var obj = object;

    	    var tmpSc = sideChannel;
    	    var step = 0;
    	    var findFlag = false;
    	    while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {
    	        // Where object last appeared in the ref tree
    	        var pos = tmpSc.get(object);
    	        step += 1;
    	        if (typeof pos !== 'undefined') {
    	            if (pos === step) {
    	                throw new RangeError('Cyclic object value');
    	            } else {
    	                findFlag = true; // Break while
    	            }
    	        }
    	        if (typeof tmpSc.get(sentinel) === 'undefined') {
    	            step = 0;
    	        }
    	    }

    	    if (typeof filter === 'function') {
    	        obj = filter(prefix, obj);
    	    } else if (obj instanceof Date) {
    	        obj = serializeDate(obj);
    	    } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
    	        obj = utils.maybeMap(obj, function (value) {
    	            if (value instanceof Date) {
    	                return serializeDate(value);
    	            }
    	            return value;
    	        });
    	    }

    	    if (obj === null) {
    	        if (strictNullHandling) {
    	            return formatter(encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix);
    	        }

    	        obj = '';
    	    }

    	    if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
    	        if (encoder) {
    	            var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
    	            return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
    	        }
    	        return [formatter(prefix) + '=' + formatter(String(obj))];
    	    }

    	    var values = [];

    	    if (typeof obj === 'undefined') {
    	        return values;
    	    }

    	    var objKeys;
    	    if (generateArrayPrefix === 'comma' && isArray(obj)) {
    	        // we need to join elements in
    	        if (encodeValuesOnly && encoder) {
    	            obj = utils.maybeMap(obj, function (v) {
    	                return v == null ? v : encoder(v);
    	            });
    	        }
    	        objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
    	    } else if (isArray(filter)) {
    	        objKeys = filter;
    	    } else {
    	        var keys = Object.keys(obj);
    	        objKeys = sort ? keys.sort(sort) : keys;
    	    }

    	    var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix);

    	    var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix;

    	    if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
    	        return adjustedPrefix + '[]';
    	    }

    	    for (var j = 0; j < objKeys.length; ++j) {
    	        var key = objKeys[j];
    	        var value = typeof key === 'object' && key && typeof key.value !== 'undefined'
    	            ? key.value
    	            : obj[key];

    	        if (skipNulls && value === null) {
    	            continue;
    	        }

    	        var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key);
    	        var keyPrefix = isArray(obj)
    	            ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix
    	            : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']');

    	        sideChannel.set(object, step);
    	        var valueSideChannel = getSideChannel();
    	        valueSideChannel.set(sentinel, sideChannel);
    	        pushToArray(values, stringify(
    	            value,
    	            keyPrefix,
    	            generateArrayPrefix,
    	            commaRoundTrip,
    	            allowEmptyArrays,
    	            strictNullHandling,
    	            skipNulls,
    	            encodeDotInKeys,
    	            generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,
    	            filter,
    	            sort,
    	            allowDots,
    	            serializeDate,
    	            format,
    	            formatter,
    	            encodeValuesOnly,
    	            charset,
    	            valueSideChannel
    	        ));
    	    }

    	    return values;
    	};

    	var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
    	    if (!opts) {
    	        return defaults;
    	    }

    	    if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
    	        throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
    	    }

    	    if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {
    	        throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');
    	    }

    	    if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
    	        throw new TypeError('Encoder has to be a function.');
    	    }

    	    var charset = opts.charset || defaults.charset;
    	    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
    	        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
    	    }

    	    var format = formats['default'];
    	    if (typeof opts.format !== 'undefined') {
    	        if (!has.call(formats.formatters, opts.format)) {
    	            throw new TypeError('Unknown format option provided.');
    	        }
    	        format = opts.format;
    	    }
    	    var formatter = formats.formatters[format];

    	    var filter = defaults.filter;
    	    if (typeof opts.filter === 'function' || isArray(opts.filter)) {
    	        filter = opts.filter;
    	    }

    	    var arrayFormat;
    	    if (opts.arrayFormat in arrayPrefixGenerators) {
    	        arrayFormat = opts.arrayFormat;
    	    } else if ('indices' in opts) {
    	        arrayFormat = opts.indices ? 'indices' : 'repeat';
    	    } else {
    	        arrayFormat = defaults.arrayFormat;
    	    }

    	    if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
    	        throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
    	    }

    	    var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;

    	    return {
    	        addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
    	        allowDots: allowDots,
    	        allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
    	        arrayFormat: arrayFormat,
    	        charset: charset,
    	        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
    	        commaRoundTrip: !!opts.commaRoundTrip,
    	        delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
    	        encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
    	        encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
    	        encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
    	        encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
    	        filter: filter,
    	        format: format,
    	        formatter: formatter,
    	        serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
    	        skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
    	        sort: typeof opts.sort === 'function' ? opts.sort : null,
    	        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
    	    };
    	};

    	stringify_1 = function (object, opts) {
    	    var obj = object;
    	    var options = normalizeStringifyOptions(opts);

    	    var objKeys;
    	    var filter;

    	    if (typeof options.filter === 'function') {
    	        filter = options.filter;
    	        obj = filter('', obj);
    	    } else if (isArray(options.filter)) {
    	        filter = options.filter;
    	        objKeys = filter;
    	    }

    	    var keys = [];

    	    if (typeof obj !== 'object' || obj === null) {
    	        return '';
    	    }

    	    var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat];
    	    var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;

    	    if (!objKeys) {
    	        objKeys = Object.keys(obj);
    	    }

    	    if (options.sort) {
    	        objKeys.sort(options.sort);
    	    }

    	    var sideChannel = getSideChannel();
    	    for (var i = 0; i < objKeys.length; ++i) {
    	        var key = objKeys[i];

    	        if (typeof key === 'undefined' || key === null) {
    	            continue;
    	        }

    	        var value = obj[key];

    	        if (options.skipNulls && value === null) {
    	            continue;
    	        }
    	        pushToArray(keys, stringify(
    	            value,
    	            key,
    	            generateArrayPrefix,
    	            commaRoundTrip,
    	            options.allowEmptyArrays,
    	            options.strictNullHandling,
    	            options.skipNulls,
    	            options.encodeDotInKeys,
    	            options.encode ? options.encoder : null,
    	            options.filter,
    	            options.sort,
    	            options.allowDots,
    	            options.serializeDate,
    	            options.format,
    	            options.formatter,
    	            options.encodeValuesOnly,
    	            options.charset,
    	            sideChannel
    	        ));
    	    }

    	    var joined = keys.join(options.delimiter);
    	    var prefix = options.addQueryPrefix === true ? '?' : '';

    	    if (options.charsetSentinel) {
    	        if (options.charset === 'iso-8859-1') {
    	            // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
    	            prefix += 'utf8=%26%2310003%3B' + options.delimiter;
    	        } else {
    	            // encodeURIComponent('✓')
    	            prefix += 'utf8=%E2%9C%93' + options.delimiter;
    	        }
    	    }

    	    return joined.length > 0 ? prefix + joined : '';
    	};
    	return stringify_1;
    }

    var parse;
    var hasRequiredParse;

    function requireParse () {
    	if (hasRequiredParse) return parse;
    	hasRequiredParse = 1;

    	var utils = /*@__PURE__*/ requireUtils();

    	var has = Object.prototype.hasOwnProperty;
    	var isArray = Array.isArray;

    	var defaults = {
    	    allowDots: false,
    	    allowEmptyArrays: false,
    	    allowPrototypes: false,
    	    allowSparse: false,
    	    arrayLimit: 20,
    	    charset: 'utf-8',
    	    charsetSentinel: false,
    	    comma: false,
    	    decodeDotInKeys: false,
    	    decoder: utils.decode,
    	    delimiter: '&',
    	    depth: 5,
    	    duplicates: 'combine',
    	    ignoreQueryPrefix: false,
    	    interpretNumericEntities: false,
    	    parameterLimit: 1000,
    	    parseArrays: true,
    	    plainObjects: false,
    	    strictDepth: false,
    	    strictMerge: true,
    	    strictNullHandling: false,
    	    throwOnLimitExceeded: false
    	};

    	var interpretNumericEntities = function (str) {
    	    return str.replace(/&#(\d+);/g, function ($0, numberStr) {
    	        return String.fromCharCode(parseInt(numberStr, 10));
    	    });
    	};

    	var parseArrayValue = function (val, options, currentArrayLength) {
    	    if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
    	        return val.split(',');
    	    }

    	    if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) {
    	        throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
    	    }

    	    return val;
    	};

    	// This is what browsers will submit when the ✓ character occurs in an
    	// application/x-www-form-urlencoded body and the encoding of the page containing
    	// the form is iso-8859-1, or when the submitted form has an accept-charset
    	// attribute of iso-8859-1. Presumably also with other charsets that do not contain
    	// the ✓ character, such as us-ascii.
    	var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')

    	// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
    	var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')

    	var parseValues = function parseQueryStringValues(str, options) {
    	    var obj = { __proto__: null };

    	    var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
    	    cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']');

    	    var limit = options.parameterLimit === Infinity ? void undefined : options.parameterLimit;
    	    var parts = cleanStr.split(
    	        options.delimiter,
    	        options.throwOnLimitExceeded && typeof limit !== 'undefined' ? limit + 1 : limit
    	    );

    	    if (options.throwOnLimitExceeded && typeof limit !== 'undefined' && parts.length > limit) {
    	        throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.');
    	    }

    	    var skipIndex = -1; // Keep track of where the utf8 sentinel was found
    	    var i;

    	    var charset = options.charset;
    	    if (options.charsetSentinel) {
    	        for (i = 0; i < parts.length; ++i) {
    	            if (parts[i].indexOf('utf8=') === 0) {
    	                if (parts[i] === charsetSentinel) {
    	                    charset = 'utf-8';
    	                } else if (parts[i] === isoSentinel) {
    	                    charset = 'iso-8859-1';
    	                }
    	                skipIndex = i;
    	                i = parts.length; // The eslint settings do not allow break;
    	            }
    	        }
    	    }

    	    for (i = 0; i < parts.length; ++i) {
    	        if (i === skipIndex) {
    	            continue;
    	        }
    	        var part = parts[i];

    	        var bracketEqualsPos = part.indexOf(']=');
    	        var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;

    	        var key;
    	        var val;
    	        if (pos === -1) {
    	            key = options.decoder(part, defaults.decoder, charset, 'key');
    	            val = options.strictNullHandling ? null : '';
    	        } else {
    	            key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');

    	            if (key !== null) {
    	                val = utils.maybeMap(
    	                    parseArrayValue(
    	                        part.slice(pos + 1),
    	                        options,
    	                        isArray(obj[key]) ? obj[key].length : 0
    	                    ),
    	                    function (encodedVal) {
    	                        return options.decoder(encodedVal, defaults.decoder, charset, 'value');
    	                    }
    	                );
    	            }
    	        }

    	        if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
    	            val = interpretNumericEntities(String(val));
    	        }

    	        if (part.indexOf('[]=') > -1) {
    	            val = isArray(val) ? [val] : val;
    	        }

    	        if (options.comma && isArray(val) && val.length > options.arrayLimit) {
    	            if (options.throwOnLimitExceeded) {
    	                throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
    	            }
    	            val = utils.combine([], val, options.arrayLimit, options.plainObjects);
    	        }

    	        if (key !== null) {
    	            var existing = has.call(obj, key);
    	            if (existing && (options.duplicates === 'combine' || part.indexOf('[]=') > -1)) {
    	                obj[key] = utils.combine(
    	                    obj[key],
    	                    val,
    	                    options.arrayLimit,
    	                    options.plainObjects
    	                );
    	            } else if (!existing || options.duplicates === 'last') {
    	                obj[key] = val;
    	            }
    	        }
    	    }

    	    return obj;
    	};

    	var parseObject = function (chain, val, options, valuesParsed) {
    	    var currentArrayLength = 0;
    	    if (chain.length > 0 && chain[chain.length - 1] === '[]') {
    	        var parentKey = chain.slice(0, -1).join('');
    	        currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0;
    	    }

    	    var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength);

    	    for (var i = chain.length - 1; i >= 0; --i) {
    	        var obj;
    	        var root = chain[i];

    	        if (root === '[]' && options.parseArrays) {
    	            if (utils.isOverflow(leaf)) {
    	                // leaf is already an overflow object, preserve it
    	                obj = leaf;
    	            } else {
    	                obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null))
    	                    ? []
    	                    : utils.combine(
    	                        [],
    	                        leaf,
    	                        options.arrayLimit,
    	                        options.plainObjects
    	                    );
    	            }
    	        } else {
    	            obj = options.plainObjects ? { __proto__: null } : {};
    	            var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
    	            var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot;
    	            var index = parseInt(decodedRoot, 10);
    	            var isValidArrayIndex = !isNaN(index)
    	                && root !== decodedRoot
    	                && String(index) === decodedRoot
    	                && index >= 0
    	                && options.parseArrays;
    	            if (!options.parseArrays && decodedRoot === '') {
    	                obj = { 0: leaf };
    	            } else if (isValidArrayIndex && index < options.arrayLimit) {
    	                obj = [];
    	                obj[index] = leaf;
    	            } else if (isValidArrayIndex && options.throwOnLimitExceeded) {
    	                throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
    	            } else if (isValidArrayIndex) {
    	                obj[index] = leaf;
    	                utils.markOverflow(obj, index);
    	            } else if (decodedRoot !== '__proto__') {
    	                obj[decodedRoot] = leaf;
    	            }
    	        }

    	        leaf = obj;
    	    }

    	    return leaf;
    	};

    	// Split a key like "a[b][c[]]" into ['a', '[b]', '[c[]]'] while preserving
    	// qs parse semantics for depth/prototype guards.
    	var splitKeyIntoSegments = function splitKeyIntoSegments(originalKey, options) {
    	    var key = options.allowDots ? originalKey.replace(/\.([^.[]+)/g, '[$1]') : originalKey;

    	    // depth <= 0 keeps the whole key as one segment
    	    if (options.depth <= 0) {
    	        if (!options.plainObjects && has.call(Object.prototype, key)) {
    	            if (!options.allowPrototypes) {
    	                return;
    	            }
    	        }

    	        return [key];
    	    }

    	    var segments = [];

    	    // parent before the first '[' (may be empty if key starts with '[')
    	    var first = key.indexOf('[');
    	    var parent = first >= 0 ? key.slice(0, first) : key;
    	    if (parent) {
    	        if (!options.plainObjects && has.call(Object.prototype, parent)) {
    	            if (!options.allowPrototypes) {
    	                return;
    	            }
    	        }

    	        segments[segments.length] = parent;
    	    }

    	    var n = key.length;
    	    var open = first;
    	    var collected = 0;

    	    while (open >= 0 && collected < options.depth) {
    	        var level = 1;
    	        var i = open + 1;
    	        var close = -1;

    	        // balance nested '[' and ']' inside this bracket group using a nesting level counter
    	        while (i < n && close < 0) {
    	            var cu = key.charCodeAt(i);
    	            if (cu === 0x5B) { // '['
    	                level += 1;
    	            } else if (cu === 0x5D) { // ']'
    	                level -= 1;
    	                if (level === 0) {
    	                    close = i; // found matching close; loop will exit by condition
    	                }
    	            }
    	            i += 1;
    	        }

    	        if (close < 0) {
    	            // Unterminated group: wrap the raw remainder in one bracket pair so it stays
    	            // a single literal segment (e.g. "[[]b" -> "[[]b]"); we do not infer missing ']'.
    	            segments[segments.length] = '[' + key.slice(open) + ']';
    	            return segments;
    	        }

    	        var seg = key.slice(open, close + 1);
    	        // prototype guard for the content of this group
    	        var content = seg.slice(1, -1);
    	        if (!options.plainObjects && has.call(Object.prototype, content) && !options.allowPrototypes) {
    	            return;
    	        }

    	        segments[segments.length] = seg;
    	        collected += 1;

    	        // find the next '[' after this balanced group
    	        open = key.indexOf('[', close + 1);
    	    }

    	    if (open >= 0) {
    	        if (options.strictDepth === true) {
    	            throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true');
    	        }

    	        segments[segments.length] = '[' + key.slice(open) + ']';
    	    }

    	    return segments;
    	};

    	var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
    	    if (!givenKey) {
    	        return;
    	    }

    	    var keys = splitKeyIntoSegments(givenKey, options);

    	    if (!keys) {
    	        return;
    	    }

    	    return parseObject(keys, val, options, valuesParsed);
    	};

    	var normalizeParseOptions = function normalizeParseOptions(opts) {
    	    if (!opts) {
    	        return defaults;
    	    }

    	    if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
    	        throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
    	    }

    	    if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') {
    	        throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided');
    	    }

    	    if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') {
    	        throw new TypeError('Decoder has to be a function.');
    	    }

    	    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
    	        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
    	    }

    	    if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') {
    	        throw new TypeError('`throwOnLimitExceeded` option must be a boolean');
    	    }

    	    var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;

    	    var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates;

    	    if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') {
    	        throw new TypeError('The duplicates option must be either combine, first, or last');
    	    }

    	    var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;

    	    return {
    	        allowDots: allowDots,
    	        allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
    	        allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
    	        allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
    	        arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
    	        charset: charset,
    	        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
    	        comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
    	        decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys,
    	        decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
    	        delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
    	        // eslint-disable-next-line no-implicit-coercion, no-extra-parens
    	        depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
    	        duplicates: duplicates,
    	        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
    	        interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
    	        parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
    	        parseArrays: opts.parseArrays !== false,
    	        plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
    	        strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth,
    	        strictMerge: typeof opts.strictMerge === 'boolean' ? !!opts.strictMerge : defaults.strictMerge,
    	        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,
    	        throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false
    	    };
    	};

    	parse = function (str, opts) {
    	    var options = normalizeParseOptions(opts);

    	    if (str === '' || str === null || typeof str === 'undefined') {
    	        return options.plainObjects ? { __proto__: null } : {};
    	    }

    	    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
    	    var obj = options.plainObjects ? { __proto__: null } : {};

    	    // Iterate over the keys and setup the new object

    	    var keys = Object.keys(tempObj);
    	    for (var i = 0; i < keys.length; ++i) {
    	        var key = keys[i];
    	        var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
    	        obj = utils.merge(obj, newObj, options);
    	    }

    	    if (options.allowSparse === true) {
    	        return obj;
    	    }

    	    return utils.compact(obj);
    	};
    	return parse;
    }

    var lib;
    var hasRequiredLib;

    function requireLib () {
    	if (hasRequiredLib) return lib;
    	hasRequiredLib = 1;

    	var stringify = /*@__PURE__*/ requireStringify();
    	var parse = /*@__PURE__*/ requireParse();
    	var formats = /*@__PURE__*/ requireFormats();

    	lib = {
    	    formats: formats,
    	    parse: parse,
    	    stringify: stringify
    	};
    	return lib;
    }

    var libExports = /*@__PURE__*/ requireLib();
    var qs = /*@__PURE__*/getDefaultExportFromCjs(libExports);

    // Matches 'sub.host:port' or 'host:port' and extracts hostname and port
    // Also enforces toplevel domain specified, no spaces and no protocol
    const HOST_REGEX = /^(?!\w+:\/\/)([^\s:]+\.?[^\s:]+)(?::(\d+))?(?!:)$/;
    /**
     * Create default options
     * @private
     * @param {CreateHttpClientParams} options - Initialization parameters for the HTTP client
     * @return {DefaultOptions} options to pass to axios
     */
    function createDefaultOptions(options) {
        const defaultConfig = {
            insecure: false,
            retryOnError: true,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            logHandler: (level, data) => {
                if (level === 'error' && data) {
                    const title = [data.name, data.message].filter((a) => a).join(' - ');
                    console.error(`[error] ${title}`);
                    console.error(data);
                    return;
                }
                console.log(`[${level}] ${data}`);
            },
            // Passed to axios
            headers: {},
            httpAgent: false,
            httpsAgent: false,
            timeout: 30000,
            throttle: 0,
            basePath: '',
            adapter: undefined,
            maxContentLength: 1073741824, // 1GB
            maxBodyLength: 1073741824, // 1GB
        };
        const config = {
            ...defaultConfig,
            ...options,
        };
        if (!config.accessToken) {
            const missingAccessTokenError = new TypeError('Expected parameter accessToken');
            config.logHandler('error', missingAccessTokenError);
            throw missingAccessTokenError;
        }
        // Construct axios baseURL option
        const protocol = config.insecure ? 'http' : 'https';
        const space = config.space ? `${config.space}/` : '';
        let hostname = config.defaultHostname;
        let port = config.insecure ? 80 : 443;
        if (config.host && HOST_REGEX.test(config.host)) {
            const parsed = config.host.split(':');
            if (parsed.length === 2) {
                [hostname, port] = parsed;
            }
            else {
                hostname = parsed[0];
            }
        }
        // Ensure that basePath does start but not end with a slash
        if (config.basePath) {
            config.basePath = `/${config.basePath.split('/').filter(Boolean).join('/')}`;
        }
        const baseURL = options.baseURL || `${protocol}://${hostname}:${port}${config.basePath}/spaces/${space}`;
        if (!config.headers.Authorization && typeof config.accessToken !== 'function') {
            config.headers.Authorization = 'Bearer ' + config.accessToken;
        }
        const axiosOptions = {
            // Axios
            baseURL,
            headers: config.headers,
            httpAgent: config.httpAgent,
            httpsAgent: config.httpsAgent,
            proxy: config.proxy,
            timeout: config.timeout,
            adapter: config.adapter,
            fetchOptions: config.fetchOptions,
            maxContentLength: config.maxContentLength,
            maxBodyLength: config.maxBodyLength,
            paramsSerializer: {
                serialize: (params) => {
                    return qs.stringify(params);
                },
            },
            // Contentful
            logHandler: config.logHandler,
            responseLogger: config.responseLogger,
            requestLogger: config.requestLogger,
            retryOnError: config.retryOnError,
        };
        return axiosOptions;
    }

    function copyHttpClientParams(options) {
        const copiedOptions = index$2(options);
        // httpAgent and httpsAgent cannot be copied because they can contain private fields
        copiedOptions.httpAgent = options.httpAgent;
        copiedOptions.httpsAgent = options.httpsAgent;
        return copiedOptions;
    }
    /**
     * Create pre-configured axios instance
     * @private
     * @param {AxiosStatic} axios - Axios library
     * @param {CreateHttpClientParams} options - Initialization parameters for the HTTP client
     * @return {AxiosInstance} Initialized axios instance
     */
    function createHttpClient(axios, options) {
        const axiosOptions = createDefaultOptions(options);
        const instance = axios.create(axiosOptions);
        instance.httpClientParams = options;
        /**
         * Creates a new axios instance with the same default base parameters as the
         * current one, and with any overrides passed to the newParams object
         * This is useful as the SDKs use dependency injection to get the axios library
         * and the version of the library comes from different places depending
         * on whether it's a browser build or a node.js build.
         * @private
         * @param {CreateHttpClientParams} newParams - Initialization parameters for the HTTP client
         * @return {AxiosInstance} Initialized axios instance
         */
        instance.cloneWithNewParams = function (newParams) {
            return createHttpClient(axios, {
                ...copyHttpClientParams(options),
                ...newParams,
            });
        };
        /**
         * Apply interceptors.
         * Please note that the order of interceptors is important
         */
        if (options.onBeforeRequest) {
            instance.interceptors.request.use(options.onBeforeRequest);
        }
        if (typeof options.accessToken === 'function') {
            asyncToken(instance, options.accessToken);
        }
        if (options.throttle) {
            rateLimitThrottle(instance, options.throttle);
        }
        rateLimit(instance, options.retryLimit);
        if (options.onError) {
            instance.interceptors.response.use((response) => response, options.onError);
        }
        return instance;
    }

    /**
     * Creates request parameters configuration by parsing an existing query object
     * @private
     * @param {Object} query
     * @return {Object} Config object with `params` property, ready to be used in axios
     */
    function createRequestConfig({ query }) {
        const config = {};
        delete query.resolveLinks;
        config.params = index$2(query);
        return config;
    }

    // copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
    function deepFreeze(object) {
        const propNames = Object.getOwnPropertyNames(object);
        for (const name of propNames) {
            const value = object[name];
            if (value && typeof value === 'object') {
                deepFreeze(value);
            }
        }
        return Object.freeze(object);
    }
    function freezeSys(obj) {
        deepFreeze(obj.sys || {});
        return obj;
    }

    function getBrowserOS() {
        const win = getWindow();
        if (!win) {
            return null;
        }
        const userAgent = win.navigator.userAgent;
        // TODO: platform is deprecated.
        const platform = win.navigator.platform;
        const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];
        const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];
        const iosPlatforms = ['iPhone', 'iPad', 'iPod'];
        if (macosPlatforms.indexOf(platform) !== -1) {
            return 'macOS';
        }
        else if (iosPlatforms.indexOf(platform) !== -1) {
            return 'iOS';
        }
        else if (windowsPlatforms.indexOf(platform) !== -1) {
            return 'Windows';
        }
        else if (/Android/.test(userAgent)) {
            return 'Android';
        }
        else if (/Linux/.test(platform)) {
            return 'Linux';
        }
        return null;
    }
    function getNodeOS() {
        const platform = process$1.platform || 'linux';
        const version = process$1.version || '0.0.0';
        const platformMap = {
            android: 'Android',
            aix: 'Linux',
            darwin: 'macOS',
            freebsd: 'Linux',
            linux: 'Linux',
            openbsd: 'Linux',
            sunos: 'Linux',
            win32: 'Windows',
        };
        if (platform in platformMap) {
            return `${platformMap[platform] || 'Linux'}/${version}`;
        }
        return null;
    }
    function getUserAgentHeader(sdk, application, integration, feature) {
        const headerParts = [];
        if (application) {
            headerParts.push(`app ${application}`);
        }
        if (integration) {
            headerParts.push(`integration ${integration}`);
        }
        if (feature) {
            headerParts.push('feature ' + feature);
        }
        headerParts.push(`sdk ${sdk}`);
        let platform = null;
        try {
            if (isReactNative()) {
                platform = getBrowserOS();
                headerParts.push('platform ReactNative');
            }
            else if (isNode()) {
                platform = getNodeOS();
                headerParts.push(`platform node.js/${getNodeVersion()}`);
            }
            else {
                platform = getBrowserOS();
                headerParts.push('platform browser');
            }
        }
        catch (e) {
            platform = null;
        }
        if (platform) {
            headerParts.push(`os ${platform}`);
        }
        return `${headerParts.filter((item) => item !== '').join('; ')};`;
    }

    /**
     * Mixes in a method to return just a plain object with no additional methods
     * @private
     * @param data - Any plain JSON response returned from the API
     * @return Enhanced object with toPlainObject method
     */
    function toPlainObject(data) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        return Object.defineProperty(data, 'toPlainObject', {
            enumerable: false,
            configurable: false,
            writable: false,
            value: function () {
                return index$2(this);
            },
        });
    }

    /**
     * Creates a unary function that invokes `func` with its argument transformed.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {Function} transform The argument transform.
     * @returns {Function} Returns the new function.
     */

    var _overArg;
    var hasRequired_overArg;

    function require_overArg () {
    	if (hasRequired_overArg) return _overArg;
    	hasRequired_overArg = 1;
    	function overArg(func, transform) {
    	  return function(arg) {
    	    return func(transform(arg));
    	  };
    	}

    	_overArg = overArg;
    	return _overArg;
    }

    var _getPrototype;
    var hasRequired_getPrototype;

    function require_getPrototype () {
    	if (hasRequired_getPrototype) return _getPrototype;
    	hasRequired_getPrototype = 1;
    	var overArg = require_overArg();

    	/** Built-in value references. */
    	var getPrototype = overArg(Object.getPrototypeOf, Object);

    	_getPrototype = getPrototype;
    	return _getPrototype;
    }

    var isPlainObject_1;
    var hasRequiredIsPlainObject;

    function requireIsPlainObject () {
    	if (hasRequiredIsPlainObject) return isPlainObject_1;
    	hasRequiredIsPlainObject = 1;
    	var baseGetTag = require_baseGetTag(),
    	    getPrototype = require_getPrototype(),
    	    isObjectLike = requireIsObjectLike();

    	/** `Object#toString` result references. */
    	var objectTag = '[object Object]';

    	/** Used for built-in method references. */
    	var funcProto = Function.prototype,
    	    objectProto = Object.prototype;

    	/** Used to resolve the decompiled source of functions. */
    	var funcToString = funcProto.toString;

    	/** Used to check objects for own properties. */
    	var hasOwnProperty = objectProto.hasOwnProperty;

    	/** Used to infer the `Object` constructor. */
    	var objectCtorString = funcToString.call(Object);

    	/**
    	 * Checks if `value` is a plain object, that is, an object created by the
    	 * `Object` constructor or one with a `[[Prototype]]` of `null`.
    	 *
    	 * @static
    	 * @memberOf _
    	 * @since 0.8.0
    	 * @category Lang
    	 * @param {*} value The value to check.
    	 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
    	 * @example
    	 *
    	 * function Foo() {
    	 *   this.a = 1;
    	 * }
    	 *
    	 * _.isPlainObject(new Foo);
    	 * // => false
    	 *
    	 * _.isPlainObject([1, 2, 3]);
    	 * // => false
    	 *
    	 * _.isPlainObject({ 'x': 0, 'y': 0 });
    	 * // => true
    	 *
    	 * _.isPlainObject(Object.create(null));
    	 * // => true
    	 */
    	function isPlainObject(value) {
    	  if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
    	    return false;
    	  }
    	  var proto = getPrototype(value);
    	  if (proto === null) {
    	    return true;
    	  }
    	  var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
    	  return typeof Ctor == 'function' && Ctor instanceof Ctor &&
    	    funcToString.call(Ctor) == objectCtorString;
    	}

    	isPlainObject_1 = isPlainObject;
    	return isPlainObject_1;
    }

    var isPlainObjectExports = requireIsPlainObject();
    var isPlainObject = /*@__PURE__*/getDefaultExportFromCjs(isPlainObjectExports);

    function obscureHeaders(config) {
        // Management, Delivery and Preview API tokens
        if (config?.headers?.['Authorization']) {
            const token = `...${config.headers['Authorization'].toString().substr(-5)}`;
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        // Encoded Delivery or Preview token map for Cross-Space References
        if (config?.headers?.['X-Contentful-Resource-Resolution']) {
            const token = `...${config.headers['X-Contentful-Resource-Resolution'].toString().substr(-5)}`;
            config.headers['X-Contentful-Resource-Resolution'] = token;
        }
    }
    /**
     * Handles errors received from the server. Parses the error into a more useful
     * format, places it in an exception and throws it.
     * See https://www.contentful.com/developers/docs/references/errors/
     * for more details on the data received on the errorResponse.data property
     * and the expected error codes.
     * @private
     */
    function errorHandler(errorResponse) {
        const { config, response } = errorResponse;
        let errorName;
        obscureHeaders(config);
        if (!isPlainObject(response) || !isPlainObject(config)) {
            throw errorResponse;
        }
        const data = response?.data;
        const errorData = {
            status: response?.status,
            statusText: response?.statusText,
            message: '',
            details: {},
        };
        if (config && isPlainObject(config)) {
            errorData.request = {
                url: config.url,
                headers: config.headers,
                method: config.method,
                payloadData: config.data,
            };
        }
        if (data && typeof data === 'object') {
            if ('requestId' in data) {
                errorData.requestId = data.requestId || 'UNKNOWN';
            }
            if ('message' in data) {
                errorData.message = data.message || '';
            }
            if ('details' in data) {
                errorData.details = data.details || {};
            }
            errorName = data.sys?.id;
        }
        const error = new Error();
        error.name =
            errorName && errorName !== 'Unknown' ? errorName : `${response?.status} ${response?.statusText}`;
        try {
            error.message = JSON.stringify(errorData, null, '  ');
        }
        catch {
            error.message = errorData?.message ?? '';
        }
        throw error;
    }

    /*! Axios v1.18.0 Copyright (c) 2026 Matt Zabriskie and contributors */

    var axios_1;
    var hasRequiredAxios;

    function requireAxios () {
    	if (hasRequiredAxios) return axios_1;
    	hasRequiredAxios = 1;

    	/**
    	 * Create a bound version of a function with a specified `this` context
    	 *
    	 * @param {Function} fn - The function to bind
    	 * @param {*} thisArg - The value to be passed as the `this` parameter
    	 * @returns {Function} A new function that will call the original function with the specified `this` context
    	 */
    	function bind(fn, thisArg) {
    	  return function wrap() {
    	    return fn.apply(thisArg, arguments);
    	  };
    	}

    	// utils is a library of generic helper functions non-specific to axios

    	const { toString } = Object.prototype;
    	const { getPrototypeOf } = Object;
    	const { iterator, toStringTag } = Symbol;

    	/* Creating a function that will check if an object has a property. */
    	const hasOwnProperty = (
    	  ({ hasOwnProperty }) =>
    	  (obj, prop) =>
    	    hasOwnProperty.call(obj, prop)
    	)(Object.prototype);

    	/**
    	 * Walk the prototype chain (excluding the shared Object.prototype) looking for
    	 * an own `prop`. This distinguishes genuine own/inherited members — including
    	 * class accessors and template prototypes — from members injected via
    	 * Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
    	 * live on Object.prototype itself and are therefore never matched.
    	 *
    	 * @param {*} thing The value whose chain to inspect
    	 * @param {string|symbol} prop The property key to look for
    	 *
    	 * @returns {boolean} True when `prop` is owned below Object.prototype
    	 */
    	const hasOwnInPrototypeChain = (thing, prop) => {
    	  let obj = thing;
    	  const seen = [];

    	  while (obj != null && obj !== Object.prototype) {
    	    if (seen.indexOf(obj) !== -1) {
    	      return false;
    	    }
    	    seen.push(obj);

    	    if (hasOwnProperty(obj, prop)) {
    	      return true;
    	    }
    	    obj = getPrototypeOf(obj);
    	  }
    	  return false;
    	};

    	/**
    	 * Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
    	 * properties and members inherited from a non-Object.prototype source (a class
    	 * instance or template object) are honored; a value reachable only through a
    	 * polluted Object.prototype is ignored and `undefined` is returned.
    	 *
    	 * @param {*} obj The source object
    	 * @param {string|symbol} prop The property key to read
    	 *
    	 * @returns {*} The resolved value, or undefined when unsafe/absent
    	 */
    	const getSafeProp = (obj, prop) =>
    	  obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;

    	const kindOf = ((cache) => (thing) => {
    	  const str = toString.call(thing);
    	  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
    	})(Object.create(null));

    	const kindOfTest = (type) => {
    	  type = type.toLowerCase();
    	  return (thing) => kindOf(thing) === type;
    	};

    	const typeOfTest = (type) => (thing) => typeof thing === type;

    	/**
    	 * Determine if a value is a non-null object
    	 *
    	 * @param {Object} val The value to test
    	 *
    	 * @returns {boolean} True if value is an Array, otherwise false
    	 */
    	const { isArray } = Array;

    	/**
    	 * Determine if a value is undefined
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if the value is undefined, otherwise false
    	 */
    	const isUndefined = typeOfTest('undefined');

    	/**
    	 * Determine if a value is a Buffer
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a Buffer, otherwise false
    	 */
    	function isBuffer(val) {
    	  return (
    	    val !== null &&
    	    !isUndefined(val) &&
    	    val.constructor !== null &&
    	    !isUndefined(val.constructor) &&
    	    isFunction$1(val.constructor.isBuffer) &&
    	    val.constructor.isBuffer(val)
    	  );
    	}

    	/**
    	 * Determine if a value is an ArrayBuffer
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
    	 */
    	const isArrayBuffer = kindOfTest('ArrayBuffer');

    	/**
    	 * Determine if a value is a view on an ArrayBuffer
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
    	 */
    	function isArrayBufferView(val) {
    	  let result;
    	  if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
    	    result = ArrayBuffer.isView(val);
    	  } else {
    	    result = val && val.buffer && isArrayBuffer(val.buffer);
    	  }
    	  return result;
    	}

    	/**
    	 * Determine if a value is a String
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a String, otherwise false
    	 */
    	const isString = typeOfTest('string');

    	/**
    	 * Determine if a value is a Function
    	 *
    	 * @param {*} val The value to test
    	 * @returns {boolean} True if value is a Function, otherwise false
    	 */
    	const isFunction$1 = typeOfTest('function');

    	/**
    	 * Determine if a value is a Number
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a Number, otherwise false
    	 */
    	const isNumber = typeOfTest('number');

    	/**
    	 * Determine if a value is an Object
    	 *
    	 * @param {*} thing The value to test
    	 *
    	 * @returns {boolean} True if value is an Object, otherwise false
    	 */
    	const isObject = (thing) => thing !== null && typeof thing === 'object';

    	/**
    	 * Determine if a value is a Boolean
    	 *
    	 * @param {*} thing The value to test
    	 * @returns {boolean} True if value is a Boolean, otherwise false
    	 */
    	const isBoolean = (thing) => thing === true || thing === false;

    	/**
    	 * Determine if a value is a plain Object
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a plain Object, otherwise false
    	 */
    	const isPlainObject = (val) => {
    	  if (!isObject(val)) {
    	    return false;
    	  }

    	  const prototype = getPrototypeOf(val);
    	  return (
    	    (prototype === null ||
    	      prototype === Object.prototype ||
    	      getPrototypeOf(prototype) === null) &&
    	    // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
    	    // Symbol.iterator as evidence the value is a tagged/iterable type rather
    	    // than a plain object, while ignoring keys injected onto Object.prototype.
    	    !hasOwnInPrototypeChain(val, toStringTag) &&
    	    !hasOwnInPrototypeChain(val, iterator)
    	  );
    	};

    	/**
    	 * Determine if a value is an empty object (safely handles Buffers)
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is an empty object, otherwise false
    	 */
    	const isEmptyObject = (val) => {
    	  // Early return for non-objects or Buffers to prevent RangeError
    	  if (!isObject(val) || isBuffer(val)) {
    	    return false;
    	  }

    	  try {
    	    return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
    	  } catch (e) {
    	    // Fallback for any other objects that might cause RangeError with Object.keys()
    	    return false;
    	  }
    	};

    	/**
    	 * Determine if a value is a Date
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a Date, otherwise false
    	 */
    	const isDate = kindOfTest('Date');

    	/**
    	 * Determine if a value is a File
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a File, otherwise false
    	 */
    	const isFile = kindOfTest('File');

    	/**
    	 * Determine if a value is a React Native Blob
    	 * React Native "blob": an object with a `uri` attribute. Optionally, it can
    	 * also have a `name` and `type` attribute to specify filename and content type
    	 *
    	 * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
    	 *
    	 * @param {*} value The value to test
    	 *
    	 * @returns {boolean} True if value is a React Native Blob, otherwise false
    	 */
    	const isReactNativeBlob = (value) => {
    	  return !!(value && typeof value.uri !== 'undefined');
    	};

    	/**
    	 * Determine if environment is React Native
    	 * ReactNative `FormData` has a non-standard `getParts()` method
    	 *
    	 * @param {*} formData The formData to test
    	 *
    	 * @returns {boolean} True if environment is React Native, otherwise false
    	 */
    	const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';

    	/**
    	 * Determine if a value is a Blob
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a Blob, otherwise false
    	 */
    	const isBlob = kindOfTest('Blob');

    	/**
    	 * Determine if a value is a FileList
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a FileList, otherwise false
    	 */
    	const isFileList = kindOfTest('FileList');

    	/**
    	 * Determine if a value is a Stream
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a Stream, otherwise false
    	 */
    	const isStream = (val) => isObject(val) && isFunction$1(val.pipe);

    	/**
    	 * Determine if a value is a FormData
    	 *
    	 * @param {*} thing The value to test
    	 *
    	 * @returns {boolean} True if value is an FormData, otherwise false
    	 */
    	function getGlobal() {
    	  if (typeof globalThis !== 'undefined') return globalThis;
    	  if (typeof self !== 'undefined') return self;
    	  if (typeof window !== 'undefined') return window;
    	  if (typeof global !== 'undefined') return global;
    	  return {};
    	}

    	const G = getGlobal();
    	const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;

    	const isFormData = (thing) => {
    	  if (!thing) return false;
    	  if (FormDataCtor && thing instanceof FormDataCtor) return true;
    	  // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
    	  const proto = getPrototypeOf(thing);
    	  if (!proto || proto === Object.prototype) return false;
    	  if (!isFunction$1(thing.append)) return false;
    	  const kind = kindOf(thing);
    	  return (
    	    kind === 'formdata' ||
    	    // detect form-data instance
    	    (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
    	  );
    	};

    	/**
    	 * Determine if a value is a URLSearchParams object
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
    	 */
    	const isURLSearchParams = kindOfTest('URLSearchParams');

    	const [isReadableStream, isRequest, isResponse, isHeaders] = [
    	  'ReadableStream',
    	  'Request',
    	  'Response',
    	  'Headers',
    	].map(kindOfTest);

    	/**
    	 * Trim excess whitespace off the beginning and end of a string
    	 *
    	 * @param {String} str The String to trim
    	 *
    	 * @returns {String} The String freed of excess whitespace
    	 */
    	const trim = (str) => {
    	  return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    	};
    	/**
    	 * Iterate over an Array or an Object invoking a function for each item.
    	 *
    	 * If `obj` is an Array callback will be called passing
    	 * the value, index, and complete array for each item.
    	 *
    	 * If 'obj' is an Object callback will be called passing
    	 * the value, key, and complete object for each property.
    	 *
    	 * @param {Object|Array<unknown>} obj The object to iterate
    	 * @param {Function} fn The callback to invoke for each item
    	 *
    	 * @param {Object} [options]
    	 * @param {Boolean} [options.allOwnKeys = false]
    	 * @returns {any}
    	 */
    	function forEach(obj, fn, { allOwnKeys = false } = {}) {
    	  // Don't bother if no value provided
    	  if (obj === null || typeof obj === 'undefined') {
    	    return;
    	  }

    	  let i;
    	  let l;

    	  // Force an array if not already something iterable
    	  if (typeof obj !== 'object') {
    	    /*eslint no-param-reassign:0*/
    	    obj = [obj];
    	  }

    	  if (isArray(obj)) {
    	    // Iterate over array values
    	    for (i = 0, l = obj.length; i < l; i++) {
    	      fn.call(null, obj[i], i, obj);
    	    }
    	  } else {
    	    // Buffer check
    	    if (isBuffer(obj)) {
    	      return;
    	    }

    	    // Iterate over object keys
    	    const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
    	    const len = keys.length;
    	    let key;

    	    for (i = 0; i < len; i++) {
    	      key = keys[i];
    	      fn.call(null, obj[key], key, obj);
    	    }
    	  }
    	}

    	/**
    	 * Finds a key in an object, case-insensitive, returning the actual key name.
    	 * Returns null if the object is a Buffer or if no match is found.
    	 *
    	 * @param {Object} obj - The object to search.
    	 * @param {string} key - The key to find (case-insensitive).
    	 * @returns {?string} The actual key name if found, otherwise null.
    	 */
    	function findKey(obj, key) {
    	  if (isBuffer(obj)) {
    	    return null;
    	  }

    	  key = key.toLowerCase();
    	  const keys = Object.keys(obj);
    	  let i = keys.length;
    	  let _key;
    	  while (i-- > 0) {
    	    _key = keys[i];
    	    if (key === _key.toLowerCase()) {
    	      return _key;
    	    }
    	  }
    	  return null;
    	}

    	const _global = (() => {
    	  /*eslint no-undef:0*/
    	  if (typeof globalThis !== 'undefined') return globalThis;
    	  return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
    	})();

    	const isContextDefined = (context) => !isUndefined(context) && context !== _global;

    	/**
    	 * Accepts varargs expecting each argument to be an object, then
    	 * immutably merges the properties of each object and returns result.
    	 *
    	 * When multiple objects contain the same key the later object in
    	 * the arguments list will take precedence.
    	 *
    	 * Example:
    	 *
    	 * ```js
    	 * const result = merge({foo: 123}, {foo: 456});
    	 * console.log(result.foo); // outputs 456
    	 * ```
    	 *
    	 * @param {Object} obj1 Object to merge
    	 *
    	 * @returns {Object} Result of all merge properties
    	 */
    	function merge(...objs) {
    	  const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
    	  const result = {};
    	  const assignValue = (val, key) => {
    	    // Skip dangerous property names to prevent prototype pollution
    	    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
    	      return;
    	    }

    	    // findKey lowercases the key, so caseless lookup only applies to strings —
    	    // symbol keys are identity-matched.
    	    const targetKey = (caseless && typeof key === 'string' && findKey(result, key)) || key;
    	    // Read via own-prop only — a bare `result[targetKey]` walks the prototype
    	    // chain, so a polluted Object.prototype value could surface here and get
    	    // copied into the merged result.
    	    const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
    	    if (isPlainObject(existing) && isPlainObject(val)) {
    	      result[targetKey] = merge(existing, val);
    	    } else if (isPlainObject(val)) {
    	      result[targetKey] = merge({}, val);
    	    } else if (isArray(val)) {
    	      result[targetKey] = val.slice();
    	    } else if (!skipUndefined || !isUndefined(val)) {
    	      result[targetKey] = val;
    	    }
    	  };

    	  for (let i = 0, l = objs.length; i < l; i++) {
    	    const source = objs[i];
    	    if (!source || isBuffer(source)) {
    	      continue;
    	    }

    	    forEach(source, assignValue);

    	    if (typeof source !== 'object' || isArray(source)) {
    	      continue;
    	    }

    	    const symbols = Object.getOwnPropertySymbols(source);
    	    for (let j = 0; j < symbols.length; j++) {
    	      const symbol = symbols[j];
    	      if (propertyIsEnumerable.call(source, symbol)) {
    	        assignValue(source[symbol], symbol);
    	      }
    	    }
    	  }
    	  return result;
    	}

    	/**
    	 * Extends object a by mutably adding to it the properties of object b.
    	 *
    	 * @param {Object} a The object to be extended
    	 * @param {Object} b The object to copy properties from
    	 * @param {Object} thisArg The object to bind function to
    	 *
    	 * @param {Object} [options]
    	 * @param {Boolean} [options.allOwnKeys]
    	 * @returns {Object} The resulting value of object a
    	 */
    	const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
    	  forEach(
    	    b,
    	    (val, key) => {
    	      if (thisArg && isFunction$1(val)) {
    	        Object.defineProperty(a, key, {
    	          // Null-proto descriptor so a polluted Object.prototype.get cannot
    	          // hijack defineProperty's accessor-vs-data resolution.
    	          __proto__: null,
    	          value: bind(val, thisArg),
    	          writable: true,
    	          enumerable: true,
    	          configurable: true,
    	        });
    	      } else {
    	        Object.defineProperty(a, key, {
    	          __proto__: null,
    	          value: val,
    	          writable: true,
    	          enumerable: true,
    	          configurable: true,
    	        });
    	      }
    	    },
    	    { allOwnKeys }
    	  );
    	  return a;
    	};

    	/**
    	 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
    	 *
    	 * @param {string} content with BOM
    	 *
    	 * @returns {string} content value without BOM
    	 */
    	const stripBOM = (content) => {
    	  if (content.charCodeAt(0) === 0xfeff) {
    	    content = content.slice(1);
    	  }
    	  return content;
    	};

    	/**
    	 * Inherit the prototype methods from one constructor into another
    	 * @param {function} constructor
    	 * @param {function} superConstructor
    	 * @param {object} [props]
    	 * @param {object} [descriptors]
    	 *
    	 * @returns {void}
    	 */
    	const inherits = (constructor, superConstructor, props, descriptors) => {
    	  constructor.prototype = Object.create(superConstructor.prototype, descriptors);
    	  Object.defineProperty(constructor.prototype, 'constructor', {
    	    __proto__: null,
    	    value: constructor,
    	    writable: true,
    	    enumerable: false,
    	    configurable: true,
    	  });
    	  Object.defineProperty(constructor, 'super', {
    	    __proto__: null,
    	    value: superConstructor.prototype,
    	  });
    	  props && Object.assign(constructor.prototype, props);
    	};

    	/**
    	 * Resolve object with deep prototype chain to a flat object
    	 * @param {Object} sourceObj source object
    	 * @param {Object} [destObj]
    	 * @param {Function|Boolean} [filter]
    	 * @param {Function} [propFilter]
    	 *
    	 * @returns {Object}
    	 */
    	const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
    	  let props;
    	  let i;
    	  let prop;
    	  const merged = {};

    	  destObj = destObj || {};
    	  // eslint-disable-next-line no-eq-null,eqeqeq
    	  if (sourceObj == null) return destObj;

    	  do {
    	    props = Object.getOwnPropertyNames(sourceObj);
    	    i = props.length;
    	    while (i-- > 0) {
    	      prop = props[i];
    	      if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
    	        destObj[prop] = sourceObj[prop];
    	        merged[prop] = true;
    	      }
    	    }
    	    sourceObj = filter !== false && getPrototypeOf(sourceObj);
    	  } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);

    	  return destObj;
    	};

    	/**
    	 * Determines whether a string ends with the characters of a specified string
    	 *
    	 * @param {String} str
    	 * @param {String} searchString
    	 * @param {Number} [position= 0]
    	 *
    	 * @returns {boolean}
    	 */
    	const endsWith = (str, searchString, position) => {
    	  str = String(str);
    	  if (position === undefined || position > str.length) {
    	    position = str.length;
    	  }
    	  position -= searchString.length;
    	  const lastIndex = str.indexOf(searchString, position);
    	  return lastIndex !== -1 && lastIndex === position;
    	};

    	/**
    	 * Returns new array from array like object or null if failed
    	 *
    	 * @param {*} [thing]
    	 *
    	 * @returns {?Array}
    	 */
    	const toArray = (thing) => {
    	  if (!thing) return null;
    	  if (isArray(thing)) return thing;
    	  let i = thing.length;
    	  if (!isNumber(i)) return null;
    	  const arr = new Array(i);
    	  while (i-- > 0) {
    	    arr[i] = thing[i];
    	  }
    	  return arr;
    	};

    	/**
    	 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
    	 * thing passed in is an instance of Uint8Array
    	 *
    	 * @param {TypedArray}
    	 *
    	 * @returns {Array}
    	 */
    	// eslint-disable-next-line func-names
    	const isTypedArray = ((TypedArray) => {
    	  // eslint-disable-next-line func-names
    	  return (thing) => {
    	    return TypedArray && thing instanceof TypedArray;
    	  };
    	})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));

    	/**
    	 * For each entry in the object, call the function with the key and value.
    	 *
    	 * @param {Object<any, any>} obj - The object to iterate over.
    	 * @param {Function} fn - The function to call for each entry.
    	 *
    	 * @returns {void}
    	 */
    	const forEachEntry = (obj, fn) => {
    	  const generator = obj && obj[iterator];

    	  const _iterator = generator.call(obj);

    	  let result;

    	  while ((result = _iterator.next()) && !result.done) {
    	    const pair = result.value;
    	    fn.call(obj, pair[0], pair[1]);
    	  }
    	};

    	/**
    	 * It takes a regular expression and a string, and returns an array of all the matches
    	 *
    	 * @param {string} regExp - The regular expression to match against.
    	 * @param {string} str - The string to search.
    	 *
    	 * @returns {Array<boolean>}
    	 */
    	const matchAll = (regExp, str) => {
    	  let matches;
    	  const arr = [];

    	  while ((matches = regExp.exec(str)) !== null) {
    	    arr.push(matches);
    	  }

    	  return arr;
    	};

    	/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
    	const isHTMLForm = kindOfTest('HTMLFormElement');

    	const toCamelCase = (str) => {
    	  return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
    	    return p1.toUpperCase() + p2;
    	  });
    	};

    	const { propertyIsEnumerable } = Object.prototype;

    	/**
    	 * Determine if a value is a RegExp object
    	 *
    	 * @param {*} val The value to test
    	 *
    	 * @returns {boolean} True if value is a RegExp object, otherwise false
    	 */
    	const isRegExp = kindOfTest('RegExp');

    	const reduceDescriptors = (obj, reducer) => {
    	  const descriptors = Object.getOwnPropertyDescriptors(obj);
    	  const reducedDescriptors = {};

    	  forEach(descriptors, (descriptor, name) => {
    	    let ret;
    	    if ((ret = reducer(descriptor, name, obj)) !== false) {
    	      reducedDescriptors[name] = ret || descriptor;
    	    }
    	  });

    	  Object.defineProperties(obj, reducedDescriptors);
    	};

    	/**
    	 * Makes all methods read-only
    	 * @param {Object} obj
    	 */

    	const freezeMethods = (obj) => {
    	  reduceDescriptors(obj, (descriptor, name) => {
    	    // skip restricted props in strict mode
    	    if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
    	      return false;
    	    }

    	    const value = obj[name];

    	    if (!isFunction$1(value)) return;

    	    descriptor.enumerable = false;

    	    if ('writable' in descriptor) {
    	      descriptor.writable = false;
    	      return;
    	    }

    	    if (!descriptor.set) {
    	      descriptor.set = () => {
    	        throw Error("Can not rewrite read-only method '" + name + "'");
    	      };
    	    }
    	  });
    	};

    	/**
    	 * Converts an array or a delimited string into an object set with values as keys and true as values.
    	 * Useful for fast membership checks.
    	 *
    	 * @param {Array|string} arrayOrString - The array or string to convert.
    	 * @param {string} delimiter - The delimiter to use if input is a string.
    	 * @returns {Object} An object with keys from the array or string, values set to true.
    	 */
    	const toObjectSet = (arrayOrString, delimiter) => {
    	  const obj = {};

    	  const define = (arr) => {
    	    arr.forEach((value) => {
    	      obj[value] = true;
    	    });
    	  };

    	  isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));

    	  return obj;
    	};

    	const noop = () => {};

    	const toFiniteNumber = (value, defaultValue) => {
    	  return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
    	};

    	/**
    	 * If the thing is a FormData object, return true, otherwise return false.
    	 *
    	 * @param {unknown} thing - The thing to check.
    	 *
    	 * @returns {boolean}
    	 */
    	function isSpecCompliantForm(thing) {
    	  return !!(
    	    thing &&
    	    isFunction$1(thing.append) &&
    	    thing[toStringTag] === 'FormData' &&
    	    thing[iterator]
    	  );
    	}

    	/**
    	 * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
    	 *
    	 * @param {Object} obj - The object to convert.
    	 * @returns {Object} The JSON-compatible object.
    	 */
    	const toJSONObject = (obj) => {
    	  const visited = new WeakSet();

    	  const visit = (source) => {
    	    if (isObject(source)) {
    	      if (visited.has(source)) {
    	        return;
    	      }

    	      //Buffer check
    	      if (isBuffer(source)) {
    	        return source;
    	      }

    	      if (!('toJSON' in source)) {
    	        // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
    	        visited.add(source);
    	        const target = isArray(source) ? [] : {};

    	        forEach(source, (value, key) => {
    	          const reducedValue = visit(value);
    	          !isUndefined(reducedValue) && (target[key] = reducedValue);
    	        });

    	        visited.delete(source);

    	        return target;
    	      }
    	    }

    	    return source;
    	  };

    	  return visit(obj);
    	};

    	/**
    	 * Determines if a value is an async function.
    	 *
    	 * @param {*} thing - The value to test.
    	 * @returns {boolean} True if value is an async function, otherwise false.
    	 */
    	const isAsyncFn = kindOfTest('AsyncFunction');

    	/**
    	 * Determines if a value is thenable (has then and catch methods).
    	 *
    	 * @param {*} thing - The value to test.
    	 * @returns {boolean} True if value is thenable, otherwise false.
    	 */
    	const isThenable = (thing) =>
    	  thing &&
    	  (isObject(thing) || isFunction$1(thing)) &&
    	  isFunction$1(thing.then) &&
    	  isFunction$1(thing.catch);

    	// original code
    	// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34

    	/**
    	 * Provides a cross-platform setImmediate implementation.
    	 * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
    	 *
    	 * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
    	 * @param {boolean} postMessageSupported - Whether postMessage is supported.
    	 * @returns {Function} A function to schedule a callback asynchronously.
    	 */
    	const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
    	  if (setImmediateSupported) {
    	    return setImmediate;
    	  }

    	  return postMessageSupported
    	    ? ((token, callbacks) => {
    	        _global.addEventListener(
    	          'message',
    	          ({ source, data }) => {
    	            if (source === _global && data === token) {
    	              callbacks.length && callbacks.shift()();
    	            }
    	          },
    	          false
    	        );

    	        return (cb) => {
    	          callbacks.push(cb);
    	          _global.postMessage(token, '*');
    	        };
    	      })(`axios@${Math.random()}`, [])
    	    : (cb) => setTimeout(cb);
    	})(typeof setImmediate === 'function', isFunction$1(_global.postMessage));

    	/**
    	 * Schedules a microtask or asynchronous callback as soon as possible.
    	 * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
    	 *
    	 * @type {Function}
    	 */
    	const asap =
    	  typeof queueMicrotask !== 'undefined'
    	    ? queueMicrotask.bind(_global)
    	    : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;

    	// *********************

    	const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);

    	/**
    	 * Determine if a value is iterable via an iterator that is NOT sourced solely
    	 * from a polluted Object.prototype. Use this instead of `isIterable` whenever
    	 * the iterable comes from untrusted input (e.g. user-supplied header sources),
    	 * so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
    	 * into an attacker-controlled entries iterator.
    	 *
    	 * @param {*} thing The value to test
    	 *
    	 * @returns {boolean} True if value has a non-polluted iterator
    	 */
    	const isSafeIterable = (thing) =>
    	  thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);

    	var utils$1 = {
    	  isArray,
    	  isArrayBuffer,
    	  isBuffer,
    	  isFormData,
    	  isArrayBufferView,
    	  isString,
    	  isNumber,
    	  isBoolean,
    	  isObject,
    	  isPlainObject,
    	  isEmptyObject,
    	  isReadableStream,
    	  isRequest,
    	  isResponse,
    	  isHeaders,
    	  isUndefined,
    	  isDate,
    	  isFile,
    	  isReactNativeBlob,
    	  isReactNative,
    	  isBlob,
    	  isRegExp,
    	  isFunction: isFunction$1,
    	  isStream,
    	  isURLSearchParams,
    	  isTypedArray,
    	  isFileList,
    	  forEach,
    	  merge,
    	  extend,
    	  trim,
    	  stripBOM,
    	  inherits,
    	  toFlatObject,
    	  kindOf,
    	  kindOfTest,
    	  endsWith,
    	  toArray,
    	  forEachEntry,
    	  matchAll,
    	  isHTMLForm,
    	  hasOwnProperty,
    	  hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
    	  hasOwnInPrototypeChain,
    	  getSafeProp,
    	  reduceDescriptors,
    	  freezeMethods,
    	  toObjectSet,
    	  toCamelCase,
    	  noop,
    	  toFiniteNumber,
    	  findKey,
    	  global: _global,
    	  isContextDefined,
    	  isSpecCompliantForm,
    	  toJSONObject,
    	  isAsyncFn,
    	  isThenable,
    	  setImmediate: _setImmediate,
    	  asap,
    	  isIterable,
    	  isSafeIterable,
    	};

    	// RawAxiosHeaders whose duplicates are ignored by node
    	// c.f. https://nodejs.org/api/http.html#http_message_headers
    	const ignoreDuplicateOf = utils$1.toObjectSet([
    	  'age',
    	  'authorization',
    	  'content-length',
    	  'content-type',
    	  'etag',
    	  'expires',
    	  'from',
    	  'host',
    	  'if-modified-since',
    	  'if-unmodified-since',
    	  'last-modified',
    	  'location',
    	  'max-forwards',
    	  'proxy-authorization',
    	  'referer',
    	  'retry-after',
    	  'user-agent',
    	]);

    	/**
    	 * Parse headers into an object
    	 *
    	 * ```
    	 * Date: Wed, 27 Aug 2014 08:58:49 GMT
    	 * Content-Type: application/json
    	 * Connection: keep-alive
    	 * Transfer-Encoding: chunked
    	 * ```
    	 *
    	 * @param {String} rawHeaders Headers needing to be parsed
    	 *
    	 * @returns {Object} Headers parsed into an object
    	 */
    	var parseHeaders = (rawHeaders) => {
    	  const parsed = {};
    	  let key;
    	  let val;
    	  let i;

    	  rawHeaders &&
    	    rawHeaders.split('\n').forEach(function parser(line) {
    	      i = line.indexOf(':');
    	      key = line.substring(0, i).trim().toLowerCase();
    	      val = line.substring(i + 1).trim();

    	      if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
    	        return;
    	      }

    	      if (key === 'set-cookie') {
    	        if (parsed[key]) {
    	          parsed[key].push(val);
    	        } else {
    	          parsed[key] = [val];
    	        }
    	      } else {
    	        parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
    	      }
    	    });

    	  return parsed;
    	};

    	function trimSPorHTAB(str) {
    	  let start = 0;
    	  let end = str.length;

    	  while (start < end) {
    	    const code = str.charCodeAt(start);

    	    if (code !== 0x09 && code !== 0x20) {
    	      break;
    	    }

    	    start += 1;
    	  }

    	  while (end > start) {
    	    const code = str.charCodeAt(end - 1);

    	    if (code !== 0x09 && code !== 0x20) {
    	      break;
    	    }

    	    end -= 1;
    	  }

    	  return start === 0 && end === str.length ? str : str.slice(start, end);
    	}

    	// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
    	// eslint-disable-next-line no-control-regex
    	const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
    	// eslint-disable-next-line no-control-regex
    	const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');

    	function sanitizeValue(value, invalidChars) {
    	  if (utils$1.isArray(value)) {
    	    return value.map((item) => sanitizeValue(item, invalidChars));
    	  }

    	  return trimSPorHTAB(String(value).replace(invalidChars, ''));
    	}

    	const sanitizeHeaderValue = (value) =>
    	  sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);

    	const sanitizeByteStringHeaderValue = (value) =>
    	  sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);

    	function toByteStringHeaderObject(headers) {
    	  const byteStringHeaders = Object.create(null);

    	  utils$1.forEach(headers.toJSON(), (value, header) => {
    	    byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
    	  });

    	  return byteStringHeaders;
    	}

    	const $internals = Symbol('internals');

    	function normalizeHeader(header) {
    	  return header && String(header).trim().toLowerCase();
    	}

    	function normalizeValue(value) {
    	  if (value === false || value == null) {
    	    return value;
    	  }

    	  return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
    	}

    	function parseTokens(str) {
    	  const tokens = Object.create(null);
    	  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
    	  let match;

    	  while ((match = tokensRE.exec(str))) {
    	    tokens[match[1]] = match[2];
    	  }

    	  return tokens;
    	}

    	const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());

    	function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
    	  if (utils$1.isFunction(filter)) {
    	    return filter.call(this, value, header);
    	  }

    	  if (isHeaderNameFilter) {
    	    value = header;
    	  }

    	  if (!utils$1.isString(value)) return;

    	  if (utils$1.isString(filter)) {
    	    return value.indexOf(filter) !== -1;
    	  }

    	  if (utils$1.isRegExp(filter)) {
    	    return filter.test(value);
    	  }
    	}

    	function formatHeader(header) {
    	  return header
    	    .trim()
    	    .toLowerCase()
    	    .replace(/([a-z\d])(\w*)/g, (w, char, str) => {
    	      return char.toUpperCase() + str;
    	    });
    	}

    	function buildAccessors(obj, header) {
    	  const accessorName = utils$1.toCamelCase(' ' + header);

    	  ['get', 'set', 'has'].forEach((methodName) => {
    	    Object.defineProperty(obj, methodName + accessorName, {
    	      // Null-proto descriptor so a polluted Object.prototype.get cannot turn
    	      // this data descriptor into an accessor descriptor on the way in.
    	      __proto__: null,
    	      value: function (arg1, arg2, arg3) {
    	        return this[methodName].call(this, header, arg1, arg2, arg3);
    	      },
    	      configurable: true,
    	    });
    	  });
    	}

    	class AxiosHeaders {
    	  constructor(headers) {
    	    headers && this.set(headers);
    	  }

    	  set(header, valueOrRewrite, rewrite) {
    	    const self = this;

    	    function setHeader(_value, _header, _rewrite) {
    	      const lHeader = normalizeHeader(_header);

    	      if (!lHeader) {
    	        return;
    	      }

    	      const key = utils$1.findKey(self, lHeader);

    	      if (
    	        !key ||
    	        self[key] === undefined ||
    	        _rewrite === true ||
    	        (_rewrite === undefined && self[key] !== false)
    	      ) {
    	        self[key || _header] = normalizeValue(_value);
    	      }
    	    }

    	    const setHeaders = (headers, _rewrite) =>
    	      utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));

    	    if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
    	      setHeaders(header, valueOrRewrite);
    	    } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
    	      setHeaders(parseHeaders(header), valueOrRewrite);
    	    } else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
    	      let obj = Object.create(null),
    	        dest,
    	        key;
    	      for (const entry of header) {
    	        if (!utils$1.isArray(entry)) {
    	          throw new TypeError('Object iterator must return a key-value pair');
    	        }

    	        key = entry[0];

    	        if (utils$1.hasOwnProp(obj, key)) {
    	          dest = obj[key];
    	          obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
    	        } else {
    	          obj[key] = entry[1];
    	        }
    	      }

    	      setHeaders(obj, valueOrRewrite);
    	    } else {
    	      header != null && setHeader(valueOrRewrite, header, rewrite);
    	    }

    	    return this;
    	  }

    	  get(header, parser) {
    	    header = normalizeHeader(header);

    	    if (header) {
    	      const key = utils$1.findKey(this, header);

    	      if (key) {
    	        const value = this[key];

    	        if (!parser) {
    	          return value;
    	        }

    	        if (parser === true) {
    	          return parseTokens(value);
    	        }

    	        if (utils$1.isFunction(parser)) {
    	          return parser.call(this, value, key);
    	        }

    	        if (utils$1.isRegExp(parser)) {
    	          return parser.exec(value);
    	        }

    	        throw new TypeError('parser must be boolean|regexp|function');
    	      }
    	    }
    	  }

    	  has(header, matcher) {
    	    header = normalizeHeader(header);

    	    if (header) {
    	      const key = utils$1.findKey(this, header);

    	      return !!(
    	        key &&
    	        this[key] !== undefined &&
    	        (!matcher || matchHeaderValue(this, this[key], key, matcher))
    	      );
    	    }

    	    return false;
    	  }

    	  delete(header, matcher) {
    	    const self = this;
    	    let deleted = false;

    	    function deleteHeader(_header) {
    	      _header = normalizeHeader(_header);

    	      if (_header) {
    	        const key = utils$1.findKey(self, _header);

    	        if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
    	          delete self[key];

    	          deleted = true;
    	        }
    	      }
    	    }

    	    if (utils$1.isArray(header)) {
    	      header.forEach(deleteHeader);
    	    } else {
    	      deleteHeader(header);
    	    }

    	    return deleted;
    	  }

    	  clear(matcher) {
    	    const keys = Object.keys(this);
    	    let i = keys.length;
    	    let deleted = false;

    	    while (i--) {
    	      const key = keys[i];
    	      if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
    	        delete this[key];
    	        deleted = true;
    	      }
    	    }

    	    return deleted;
    	  }

    	  normalize(format) {
    	    const self = this;
    	    const headers = {};

    	    utils$1.forEach(this, (value, header) => {
    	      const key = utils$1.findKey(headers, header);

    	      if (key) {
    	        self[key] = normalizeValue(value);
    	        delete self[header];
    	        return;
    	      }

    	      const normalized = format ? formatHeader(header) : String(header).trim();

    	      if (normalized !== header) {
    	        delete self[header];
    	      }

    	      self[normalized] = normalizeValue(value);

    	      headers[normalized] = true;
    	    });

    	    return this;
    	  }

    	  concat(...targets) {
    	    return this.constructor.concat(this, ...targets);
    	  }

    	  toJSON(asStrings) {
    	    const obj = Object.create(null);

    	    utils$1.forEach(this, (value, header) => {
    	      value != null &&
    	        value !== false &&
    	        (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
    	    });

    	    return obj;
    	  }

    	  [Symbol.iterator]() {
    	    return Object.entries(this.toJSON())[Symbol.iterator]();
    	  }

    	  toString() {
    	    return Object.entries(this.toJSON())
    	      .map(([header, value]) => header + ': ' + value)
    	      .join('\n');
    	  }

    	  getSetCookie() {
    	    return this.get('set-cookie') || [];
    	  }

    	  get [Symbol.toStringTag]() {
    	    return 'AxiosHeaders';
    	  }

    	  static from(thing) {
    	    return thing instanceof this ? thing : new this(thing);
    	  }

    	  static concat(first, ...targets) {
    	    const computed = new this(first);

    	    targets.forEach((target) => computed.set(target));

    	    return computed;
    	  }

    	  static accessor(header) {
    	    const internals =
    	      (this[$internals] =
    	      this[$internals] =
    	        {
    	          accessors: {},
    	        });

    	    const accessors = internals.accessors;
    	    const prototype = this.prototype;

    	    function defineAccessor(_header) {
    	      const lHeader = normalizeHeader(_header);

    	      if (!accessors[lHeader]) {
    	        buildAccessors(prototype, _header);
    	        accessors[lHeader] = true;
    	      }
    	    }

    	    utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);

    	    return this;
    	  }
    	}

    	AxiosHeaders.accessor([
    	  'Content-Type',
    	  'Content-Length',
    	  'Accept',
    	  'Accept-Encoding',
    	  'User-Agent',
    	  'Authorization',
    	]);

    	// reserved names hotfix
    	utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
    	  let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
    	  return {
    	    get: () => value,
    	    set(headerValue) {
    	      this[mapped] = headerValue;
    	    },
    	  };
    	});

    	utils$1.freezeMethods(AxiosHeaders);

    	const REDACTED = '[REDACTED ****]';

    	function hasOwnOrPrototypeToJSON(source) {
    	  if (utils$1.hasOwnProp(source, 'toJSON')) {
    	    return true;
    	  }

    	  let prototype = Object.getPrototypeOf(source);

    	  while (prototype && prototype !== Object.prototype) {
    	    if (utils$1.hasOwnProp(prototype, 'toJSON')) {
    	      return true;
    	    }

    	    prototype = Object.getPrototypeOf(prototype);
    	  }

    	  return false;
    	}

    	// Build a plain-object snapshot of `config` and replace the value of any key
    	// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
    	// and AxiosHeaders, and short-circuits on circular references.
    	function redactConfig(config, redactKeys) {
    	  const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase()));
    	  const seen = [];

    	  const visit = (source) => {
    	    if (source === null || typeof source !== 'object') return source;
    	    if (utils$1.isBuffer(source)) return source;
    	    if (seen.indexOf(source) !== -1) return undefined;

    	    if (source instanceof AxiosHeaders) {
    	      source = source.toJSON();
    	    }

    	    seen.push(source);

    	    let result;
    	    if (utils$1.isArray(source)) {
    	      result = [];
    	      source.forEach((v, i) => {
    	        const reducedValue = visit(v);
    	        if (!utils$1.isUndefined(reducedValue)) {
    	          result[i] = reducedValue;
    	        }
    	      });
    	    } else {
    	      if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
    	        seen.pop();
    	        return source;
    	      }

    	      result = Object.create(null);
    	      for (const [key, value] of Object.entries(source)) {
    	        const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
    	        if (!utils$1.isUndefined(reducedValue)) {
    	          result[key] = reducedValue;
    	        }
    	      }
    	    }

    	    seen.pop();
    	    return result;
    	  };

    	  return visit(config);
    	}

    	class AxiosError extends Error {
    	  static from(error, code, config, request, response, customProps) {
    	    const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
    	    axiosError.cause = error;
    	    axiosError.name = error.name;

    	    // Preserve status from the original error if not already set from response
    	    if (error.status != null && axiosError.status == null) {
    	      axiosError.status = error.status;
    	    }

    	    customProps && Object.assign(axiosError, customProps);
    	    return axiosError;
    	  }

    	  /**
    	   * Create an Error with the specified message, config, error code, request and response.
    	   *
    	   * @param {string} message The error message.
    	   * @param {string} [code] The error code (for example, 'ECONNABORTED').
    	   * @param {Object} [config] The config.
    	   * @param {Object} [request] The request.
    	   * @param {Object} [response] The response.
    	   *
    	   * @returns {Error} The created error.
    	   */
    	  constructor(message, code, config, request, response) {
    	    super(message);

    	    // Make message enumerable to maintain backward compatibility
    	    // The native Error constructor sets message as non-enumerable,
    	    // but axios < v1.13.3 had it as enumerable
    	    Object.defineProperty(this, 'message', {
    	      // Null-proto descriptor so a polluted Object.prototype.get cannot turn
    	      // this data descriptor into an accessor descriptor on the way in.
    	      __proto__: null,
    	      value: message,
    	      enumerable: true,
    	      writable: true,
    	      configurable: true,
    	    });

    	    this.name = 'AxiosError';
    	    this.isAxiosError = true;
    	    code && (this.code = code);
    	    config && (this.config = config);
    	    request && (this.request = request);
    	    if (response) {
    	      this.response = response;
    	      this.status = response.status;
    	    }
    	  }

    	  toJSON() {
    	    // Opt-in redaction: when the request config carries a `redact` array, the
    	    // value of any matching key (case-insensitive, at any depth) is replaced
    	    // with REDACTED in the serialized snapshot. Undefined or empty leaves the
    	    // existing serialization behavior unchanged.
    	    const config = this.config;
    	    const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
    	    const serializedConfig =
    	      utils$1.isArray(redactKeys) && redactKeys.length > 0
    	        ? redactConfig(config, redactKeys)
    	        : utils$1.toJSONObject(config);

    	    return {
    	      // Standard
    	      message: this.message,
    	      name: this.name,
    	      // Microsoft
    	      description: this.description,
    	      number: this.number,
    	      // Mozilla
    	      fileName: this.fileName,
    	      lineNumber: this.lineNumber,
    	      columnNumber: this.columnNumber,
    	      stack: this.stack,
    	      // Axios
    	      config: serializedConfig,
    	      code: this.code,
    	      status: this.status,
    	    };
    	  }
    	}

    	// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
    	AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
    	AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
    	AxiosError.ECONNABORTED = 'ECONNABORTED';
    	AxiosError.ETIMEDOUT = 'ETIMEDOUT';
    	AxiosError.ECONNREFUSED = 'ECONNREFUSED';
    	AxiosError.ERR_NETWORK = 'ERR_NETWORK';
    	AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
    	AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
    	AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
    	AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
    	AxiosError.ERR_CANCELED = 'ERR_CANCELED';
    	AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
    	AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
    	AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';

    	// eslint-disable-next-line strict
    	var httpAdapter = null;

    	// Default nesting limit shared with the inverse transform (formDataToJSON) so
    	// the FormData <-> JSON round-trip stays symmetric.
    	const DEFAULT_FORM_DATA_MAX_DEPTH = 100;

    	/**
    	 * Determines if the given thing is a array or js object.
    	 *
    	 * @param {string} thing - The object or array to be visited.
    	 *
    	 * @returns {boolean}
    	 */
    	function isVisitable(thing) {
    	  return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
    	}

    	/**
    	 * It removes the brackets from the end of a string
    	 *
    	 * @param {string} key - The key of the parameter.
    	 *
    	 * @returns {string} the key without the brackets.
    	 */
    	function removeBrackets(key) {
    	  return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
    	}

    	/**
    	 * It takes a path, a key, and a boolean, and returns a string
    	 *
    	 * @param {string} path - The path to the current key.
    	 * @param {string} key - The key of the current object being iterated over.
    	 * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
    	 *
    	 * @returns {string} The path to the current key.
    	 */
    	function renderKey(path, key, dots) {
    	  if (!path) return key;
    	  return path
    	    .concat(key)
    	    .map(function each(token, i) {
    	      // eslint-disable-next-line no-param-reassign
    	      token = removeBrackets(token);
    	      return !dots && i ? '[' + token + ']' : token;
    	    })
    	    .join(dots ? '.' : '');
    	}

    	/**
    	 * If the array is an array and none of its elements are visitable, then it's a flat array.
    	 *
    	 * @param {Array<any>} arr - The array to check
    	 *
    	 * @returns {boolean}
    	 */
    	function isFlatArray(arr) {
    	  return utils$1.isArray(arr) && !arr.some(isVisitable);
    	}

    	const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
    	  return /^is[A-Z]/.test(prop);
    	});

    	/**
    	 * Convert a data object to FormData
    	 *
    	 * @param {Object} obj
    	 * @param {?Object} [formData]
    	 * @param {?Object} [options]
    	 * @param {Function} [options.visitor]
    	 * @param {Boolean} [options.metaTokens = true]
    	 * @param {Boolean} [options.dots = false]
    	 * @param {?Boolean} [options.indexes = false]
    	 *
    	 * @returns {Object}
    	 **/

    	/**
    	 * It converts an object into a FormData object
    	 *
    	 * @param {Object<any, any>} obj - The object to convert to form data.
    	 * @param {string} formData - The FormData object to append to.
    	 * @param {Object<string, any>} options
    	 *
    	 * @returns
    	 */
    	function toFormData(obj, formData, options) {
    	  if (!utils$1.isObject(obj)) {
    	    throw new TypeError('target must be an object');
    	  }

    	  // eslint-disable-next-line no-param-reassign
    	  formData = formData || new (FormData)();

    	  // eslint-disable-next-line no-param-reassign
    	  options = utils$1.toFlatObject(
    	    options,
    	    {
    	      metaTokens: true,
    	      dots: false,
    	      indexes: false,
    	    },
    	    false,
    	    function defined(option, source) {
    	      // eslint-disable-next-line no-eq-null,eqeqeq
    	      return !utils$1.isUndefined(source[option]);
    	    }
    	  );

    	  const metaTokens = options.metaTokens;
    	  // eslint-disable-next-line no-use-before-define
    	  const visitor = options.visitor || defaultVisitor;
    	  const dots = options.dots;
    	  const indexes = options.indexes;
    	  const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
    	  const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
    	  const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
    	  const stack = [];

    	  if (!utils$1.isFunction(visitor)) {
    	    throw new TypeError('visitor must be a function');
    	  }

    	  function convertValue(value) {
    	    if (value === null) return '';

    	    if (utils$1.isDate(value)) {
    	      return value.toISOString();
    	    }

    	    if (utils$1.isBoolean(value)) {
    	      return value.toString();
    	    }

    	    if (!useBlob && utils$1.isBlob(value)) {
    	      throw new AxiosError('Blob is not supported. Use a Buffer instead.');
    	    }

    	    if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
    	      return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
    	    }

    	    return value;
    	  }

    	  function throwIfMaxDepthExceeded(depth) {
    	    if (depth > maxDepth) {
    	      throw new AxiosError(
    	        'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth,
    	        AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
    	      );
    	    }
    	  }

    	  function stringifyWithDepthLimit(value, depth) {
    	    if (maxDepth === Infinity) {
    	      return JSON.stringify(value);
    	    }

    	    const ancestors = [];

    	    return JSON.stringify(value, function limitDepth(_key, currentValue) {
    	      if (!utils$1.isObject(currentValue)) {
    	        return currentValue;
    	      }

    	      while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
    	        ancestors.pop();
    	      }

    	      ancestors.push(currentValue);
    	      throwIfMaxDepthExceeded(depth + ancestors.length - 1);

    	      return currentValue;
    	    });
    	  }

    	  /**
    	   * Default visitor.
    	   *
    	   * @param {*} value
    	   * @param {String|Number} key
    	   * @param {Array<String|Number>} path
    	   * @this {FormData}
    	   *
    	   * @returns {boolean} return true to visit the each prop of the value recursively
    	   */
    	  function defaultVisitor(value, key, path) {
    	    let arr = value;

    	    if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
    	      formData.append(renderKey(path, key, dots), convertValue(value));
    	      return false;
    	    }

    	    if (value && !path && typeof value === 'object') {
    	      if (utils$1.endsWith(key, '{}')) {
    	        // eslint-disable-next-line no-param-reassign
    	        key = metaTokens ? key : key.slice(0, -2);
    	        // eslint-disable-next-line no-param-reassign
    	        value = stringifyWithDepthLimit(value, 1);
    	      } else if (
    	        (utils$1.isArray(value) && isFlatArray(value)) ||
    	        ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)))
    	      ) {
    	        // eslint-disable-next-line no-param-reassign
    	        key = removeBrackets(key);

    	        arr.forEach(function each(el, index) {
    	          !(utils$1.isUndefined(el) || el === null) &&
    	            formData.append(
    	              // eslint-disable-next-line no-nested-ternary
    	              indexes === true
    	                ? renderKey([key], index, dots)
    	                : indexes === null
    	                  ? key
    	                  : key + '[]',
    	              convertValue(el)
    	            );
    	        });
    	        return false;
    	      }
    	    }

    	    if (isVisitable(value)) {
    	      return true;
    	    }

    	    formData.append(renderKey(path, key, dots), convertValue(value));

    	    return false;
    	  }

    	  const exposedHelpers = Object.assign(predicates, {
    	    defaultVisitor,
    	    convertValue,
    	    isVisitable,
    	  });

    	  function build(value, path, depth = 0) {
    	    if (utils$1.isUndefined(value)) return;

    	    throwIfMaxDepthExceeded(depth);

    	    if (stack.indexOf(value) !== -1) {
    	      throw new Error('Circular reference detected in ' + path.join('.'));
    	    }

    	    stack.push(value);

    	    utils$1.forEach(value, function each(el, key) {
    	      const result =
    	        !(utils$1.isUndefined(el) || el === null) &&
    	        visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);

    	      if (result === true) {
    	        build(el, path ? path.concat(key) : [key], depth + 1);
    	      }
    	    });

    	    stack.pop();
    	  }

    	  if (!utils$1.isObject(obj)) {
    	    throw new TypeError('data must be an object');
    	  }

    	  build(obj);

    	  return formData;
    	}

    	/**
    	 * It encodes a string by replacing all characters that are not in the unreserved set with
    	 * their percent-encoded equivalents
    	 *
    	 * @param {string} str - The string to encode.
    	 *
    	 * @returns {string} The encoded string.
    	 */
    	function encode$1(str) {
    	  const charMap = {
    	    '!': '%21',
    	    "'": '%27',
    	    '(': '%28',
    	    ')': '%29',
    	    '~': '%7E',
    	    '%20': '+',
    	  };
    	  return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
    	    return charMap[match];
    	  });
    	}

    	/**
    	 * It takes a params object and converts it to a FormData object
    	 *
    	 * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
    	 * @param {Object<string, any>} options - The options object passed to the Axios constructor.
    	 *
    	 * @returns {void}
    	 */
    	function AxiosURLSearchParams(params, options) {
    	  this._pairs = [];

    	  params && toFormData(params, this, options);
    	}

    	const prototype = AxiosURLSearchParams.prototype;

    	prototype.append = function append(name, value) {
    	  this._pairs.push([name, value]);
    	};

    	prototype.toString = function toString(encoder) {
    	  const _encode = encoder
    	    ? function (value) {
    	        return encoder.call(this, value, encode$1);
    	      }
    	    : encode$1;

    	  return this._pairs
    	    .map(function each(pair) {
    	      return _encode(pair[0]) + '=' + _encode(pair[1]);
    	    }, '')
    	    .join('&');
    	};

    	/**
    	 * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
    	 * their plain counterparts (`:`, `$`, `,`, `+`).
    	 *
    	 * @param {string} val The value to be encoded.
    	 *
    	 * @returns {string} The encoded value.
    	 */
    	function encode(val) {
    	  return encodeURIComponent(val)
    	    .replace(/%3A/gi, ':')
    	    .replace(/%24/g, '$')
    	    .replace(/%2C/gi, ',')
    	    .replace(/%20/g, '+');
    	}

    	/**
    	 * Build a URL by appending params to the end
    	 *
    	 * @param {string} url The base of the url (e.g., http://www.google.com)
    	 * @param {object} [params] The params to be appended
    	 * @param {?(object|Function)} options
    	 *
    	 * @returns {string} The formatted url
    	 */
    	function buildURL(url, params, options) {
    	  if (!params) {
    	    return url;
    	  }

    	  const _options = utils$1.isFunction(options)
    	    ? {
    	        serialize: options,
    	      }
    	    : options;

    	  // Read serializer options pollution-safely: own properties and methods on a
    	  // class/template prototype are honored, but values injected onto a polluted
    	  // Object.prototype are ignored.
    	  const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
    	  const serializeFn = utils$1.getSafeProp(_options, 'serialize');

    	  let serializedParams;

    	  if (serializeFn) {
    	    serializedParams = serializeFn(params, _options);
    	  } else {
    	    serializedParams = utils$1.isURLSearchParams(params)
    	      ? params.toString()
    	      : new AxiosURLSearchParams(params, _options).toString(_encode);
    	  }

    	  if (serializedParams) {
    	    const hashmarkIndex = url.indexOf('#');

    	    if (hashmarkIndex !== -1) {
    	      url = url.slice(0, hashmarkIndex);
    	    }
    	    url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
    	  }

    	  return url;
    	}

    	class InterceptorManager {
    	  constructor() {
    	    this.handlers = [];
    	  }

    	  /**
    	   * Add a new interceptor to the stack
    	   *
    	   * @param {Function} fulfilled The function to handle `then` for a `Promise`
    	   * @param {Function} rejected The function to handle `reject` for a `Promise`
    	   * @param {Object} options The options for the interceptor, synchronous and runWhen
    	   *
    	   * @return {Number} An ID used to remove interceptor later
    	   */
    	  use(fulfilled, rejected, options) {
    	    this.handlers.push({
    	      fulfilled,
    	      rejected,
    	      synchronous: options ? options.synchronous : false,
    	      runWhen: options ? options.runWhen : null,
    	    });
    	    return this.handlers.length - 1;
    	  }

    	  /**
    	   * Remove an interceptor from the stack
    	   *
    	   * @param {Number} id The ID that was returned by `use`
    	   *
    	   * @returns {void}
    	   */
    	  eject(id) {
    	    if (this.handlers[id]) {
    	      this.handlers[id] = null;
    	    }
    	  }

    	  /**
    	   * Clear all interceptors from the stack
    	   *
    	   * @returns {void}
    	   */
    	  clear() {
    	    if (this.handlers) {
    	      this.handlers = [];
    	    }
    	  }

    	  /**
    	   * Iterate over all the registered interceptors
    	   *
    	   * This method is particularly useful for skipping over any
    	   * interceptors that may have become `null` calling `eject`.
    	   *
    	   * @param {Function} fn The function to call for each interceptor
    	   *
    	   * @returns {void}
    	   */
    	  forEach(fn) {
    	    utils$1.forEach(this.handlers, function forEachHandler(h) {
    	      if (h !== null) {
    	        fn(h);
    	      }
    	    });
    	  }
    	}

    	var transitionalDefaults = {
    	  silentJSONParsing: true,
    	  forcedJSONParsing: true,
    	  clarifyTimeoutError: false,
    	  legacyInterceptorReqResOrdering: true,
    	  advertiseZstdAcceptEncoding: false,
    	  validateStatusUndefinedResolves: true,
    	};

    	var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;

    	var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;

    	var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;

    	var platform$1 = {
    	  isBrowser: true,
    	  classes: {
    	    URLSearchParams: URLSearchParams$1,
    	    FormData: FormData$1,
    	    Blob: Blob$1,
    	  },
    	  protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],
    	};

    	const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';

    	const _navigator = (typeof navigator === 'object' && navigator) || undefined;

    	/**
    	 * Determine if we're running in a standard browser environment
    	 *
    	 * This allows axios to run in a web worker, and react-native.
    	 * Both environments support XMLHttpRequest, but not fully standard globals.
    	 *
    	 * web workers:
    	 *  typeof window -> undefined
    	 *  typeof document -> undefined
    	 *
    	 * react-native:
    	 *  navigator.product -> 'ReactNative'
    	 * nativescript
    	 *  navigator.product -> 'NativeScript' or 'NS'
    	 *
    	 * @returns {boolean}
    	 */
    	const hasStandardBrowserEnv =
    	  hasBrowserEnv &&
    	  (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);

    	/**
    	 * Determine if we're running in a standard browser webWorker environment
    	 *
    	 * Although the `isStandardBrowserEnv` method indicates that
    	 * `allows axios to run in a web worker`, the WebWorker will still be
    	 * filtered out due to its judgment standard
    	 * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
    	 * This leads to a problem when axios post `FormData` in webWorker
    	 */
    	const hasStandardBrowserWebWorkerEnv = (() => {
    	  return (
    	    typeof WorkerGlobalScope !== 'undefined' &&
    	    // eslint-disable-next-line no-undef
    	    self instanceof WorkerGlobalScope &&
    	    typeof self.importScripts === 'function'
    	  );
    	})();

    	const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';

    	var utils = /*#__PURE__*/Object.freeze({
    	  __proto__: null,
    	  hasBrowserEnv: hasBrowserEnv,
    	  hasStandardBrowserEnv: hasStandardBrowserEnv,
    	  hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
    	  navigator: _navigator,
    	  origin: origin
    	});

    	var platform = {
    	  ...utils,
    	  ...platform$1,
    	};

    	function toURLEncodedForm(data, options) {
    	  return toFormData(data, new platform.classes.URLSearchParams(), {
    	    visitor: function (value, key, path, helpers) {
    	      if (platform.isNode && utils$1.isBuffer(value)) {
    	        this.append(key, value.toString('base64'));
    	        return false;
    	      }

    	      return helpers.defaultVisitor.apply(this, arguments);
    	    },
    	    ...options,
    	  });
    	}

    	const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;

    	function throwIfDepthExceeded(index) {
    	  if (index > MAX_DEPTH) {
    	    throw new AxiosError(
    	      'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
    	      AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
    	    );
    	  }
    	}

    	/**
    	 * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
    	 *
    	 * @param {string} name - The name of the property to get.
    	 *
    	 * @returns An array of strings.
    	 */
    	function parsePropPath(name) {
    	  // foo[x][y][z]
    	  // foo.x.y.z
    	  // foo-x-y-z
    	  // foo x y z
    	  const path = [];
    	  const pattern = /\w+|\[(\w*)]/g;
    	  let match;

    	  while ((match = pattern.exec(name)) !== null) {
    	    throwIfDepthExceeded(path.length);
    	    path.push(match[0] === '[]' ? '' : match[1] || match[0]);
    	  }

    	  return path;
    	}

    	/**
    	 * Convert an array to an object.
    	 *
    	 * @param {Array<any>} arr - The array to convert to an object.
    	 *
    	 * @returns An object with the same keys and values as the array.
    	 */
    	function arrayToObject(arr) {
    	  const obj = {};
    	  const keys = Object.keys(arr);
    	  let i;
    	  const len = keys.length;
    	  let key;
    	  for (i = 0; i < len; i++) {
    	    key = keys[i];
    	    obj[key] = arr[key];
    	  }
    	  return obj;
    	}

    	/**
    	 * It takes a FormData object and returns a JavaScript object
    	 *
    	 * @param {string} formData The FormData object to convert to JSON.
    	 *
    	 * @returns {Object<string, any> | null} The converted object.
    	 */
    	function formDataToJSON(formData) {
    	  function buildPath(path, value, target, index) {
    	    throwIfDepthExceeded(index);

    	    let name = path[index++];

    	    if (name === '__proto__') return true;

    	    const isNumericKey = Number.isFinite(+name);
    	    const isLast = index >= path.length;
    	    name = !name && utils$1.isArray(target) ? target.length : name;

    	    if (isLast) {
    	      if (utils$1.hasOwnProp(target, name)) {
    	        target[name] = utils$1.isArray(target[name])
    	          ? target[name].concat(value)
    	          : [target[name], value];
    	      } else {
    	        target[name] = value;
    	      }

    	      return !isNumericKey;
    	    }

    	    if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
    	      target[name] = [];
    	    }

    	    const result = buildPath(path, value, target[name], index);

    	    if (result && utils$1.isArray(target[name])) {
    	      target[name] = arrayToObject(target[name]);
    	    }

    	    return !isNumericKey;
    	  }

    	  if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
    	    const obj = {};

    	    utils$1.forEachEntry(formData, (name, value) => {
    	      buildPath(parsePropPath(name), value, obj, 0);
    	    });

    	    return obj;
    	  }

    	  return null;
    	}

    	const own = (obj, key) => (obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined);

    	/**
    	 * It takes a string, tries to parse it, and if it fails, it returns the stringified version
    	 * of the input
    	 *
    	 * @param {any} rawValue - The value to be stringified.
    	 * @param {Function} parser - A function that parses a string into a JavaScript object.
    	 * @param {Function} encoder - A function that takes a value and returns a string.
    	 *
    	 * @returns {string} A stringified version of the rawValue.
    	 */
    	function stringifySafely(rawValue, parser, encoder) {
    	  if (utils$1.isString(rawValue)) {
    	    try {
    	      (parser || JSON.parse)(rawValue);
    	      return utils$1.trim(rawValue);
    	    } catch (e) {
    	      if (e.name !== 'SyntaxError') {
    	        throw e;
    	      }
    	    }
    	  }

    	  return (encoder || JSON.stringify)(rawValue);
    	}

    	const defaults = {
    	  transitional: transitionalDefaults,

    	  adapter: ['xhr', 'http', 'fetch'],

    	  transformRequest: [
    	    function transformRequest(data, headers) {
    	      const contentType = headers.getContentType() || '';
    	      const hasJSONContentType = contentType.indexOf('application/json') > -1;
    	      const isObjectPayload = utils$1.isObject(data);

    	      if (isObjectPayload && utils$1.isHTMLForm(data)) {
    	        data = new FormData(data);
    	      }

    	      const isFormData = utils$1.isFormData(data);

    	      if (isFormData) {
    	        return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
    	      }

    	      if (
    	        utils$1.isArrayBuffer(data) ||
    	        utils$1.isBuffer(data) ||
    	        utils$1.isStream(data) ||
    	        utils$1.isFile(data) ||
    	        utils$1.isBlob(data) ||
    	        utils$1.isReadableStream(data)
    	      ) {
    	        return data;
    	      }
    	      if (utils$1.isArrayBufferView(data)) {
    	        return data.buffer;
    	      }
    	      if (utils$1.isURLSearchParams(data)) {
    	        headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
    	        return data.toString();
    	      }

    	      let isFileList;

    	      if (isObjectPayload) {
    	        const formSerializer = own(this, 'formSerializer');
    	        if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
    	          return toURLEncodedForm(data, formSerializer).toString();
    	        }

    	        if (
    	          (isFileList = utils$1.isFileList(data)) ||
    	          contentType.indexOf('multipart/form-data') > -1
    	        ) {
    	          const env = own(this, 'env');
    	          const _FormData = env && env.FormData;

    	          return toFormData(
    	            isFileList ? { 'files[]': data } : data,
    	            _FormData && new _FormData(),
    	            formSerializer
    	          );
    	        }
    	      }

    	      if (isObjectPayload || hasJSONContentType) {
    	        headers.setContentType('application/json', false);
    	        return stringifySafely(data);
    	      }

    	      return data;
    	    },
    	  ],

    	  transformResponse: [
    	    function transformResponse(data) {
    	      const transitional = own(this, 'transitional') || defaults.transitional;
    	      const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
    	      const responseType = own(this, 'responseType');
    	      const JSONRequested = responseType === 'json';

    	      if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
    	        return data;
    	      }

    	      if (
    	        data &&
    	        utils$1.isString(data) &&
    	        ((forcedJSONParsing && !responseType) || JSONRequested)
    	      ) {
    	        const silentJSONParsing = transitional && transitional.silentJSONParsing;
    	        const strictJSONParsing = !silentJSONParsing && JSONRequested;

    	        try {
    	          return JSON.parse(data, own(this, 'parseReviver'));
    	        } catch (e) {
    	          if (strictJSONParsing) {
    	            if (e.name === 'SyntaxError') {
    	              throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
    	            }
    	            throw e;
    	          }
    	        }
    	      }

    	      return data;
    	    },
    	  ],

    	  /**
    	   * A timeout in milliseconds to abort a request. If set to 0 (default) a
    	   * timeout is not created.
    	   */
    	  timeout: 0,

    	  xsrfCookieName: 'XSRF-TOKEN',
    	  xsrfHeaderName: 'X-XSRF-TOKEN',

    	  maxContentLength: -1,
    	  maxBodyLength: -1,

    	  env: {
    	    FormData: platform.classes.FormData,
    	    Blob: platform.classes.Blob,
    	  },

    	  validateStatus: function validateStatus(status) {
    	    return status >= 200 && status < 300;
    	  },

    	  headers: {
    	    common: {
    	      Accept: 'application/json, text/plain, */*',
    	      'Content-Type': undefined,
    	    },
    	  },
    	};

    	utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => {
    	  defaults.headers[method] = {};
    	});

    	/**
    	 * Transform the data for a request or a response
    	 *
    	 * @param {Array|Function} fns A single function or Array of functions
    	 * @param {?Object} response The response object
    	 *
    	 * @returns {*} The resulting transformed data
    	 */
    	function transformData(fns, response) {
    	  const config = this || defaults;
    	  const context = response || config;
    	  const headers = AxiosHeaders.from(context.headers);
    	  let data = context.data;

    	  utils$1.forEach(fns, function transform(fn) {
    	    data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
    	  });

    	  headers.normalize();

    	  return data;
    	}

    	function isCancel(value) {
    	  return !!(value && value.__CANCEL__);
    	}

    	class CanceledError extends AxiosError {
    	  /**
    	   * A `CanceledError` is an object that is thrown when an operation is canceled.
    	   *
    	   * @param {string=} message The message.
    	   * @param {Object=} config The config.
    	   * @param {Object=} request The request.
    	   *
    	   * @returns {CanceledError} The created error.
    	   */
    	  constructor(message, config, request) {
    	    super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
    	    this.name = 'CanceledError';
    	    this.__CANCEL__ = true;
    	  }
    	}

    	/**
    	 * Resolve or reject a Promise based on response status.
    	 *
    	 * @param {Function} resolve A function that resolves the promise.
    	 * @param {Function} reject A function that rejects the promise.
    	 * @param {object} response The response.
    	 *
    	 * @returns {object} The response.
    	 */
    	function settle(resolve, reject, response) {
    	  const validateStatus = response.config.validateStatus;
    	  if (!response.status || !validateStatus || validateStatus(response.status)) {
    	    resolve(response);
    	  } else {
    	    reject(new AxiosError(
    	      'Request failed with status code ' + response.status,
    	      response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE,
    	      response.config,
    	      response.request,
    	      response
    	    ));
    	  }
    	}

    	function parseProtocol(url) {
    	  const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
    	  return (match && match[1]) || '';
    	}

    	/**
    	 * Calculate data maxRate
    	 * @param {Number} [samplesCount= 10]
    	 * @param {Number} [min= 1000]
    	 * @returns {Function}
    	 */
    	function speedometer(samplesCount, min) {
    	  samplesCount = samplesCount || 10;
    	  const bytes = new Array(samplesCount);
    	  const timestamps = new Array(samplesCount);
    	  let head = 0;
    	  let tail = 0;
    	  let firstSampleTS;

    	  min = min !== undefined ? min : 1000;

    	  return function push(chunkLength) {
    	    const now = Date.now();

    	    const startedAt = timestamps[tail];

    	    if (!firstSampleTS) {
    	      firstSampleTS = now;
    	    }

    	    bytes[head] = chunkLength;
    	    timestamps[head] = now;

    	    let i = tail;
    	    let bytesCount = 0;

    	    while (i !== head) {
    	      bytesCount += bytes[i++];
    	      i = i % samplesCount;
    	    }

    	    head = (head + 1) % samplesCount;

    	    if (head === tail) {
    	      tail = (tail + 1) % samplesCount;
    	    }

    	    if (now - firstSampleTS < min) {
    	      return;
    	    }

    	    const passed = startedAt && now - startedAt;

    	    return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
    	  };
    	}

    	/**
    	 * Throttle decorator
    	 * @param {Function} fn
    	 * @param {Number} freq
    	 * @return {Function}
    	 */
    	function throttle(fn, freq) {
    	  let timestamp = 0;
    	  let threshold = 1000 / freq;
    	  let lastArgs;
    	  let timer;

    	  const invoke = (args, now = Date.now()) => {
    	    timestamp = now;
    	    lastArgs = null;
    	    if (timer) {
    	      clearTimeout(timer);
    	      timer = null;
    	    }
    	    fn(...args);
    	  };

    	  const throttled = (...args) => {
    	    const now = Date.now();
    	    const passed = now - timestamp;
    	    if (passed >= threshold) {
    	      invoke(args, now);
    	    } else {
    	      lastArgs = args;
    	      if (!timer) {
    	        timer = setTimeout(() => {
    	          timer = null;
    	          invoke(lastArgs);
    	        }, threshold - passed);
    	      }
    	    }
    	  };

    	  const flush = () => lastArgs && invoke(lastArgs);

    	  return [throttled, flush];
    	}

    	const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
    	  let bytesNotified = 0;
    	  const _speedometer = speedometer(50, 250);

    	  return throttle((e) => {
    	    if (!e || typeof e.loaded !== 'number') {
    	      return;
    	    }
    	    const rawLoaded = e.loaded;
    	    const total = e.lengthComputable ? e.total : undefined;
    	    const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
    	    const progressBytes = Math.max(0, loaded - bytesNotified);
    	    const rate = _speedometer(progressBytes);

    	    bytesNotified = Math.max(bytesNotified, loaded);

    	    const data = {
    	      loaded,
    	      total,
    	      progress: total ? loaded / total : undefined,
    	      bytes: progressBytes,
    	      rate: rate ? rate : undefined,
    	      estimated: rate && total ? (total - loaded) / rate : undefined,
    	      event: e,
    	      lengthComputable: total != null,
    	      [isDownloadStream ? 'download' : 'upload']: true,
    	    };

    	    listener(data);
    	  }, freq);
    	};

    	const progressEventDecorator = (total, throttled) => {
    	  const lengthComputable = total != null;

    	  return [
    	    (loaded) =>
    	      throttled[0]({
    	        lengthComputable,
    	        total,
    	        loaded,
    	      }),
    	    throttled[1],
    	  ];
    	};

    	const asyncDecorator =
    	  (fn) =>
    	  (...args) =>
    	    utils$1.asap(() => fn(...args));

    	var isURLSameOrigin = platform.hasStandardBrowserEnv
    	  ? ((origin, isMSIE) => (url) => {
    	      url = new URL(url, platform.origin);

    	      return (
    	        origin.protocol === url.protocol &&
    	        origin.host === url.host &&
    	        (isMSIE || origin.port === url.port)
    	      );
    	    })(
    	      new URL(platform.origin),
    	      platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
    	    )
    	  : () => true;

    	var cookies = platform.hasStandardBrowserEnv
    	  ? // Standard browser envs support document.cookie
    	    {
    	      write(name, value, expires, path, domain, secure, sameSite) {
    	        if (typeof document === 'undefined') return;

    	        const cookie = [`${name}=${encodeURIComponent(value)}`];

    	        if (utils$1.isNumber(expires)) {
    	          cookie.push(`expires=${new Date(expires).toUTCString()}`);
    	        }
    	        if (utils$1.isString(path)) {
    	          cookie.push(`path=${path}`);
    	        }
    	        if (utils$1.isString(domain)) {
    	          cookie.push(`domain=${domain}`);
    	        }
    	        if (secure === true) {
    	          cookie.push('secure');
    	        }
    	        if (utils$1.isString(sameSite)) {
    	          cookie.push(`SameSite=${sameSite}`);
    	        }

    	        document.cookie = cookie.join('; ');
    	      },

    	      read(name) {
    	        if (typeof document === 'undefined') return null;
    	        // Match name=value by splitting on the semicolon separator instead of building a
    	        // RegExp from `name` — interpolating an unescaped string into a RegExp would let
    	        // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
    	        // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
    	        // "; ", so ignore optional whitespace before each cookie name.
    	        const cookies = document.cookie.split(';');
    	        for (let i = 0; i < cookies.length; i++) {
    	          const cookie = cookies[i].replace(/^\s+/, '');
    	          const eq = cookie.indexOf('=');
    	          if (eq !== -1 && cookie.slice(0, eq) === name) {
    	            return decodeURIComponent(cookie.slice(eq + 1));
    	          }
    	        }
    	        return null;
    	      },

    	      remove(name) {
    	        this.write(name, '', Date.now() - 86400000, '/');
    	      },
    	    }
    	  : // Non-standard browser env (web workers, react-native) lack needed support.
    	    {
    	      write() {},
    	      read() {
    	        return null;
    	      },
    	      remove() {},
    	    };

    	/**
    	 * Determines whether the specified URL is absolute
    	 *
    	 * @param {string} url The URL to test
    	 *
    	 * @returns {boolean} True if the specified URL is absolute, otherwise false
    	 */
    	function isAbsoluteURL(url) {
    	  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
    	  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
    	  // by any combination of letters, digits, plus, period, or hyphen.
    	  if (typeof url !== 'string') {
    	    return false;
    	  }

    	  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
    	}

    	/**
    	 * Creates a new URL by combining the specified URLs
    	 *
    	 * @param {string} baseURL The base URL
    	 * @param {string} relativeURL The relative URL
    	 *
    	 * @returns {string} The combined URL
    	 */
    	function combineURLs(baseURL, relativeURL) {
    	  return relativeURL
    	    ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    	    : baseURL;
    	}

    	const malformedHttpProtocol = /^https?:(?!\/\/)/i;
    	const httpProtocolControlCharacters = /[\t\n\r]/g;

    	function stripLeadingC0ControlOrSpace(url) {
    	  let i = 0;
    	  while (i < url.length && url.charCodeAt(i) <= 0x20) {
    	    i++;
    	  }
    	  return url.slice(i);
    	}

    	function normalizeURLForProtocolCheck(url) {
    	  return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
    	}

    	function assertValidHttpProtocolURL(url, config) {
    	  if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
    	    throw new AxiosError(
    	      'Invalid URL: missing "//" after protocol',
    	      AxiosError.ERR_INVALID_URL,
    	      config
    	    );
    	  }
    	}

    	/**
    	 * Creates a new URL by combining the baseURL with the requestedURL,
    	 * only when the requestedURL is not already an absolute URL.
    	 * If the requestURL is absolute, this function returns the requestedURL untouched.
    	 *
    	 * @param {string} baseURL The base URL
    	 * @param {string} requestedURL Absolute or relative URL to combine
    	 *
    	 * @returns {string} The combined full path
    	 */
    	function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
    	  assertValidHttpProtocolURL(requestedURL, config);
    	  let isRelativeUrl = !isAbsoluteURL(requestedURL);
    	  if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
    	    assertValidHttpProtocolURL(baseURL, config);
    	    return combineURLs(baseURL, requestedURL);
    	  }
    	  return requestedURL;
    	}

    	const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing);

    	/**
    	 * Config-specific merge-function which creates a new config-object
    	 * by merging two configuration objects together.
    	 *
    	 * @param {Object} config1
    	 * @param {Object} config2
    	 *
    	 * @returns {Object} New object resulting from merging config2 to config1
    	 */
    	function mergeConfig(config1, config2) {
    	  // eslint-disable-next-line no-param-reassign
    	  config2 = config2 || {};

    	  // Use a null-prototype object so that downstream reads such as `config.auth`
    	  // or `config.baseURL` cannot inherit polluted values from Object.prototype.
    	  // `hasOwnProperty` is restored as a non-enumerable own slot to preserve
    	  // ergonomics for user code that relies on it.
    	  const config = Object.create(null);
    	  Object.defineProperty(config, 'hasOwnProperty', {
    	    // Null-proto descriptor so a polluted Object.prototype.get cannot turn
    	    // this data descriptor into an accessor descriptor on the way in.
    	    __proto__: null,
    	    value: Object.prototype.hasOwnProperty,
    	    enumerable: false,
    	    writable: true,
    	    configurable: true,
    	  });

    	  function getMergedValue(target, source, prop, caseless) {
    	    if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
    	      return utils$1.merge.call({ caseless }, target, source);
    	    } else if (utils$1.isPlainObject(source)) {
    	      return utils$1.merge({}, source);
    	    } else if (utils$1.isArray(source)) {
    	      return source.slice();
    	    }
    	    return source;
    	  }

    	  function mergeDeepProperties(a, b, prop, caseless) {
    	    if (!utils$1.isUndefined(b)) {
    	      return getMergedValue(a, b, prop, caseless);
    	    } else if (!utils$1.isUndefined(a)) {
    	      return getMergedValue(undefined, a, prop, caseless);
    	    }
    	  }

    	  // eslint-disable-next-line consistent-return
    	  function valueFromConfig2(a, b) {
    	    if (!utils$1.isUndefined(b)) {
    	      return getMergedValue(undefined, b);
    	    }
    	  }

    	  // eslint-disable-next-line consistent-return
    	  function defaultToConfig2(a, b) {
    	    if (!utils$1.isUndefined(b)) {
    	      return getMergedValue(undefined, b);
    	    } else if (!utils$1.isUndefined(a)) {
    	      return getMergedValue(undefined, a);
    	    }
    	  }

    	  function getMergedTransitionalOption(prop) {
    	    const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;

    	    if (!utils$1.isUndefined(transitional2)) {
    	      if (utils$1.isPlainObject(transitional2)) {
    	        if (utils$1.hasOwnProp(transitional2, prop)) {
    	          return transitional2[prop];
    	        }
    	      } else {
    	        return undefined;
    	      }
    	    }

    	    const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;

    	    if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
    	      return transitional1[prop];
    	    }

    	    return undefined;
    	  }

    	  // eslint-disable-next-line consistent-return
    	  function mergeDirectKeys(a, b, prop) {
    	    if (utils$1.hasOwnProp(config2, prop)) {
    	      return getMergedValue(a, b);
    	    } else if (utils$1.hasOwnProp(config1, prop)) {
    	      return getMergedValue(undefined, a);
    	    }
    	  }

    	  const mergeMap = {
    	    url: valueFromConfig2,
    	    method: valueFromConfig2,
    	    data: valueFromConfig2,
    	    baseURL: defaultToConfig2,
    	    transformRequest: defaultToConfig2,
    	    transformResponse: defaultToConfig2,
    	    paramsSerializer: defaultToConfig2,
    	    timeout: defaultToConfig2,
    	    timeoutMessage: defaultToConfig2,
    	    withCredentials: defaultToConfig2,
    	    withXSRFToken: defaultToConfig2,
    	    adapter: defaultToConfig2,
    	    responseType: defaultToConfig2,
    	    xsrfCookieName: defaultToConfig2,
    	    xsrfHeaderName: defaultToConfig2,
    	    onUploadProgress: defaultToConfig2,
    	    onDownloadProgress: defaultToConfig2,
    	    decompress: defaultToConfig2,
    	    maxContentLength: defaultToConfig2,
    	    maxBodyLength: defaultToConfig2,
    	    beforeRedirect: defaultToConfig2,
    	    transport: defaultToConfig2,
    	    httpAgent: defaultToConfig2,
    	    httpsAgent: defaultToConfig2,
    	    cancelToken: defaultToConfig2,
    	    socketPath: defaultToConfig2,
    	    allowedSocketPaths: defaultToConfig2,
    	    responseEncoding: defaultToConfig2,
    	    validateStatus: mergeDirectKeys,
    	    headers: (a, b, prop) =>
    	      mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
    	  };

    	  utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
    	    if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
    	    const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
    	    const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
    	    const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
    	    const configValue = merge(a, b, prop);
    	    (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
    	  });

    	  if (
    	    utils$1.hasOwnProp(config2, 'validateStatus') &&
    	    utils$1.isUndefined(config2.validateStatus) &&
    	    getMergedTransitionalOption('validateStatusUndefinedResolves') === false
    	  ) {
    	    if (utils$1.hasOwnProp(config1, 'validateStatus')) {
    	      config.validateStatus = getMergedValue(undefined, config1.validateStatus);
    	    } else {
    	      delete config.validateStatus;
    	    }
    	  }

    	  return config;
    	}

    	const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];

    	function setFormDataHeaders(headers, formHeaders, policy) {
    	  if (policy !== 'content-only') {
    	    headers.set(formHeaders);
    	    return;
    	  }

    	  Object.entries(formHeaders).forEach(([key, val]) => {
    	    if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
    	      headers.set(key, val);
    	    }
    	  });
    	}

    	/**
    	 * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
    	 * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
    	 *
    	 * @param {string} str The string to encode
    	 *
    	 * @returns {string} UTF-8 bytes as a Latin-1 string
    	 */
    	const encodeUTF8$1 = (str) =>
    	  encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
    	    String.fromCharCode(parseInt(hex, 16))
    	  );

    	function resolveConfig(config) {
    	  const newConfig = mergeConfig({}, config);

    	  // Read only own properties to prevent prototype pollution gadgets
    	  // (e.g. Object.prototype.baseURL = 'https://evil.com').
    	  const own = (key) => (utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined);

    	  const data = own('data');
    	  let withXSRFToken = own('withXSRFToken');
    	  const xsrfHeaderName = own('xsrfHeaderName');
    	  const xsrfCookieName = own('xsrfCookieName');
    	  let headers = own('headers');
    	  const auth = own('auth');
    	  const baseURL = own('baseURL');
    	  const allowAbsoluteUrls = own('allowAbsoluteUrls');
    	  const url = own('url');

    	  newConfig.headers = headers = AxiosHeaders.from(headers);

    	  newConfig.url = buildURL(
    	    buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig),
    	    own('params'),
    	    own('paramsSerializer')
    	  );

    	  // HTTP basic authentication
    	  if (auth) {
    	    const username = utils$1.getSafeProp(auth, 'username') || '';
    	    const password = utils$1.getSafeProp(auth, 'password') || '';

    	    headers.set(
    	      'Authorization',
    	      'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : ''))
    	    );
    	  }

    	  if (utils$1.isFormData(data)) {
    	    if (
    	      platform.hasStandardBrowserEnv ||
    	      platform.hasStandardBrowserWebWorkerEnv ||
    	      utils$1.isReactNative(data)
    	    ) {
    	      headers.setContentType(undefined); // browser/web worker/RN handles it
    	    } else if (utils$1.isFunction(data.getHeaders)) {
    	      // Node.js FormData (like form-data package)
    	      setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
    	    }
    	  }

    	  // Add xsrf header
    	  // This is only done if running in a standard browser environment.
    	  // Specifically not if we're in a web worker, or react-native.

    	  if (platform.hasStandardBrowserEnv) {
    	    if (utils$1.isFunction(withXSRFToken)) {
    	      withXSRFToken = withXSRFToken(newConfig);
    	    }

    	    // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
    	    // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
    	    // the XSRF token cross-origin.
    	    const shouldSendXSRF =
    	      withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));

    	    if (shouldSendXSRF) {
    	      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);

    	      if (xsrfValue) {
    	        headers.set(xsrfHeaderName, xsrfValue);
    	      }
    	    }
    	  }

    	  return newConfig;
    	}

    	const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';

    	var xhrAdapter = isXHRAdapterSupported &&
    	  function (config) {
    	    return new Promise(function dispatchXhrRequest(resolve, reject) {
    	      const _config = resolveConfig(config);
    	      let requestData = _config.data;
    	      const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
    	      let { responseType, onUploadProgress, onDownloadProgress } = _config;
    	      let onCanceled;
    	      let uploadThrottled, downloadThrottled;
    	      let flushUpload, flushDownload;

    	      function done() {
    	        flushUpload && flushUpload(); // flush events
    	        flushDownload && flushDownload(); // flush events

    	        _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);

    	        _config.signal && _config.signal.removeEventListener('abort', onCanceled);
    	      }

    	      let request = new XMLHttpRequest();

    	      request.open(_config.method.toUpperCase(), _config.url, true);

    	      // Set the request timeout in MS
    	      request.timeout = _config.timeout;

    	      function onloadend() {
    	        if (!request) {
    	          return;
    	        }
    	        // Prepare the response
    	        const responseHeaders = AxiosHeaders.from(
    	          'getAllResponseHeaders' in request && request.getAllResponseHeaders()
    	        );
    	        const responseData =
    	          !responseType || responseType === 'text' || responseType === 'json'
    	            ? request.responseText
    	            : request.response;
    	        const response = {
    	          data: responseData,
    	          status: request.status,
    	          statusText: request.statusText,
    	          headers: responseHeaders,
    	          config,
    	          request,
    	        };

    	        settle(
    	          function _resolve(value) {
    	            resolve(value);
    	            done();
    	          },
    	          function _reject(err) {
    	            reject(err);
    	            done();
    	          },
    	          response
    	        );

    	        // Clean up request
    	        request = null;
    	      }

    	      if ('onloadend' in request) {
    	        // Use onloadend if available
    	        request.onloadend = onloadend;
    	      } else {
    	        // Listen for ready state to emulate onloadend
    	        request.onreadystatechange = function handleLoad() {
    	          if (!request || request.readyState !== 4) {
    	            return;
    	          }

    	          // The request errored out and we didn't get a response, this will be
    	          // handled by onerror instead
    	          // With one exception: request that using file: protocol, most browsers
    	          // will return status as 0 even though it's a successful request
    	          if (
    	            request.status === 0 &&
    	            !(request.responseURL && request.responseURL.startsWith('file:'))
    	          ) {
    	            return;
    	          }
    	          // readystate handler is calling before onerror or ontimeout handlers,
    	          // so we should call onloadend on the next 'tick'
    	          setTimeout(onloadend);
    	        };
    	      }

    	      // Handle browser request cancellation (as opposed to a manual cancellation)
    	      request.onabort = function handleAbort() {
    	        if (!request) {
    	          return;
    	        }

    	        reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
    	        done();

    	        // Clean up request
    	        request = null;
    	      };

    	      // Handle low level network errors
    	      request.onerror = function handleError(event) {
    	        // Browsers deliver a ProgressEvent in XHR onerror
    	        // (message may be empty; when present, surface it)
    	        // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
    	        const msg = event && event.message ? event.message : 'Network Error';
    	        const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
    	        // attach the underlying event for consumers who want details
    	        err.event = event || null;
    	        reject(err);
    	        done();
    	        request = null;
    	      };

    	      // Handle timeout
    	      request.ontimeout = function handleTimeout() {
    	        let timeoutErrorMessage = _config.timeout
    	          ? 'timeout of ' + _config.timeout + 'ms exceeded'
    	          : 'timeout exceeded';
    	        const transitional = _config.transitional || transitionalDefaults;
    	        if (_config.timeoutErrorMessage) {
    	          timeoutErrorMessage = _config.timeoutErrorMessage;
    	        }
    	        reject(
    	          new AxiosError(
    	            timeoutErrorMessage,
    	            transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
    	            config,
    	            request
    	          )
    	        );
    	        done();

    	        // Clean up request
    	        request = null;
    	      };

    	      // Remove Content-Type if data is undefined
    	      requestData === undefined && requestHeaders.setContentType(null);

    	      // Add headers to the request
    	      if ('setRequestHeader' in request) {
    	        utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
    	          request.setRequestHeader(key, val);
    	        });
    	      }

    	      // Add withCredentials to request if needed
    	      if (!utils$1.isUndefined(_config.withCredentials)) {
    	        request.withCredentials = !!_config.withCredentials;
    	      }

    	      // Add responseType to request if needed
    	      if (responseType && responseType !== 'json') {
    	        request.responseType = _config.responseType;
    	      }

    	      // Handle progress if needed
    	      if (onDownloadProgress) {
    	        [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
    	        request.addEventListener('progress', downloadThrottled);
    	      }

    	      // Not all browsers support upload events
    	      if (onUploadProgress && request.upload) {
    	        [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);

    	        request.upload.addEventListener('progress', uploadThrottled);

    	        request.upload.addEventListener('loadend', flushUpload);
    	      }

    	      if (_config.cancelToken || _config.signal) {
    	        // Handle cancellation
    	        // eslint-disable-next-line func-names
    	        onCanceled = (cancel) => {
    	          if (!request) {
    	            return;
    	          }
    	          reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
    	          request.abort();
    	          done();
    	          request = null;
    	        };

    	        _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
    	        if (_config.signal) {
    	          _config.signal.aborted
    	            ? onCanceled()
    	            : _config.signal.addEventListener('abort', onCanceled);
    	        }
    	      }

    	      const protocol = parseProtocol(_config.url);

    	      if (protocol && !platform.protocols.includes(protocol)) {
    	        reject(
    	          new AxiosError(
    	            'Unsupported protocol ' + protocol + ':',
    	            AxiosError.ERR_BAD_REQUEST,
    	            config
    	          )
    	        );
    	        return;
    	      }

    	      // Send the request
    	      request.send(requestData || null);
    	    });
    	  };

    	const composeSignals = (signals, timeout) => {
    	  signals = signals ? signals.filter(Boolean) : [];

    	  if (!timeout && !signals.length) {
    	    return;
    	  }

    	  const controller = new AbortController();

    	  let aborted = false;

    	  const onabort = function (reason) {
    	    if (!aborted) {
    	      aborted = true;
    	      unsubscribe();
    	      const err = reason instanceof Error ? reason : this.reason;
    	      controller.abort(
    	        err instanceof AxiosError
    	          ? err
    	          : new CanceledError(err instanceof Error ? err.message : err)
    	      );
    	    }
    	  };

    	  let timer =
    	    timeout &&
    	    setTimeout(() => {
    	      timer = null;
    	      onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
    	    }, timeout);

    	  const unsubscribe = () => {
    	    if (!signals) { return; }
    	    timer && clearTimeout(timer);
    	    timer = null;
    	    signals.forEach((signal) => {
    	      signal.unsubscribe
    	        ? signal.unsubscribe(onabort)
    	        : signal.removeEventListener('abort', onabort);
    	    });
    	    signals = null;
    	  };

    	  signals.forEach((signal) => signal.addEventListener('abort', onabort));

    	  const { signal } = controller;

    	  signal.unsubscribe = () => utils$1.asap(unsubscribe);

    	  return signal;
    	};

    	const streamChunk = function* (chunk, chunkSize) {
    	  let len = chunk.byteLength;

    	  if (len < chunkSize) {
    	    yield chunk;
    	    return;
    	  }

    	  let pos = 0;
    	  let end;

    	  while (pos < len) {
    	    end = pos + chunkSize;
    	    yield chunk.slice(pos, end);
    	    pos = end;
    	  }
    	};

    	const readBytes = async function* (iterable, chunkSize) {
    	  for await (const chunk of readStream(iterable)) {
    	    yield* streamChunk(chunk, chunkSize);
    	  }
    	};

    	const readStream = async function* (stream) {
    	  if (stream[Symbol.asyncIterator]) {
    	    yield* stream;
    	    return;
    	  }

    	  const reader = stream.getReader();
    	  try {
    	    for (;;) {
    	      const { done, value } = await reader.read();
    	      if (done) {
    	        break;
    	      }
    	      yield value;
    	    }
    	  } finally {
    	    await reader.cancel();
    	  }
    	};

    	const trackStream = (stream, chunkSize, onProgress, onFinish) => {
    	  const iterator = readBytes(stream, chunkSize);

    	  let bytes = 0;
    	  let done;
    	  let _onFinish = (e) => {
    	    if (!done) {
    	      done = true;
    	      onFinish && onFinish(e);
    	    }
    	  };

    	  return new ReadableStream(
    	    {
    	      async pull(controller) {
    	        try {
    	          const { done, value } = await iterator.next();

    	          if (done) {
    	            _onFinish();
    	            controller.close();
    	            return;
    	          }

    	          let len = value.byteLength;
    	          if (onProgress) {
    	            let loadedBytes = (bytes += len);
    	            onProgress(loadedBytes);
    	          }
    	          controller.enqueue(new Uint8Array(value));
    	        } catch (err) {
    	          _onFinish(err);
    	          throw err;
    	        }
    	      },
    	      cancel(reason) {
    	        _onFinish(reason);
    	        return iterator.return();
    	      },
    	    },
    	    {
    	      highWaterMark: 2,
    	    }
    	  );
    	};

    	/**
    	 * Estimate decoded byte length of a data:// URL *without* allocating large buffers.
    	 * - For base64: compute exact decoded size using length and padding;
    	 *               handle %XX at the character-count level (no string allocation).
    	 * - For non-base64: compute the exact percent-decoded UTF-8 byte length.
    	 *
    	 * @param {string} url
    	 * @returns {number}
    	 */
    	const isHexDigit = (charCode) =>
    	  (charCode >= 48 && charCode <= 57) ||
    	  (charCode >= 65 && charCode <= 70) ||
    	  (charCode >= 97 && charCode <= 102);

    	const isPercentEncodedByte = (str, i, len) =>
    	  i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));

    	function estimateDataURLDecodedBytes(url) {
    	  if (!url || typeof url !== 'string') return 0;
    	  if (!url.startsWith('data:')) return 0;

    	  const comma = url.indexOf(',');
    	  if (comma < 0) return 0;

    	  const meta = url.slice(5, comma);
    	  const body = url.slice(comma + 1);
    	  const isBase64 = /;base64/i.test(meta);

    	  if (isBase64) {
    	    let effectiveLen = body.length;
    	    const len = body.length; // cache length

    	    for (let i = 0; i < len; i++) {
    	      if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
    	        const a = body.charCodeAt(i + 1);
    	        const b = body.charCodeAt(i + 2);
    	        const isHex = isHexDigit(a) && isHexDigit(b);

    	        if (isHex) {
    	          effectiveLen -= 2;
    	          i += 2;
    	        }
    	      }
    	    }

    	    let pad = 0;
    	    let idx = len - 1;

    	    const tailIsPct3D = (j) =>
    	      j >= 2 &&
    	      body.charCodeAt(j - 2) === 37 && // '%'
    	      body.charCodeAt(j - 1) === 51 && // '3'
    	      (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'

    	    if (idx >= 0) {
    	      if (body.charCodeAt(idx) === 61 /* '=' */) {
    	        pad++;
    	        idx--;
    	      } else if (tailIsPct3D(idx)) {
    	        pad++;
    	        idx -= 3;
    	      }
    	    }

    	    if (pad === 1 && idx >= 0) {
    	      if (body.charCodeAt(idx) === 61 /* '=' */) {
    	        pad++;
    	      } else if (tailIsPct3D(idx)) {
    	        pad++;
    	      }
    	    }

    	    const groups = Math.floor(effectiveLen / 4);
    	    const bytes = groups * 3 - (pad || 0);
    	    return bytes > 0 ? bytes : 0;
    	  }

    	  // Compute UTF-8 byte length directly from UTF-16 code units without allocating
    	  // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
    	  // Valid %XX triplets count as one decoded byte; this matches the bytes that
    	  // decodeURIComponent(body) would produce before Buffer re-encodes the string.
    	  let bytes = 0;
    	  for (let i = 0, len = body.length; i < len; i++) {
    	    const c = body.charCodeAt(i);
    	    if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
    	      bytes += 1;
    	      i += 2;
    	    } else if (c < 0x80) {
    	      bytes += 1;
    	    } else if (c < 0x800) {
    	      bytes += 2;
    	    } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
    	      const next = body.charCodeAt(i + 1);
    	      if (next >= 0xdc00 && next <= 0xdfff) {
    	        bytes += 4;
    	        i++;
    	      } else {
    	        bytes += 3;
    	      }
    	    } else {
    	      bytes += 3;
    	    }
    	  }
    	  return bytes;
    	}

    	const VERSION = "1.18.0";

    	const DEFAULT_CHUNK_SIZE = 64 * 1024;

    	const { isFunction } = utils$1;

    	/**
    	 * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
    	 * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
    	 *
    	 * @param {string} str The string to encode
    	 *
    	 * @returns {string} UTF-8 bytes as a Latin-1 string
    	 */
    	const encodeUTF8 = (str) =>
    	  encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
    	    String.fromCharCode(parseInt(hex, 16))
    	  );

    	// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
    	// Decode before composing the `auth` option so credentials such as
    	// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
    	// original value for malformed input so a bad encoding never throws.
    	const decodeURIComponentSafe = (value) => {
    	  if (!utils$1.isString(value)) {
    	    return value;
    	  }

    	  try {
    	    return decodeURIComponent(value);
    	  } catch (error) {
    	    return value;
    	  }
    	};

    	const test = (fn, ...args) => {
    	  try {
    	    return !!fn(...args);
    	  } catch (e) {
    	    return false;
    	  }
    	};

    	const maybeWithAuthCredentials = (url) => {
    	  const protocolIndex = url.indexOf('://');
    	  let urlToCheck = url;
    	  if (protocolIndex !== -1) {
    	    urlToCheck = urlToCheck.slice(protocolIndex + 3);
    	  }
    	  return urlToCheck.includes('@') || urlToCheck.includes(':');
    	};

    	const factory = (env) => {
    	  const globalObject =
    	    utils$1.global !== undefined && utils$1.global !== null
    	      ? utils$1.global
    	      : globalThis;
    	  const { ReadableStream, TextEncoder } = globalObject;

    	  env = utils$1.merge.call(
    	    {
    	      skipUndefined: true,
    	    },
    	    {
    	      Request: globalObject.Request,
    	      Response: globalObject.Response,
    	    },
    	    env
    	  );

    	  const { fetch: envFetch, Request, Response } = env;
    	  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
    	  const isRequestSupported = isFunction(Request);
    	  const isResponseSupported = isFunction(Response);

    	  if (!isFetchSupported) {
    	    return false;
    	  }

    	  const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);

    	  const encodeText =
    	    isFetchSupported &&
    	    (typeof TextEncoder === 'function'
    	      ? (
    	          (encoder) => (str) =>
    	            encoder.encode(str)
    	        )(new TextEncoder())
    	      : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));

    	  const supportsRequestStream =
    	    isRequestSupported &&
    	    isReadableStreamSupported &&
    	    test(() => {
    	      let duplexAccessed = false;

    	      const request = new Request(platform.origin, {
    	        body: new ReadableStream(),
    	        method: 'POST',
    	        get duplex() {
    	          duplexAccessed = true;
    	          return 'half';
    	        },
    	      });

    	      const hasContentType = request.headers.has('Content-Type');

    	      if (request.body != null) {
    	        request.body.cancel();
    	      }

    	      return duplexAccessed && !hasContentType;
    	    });

    	  const supportsResponseStream =
    	    isResponseSupported &&
    	    isReadableStreamSupported &&
    	    test(() => utils$1.isReadableStream(new Response('').body));

    	  const resolvers = {
    	    stream: supportsResponseStream && ((res) => res.body),
    	  };

    	  isFetchSupported &&
    	    (() => {
    	      ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
    	        !resolvers[type] &&
    	          (resolvers[type] = (res, config) => {
    	            let method = res && res[type];

    	            if (method) {
    	              return method.call(res);
    	            }

    	            throw new AxiosError(
    	              `Response type '${type}' is not supported`,
    	              AxiosError.ERR_NOT_SUPPORT,
    	              config
    	            );
    	          });
    	      });
    	    })();

    	  const getBodyLength = async (body) => {
    	    if (body == null) {
    	      return 0;
    	    }

    	    if (utils$1.isBlob(body)) {
    	      return body.size;
    	    }

    	    if (utils$1.isSpecCompliantForm(body)) {
    	      const _request = new Request(platform.origin, {
    	        method: 'POST',
    	        body,
    	      });
    	      return (await _request.arrayBuffer()).byteLength;
    	    }

    	    if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
    	      return body.byteLength;
    	    }

    	    if (utils$1.isURLSearchParams(body)) {
    	      body = body + '';
    	    }

    	    if (utils$1.isString(body)) {
    	      return (await encodeText(body)).byteLength;
    	    }
    	  };

    	  const resolveBodyLength = async (headers, body) => {
    	    const length = utils$1.toFiniteNumber(headers.getContentLength());

    	    return length == null ? getBodyLength(body) : length;
    	  };

    	  return async (config) => {
    	    let {
    	      url,
    	      method,
    	      data,
    	      signal,
    	      cancelToken,
    	      timeout,
    	      onDownloadProgress,
    	      onUploadProgress,
    	      responseType,
    	      headers,
    	      withCredentials = 'same-origin',
    	      fetchOptions,
    	      maxContentLength,
    	      maxBodyLength,
    	    } = resolveConfig(config);

    	    const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
    	    const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
    	    const own = (key) => (utils$1.hasOwnProp(config, key) ? config[key] : undefined);

    	    let _fetch = envFetch || fetch;

    	    responseType = responseType ? (responseType + '').toLowerCase() : 'text';

    	    let composedSignal = composeSignals(
    	      [signal, cancelToken && cancelToken.toAbortSignal()],
    	      timeout
    	    );

    	    let request = null;

    	    const unsubscribe =
    	      composedSignal &&
    	      composedSignal.unsubscribe &&
    	      (() => {
    	        composedSignal.unsubscribe();
    	      });

    	    let requestContentLength;

    	    // AxiosError we raise while the request body is being streamed. Captured
    	    // by identity so the catch block can surface it directly, regardless of
    	    // how the runtime wraps the resulting fetch rejection (undici exposes it
    	    // as `err.cause`; some browsers drop the original error entirely).
    	    let pendingBodyError = null;

    	    const maxBodyLengthError = () =>
    	      new AxiosError(
    	        'Request body larger than maxBodyLength limit',
    	        AxiosError.ERR_BAD_REQUEST,
    	        config,
    	        request
    	      );

    	    try {
    	      // HTTP basic authentication
    	      let auth = undefined;
    	      const configAuth = own('auth');

    	      if (configAuth) {
    	        const username = utils$1.getSafeProp(configAuth, 'username') || '';
    	        const password = utils$1.getSafeProp(configAuth, 'password') || '';
    	        auth = {
    	          username,
    	          password
    	        };
    	      }

    	      if (maybeWithAuthCredentials(url)) {
    	        const parsedURL = new URL(url, platform.origin);

    	        if (!auth && (parsedURL.username || parsedURL.password)) {
    	          const urlUsername = decodeURIComponentSafe(parsedURL.username);
    	          const urlPassword = decodeURIComponentSafe(parsedURL.password);
    	          auth = {
    	            username: urlUsername,
    	            password: urlPassword
    	          };
    	        }

    	        if (parsedURL.username || parsedURL.password) {
    	          parsedURL.username = '';
    	          parsedURL.password = '';
    	          url = parsedURL.href;
    	        }
    	      }

    	      if (auth) {
    	        headers.delete('authorization');
    	        headers.set(
    	          'Authorization',
    	          'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || '')))
    	        );
    	      }

    	      // Enforce maxContentLength for data: URLs up-front so we never materialize
    	      // an oversized payload. The HTTP adapter applies the same check (see http.js
    	      // "if (protocol === 'data:')" branch).
    	      if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
    	        const estimated = estimateDataURLDecodedBytes(url);
    	        if (estimated > maxContentLength) {
    	          throw new AxiosError(
    	            'maxContentLength size of ' + maxContentLength + ' exceeded',
    	            AxiosError.ERR_BAD_RESPONSE,
    	            config,
    	            request
    	          );
    	        }
    	      }

    	      // Enforce maxBodyLength against known-size bodies before dispatch using
    	      // the body's *actual* size — never a caller-declared Content-Length,
    	      // which could under-report to slip an oversized body past the check.
    	      // Unknown-size streams return undefined here and are counted per-chunk
    	      // below as fetch consumes them.
    	      if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
    	        const outboundLength = await getBodyLength(data);
    	        if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
    	          requestContentLength = outboundLength;
    	          if (outboundLength > maxBodyLength) {
    	            throw maxBodyLengthError();
    	          }
    	        }
    	      }

    	      // A streamed body under maxBodyLength must be counted as fetch consumes
    	      // it; its size is never trusted from a caller-declared Content-Length.
    	      const mustEnforceStreamBody =
    	        hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));

    	      const trackRequestStream = (stream, onProgress, flush) =>
    	        trackStream(
    	          stream,
    	          DEFAULT_CHUNK_SIZE,
    	          (loadedBytes) => {
    	            if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
    	              throw (pendingBodyError = maxBodyLengthError());
    	            }
    	            onProgress && onProgress(loadedBytes);
    	          },
    	          flush
    	        );

    	      if (
    	        supportsRequestStream &&
    	        method !== 'get' &&
    	        method !== 'head' &&
    	        (onUploadProgress || mustEnforceStreamBody)
    	      ) {
    	        requestContentLength =
    	          requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;

    	        // A declared length of 0 is only trusted to skip the wrap when we are
    	        // not enforcing a stream limit (which must not rely on that header).
    	        if (requestContentLength !== 0 || mustEnforceStreamBody) {
    	          let _request = new Request(url, {
    	            method: 'POST',
    	            body: data,
    	            duplex: 'half',
    	          });

    	          let contentTypeHeader;

    	          if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
    	            headers.setContentType(contentTypeHeader);
    	          }

    	          if (_request.body) {
    	            const [onProgress, flush] =
    	              (onUploadProgress &&
    	                progressEventDecorator(
    	                  requestContentLength,
    	                  progressEventReducer(asyncDecorator(onUploadProgress))
    	                )) ||
    	              [];

    	            data = trackRequestStream(_request.body, onProgress, flush);
    	          }
    	        }
    	      } else if (
    	        mustEnforceStreamBody &&
    	        !isRequestSupported &&
    	        isReadableStreamSupported &&
    	        method !== 'get' &&
    	        method !== 'head'
    	      ) {
    	        data = trackRequestStream(data);
    	      } else if (
    	        mustEnforceStreamBody &&
    	        isRequestSupported &&
    	        !supportsRequestStream &&
    	        method !== 'get' &&
    	        method !== 'head'
    	      ) {
    	        throw new AxiosError(
    	          'Stream request bodies are not supported by the current fetch implementation',
    	          AxiosError.ERR_NOT_SUPPORT,
    	          config,
    	          request
    	        );
    	      }

    	      if (!utils$1.isString(withCredentials)) {
    	        withCredentials = withCredentials ? 'include' : 'omit';
    	      }

    	      // Cloudflare Workers throws when credentials are defined
    	      // see https://github.com/cloudflare/workerd/issues/902
    	      const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;

    	      // If data is FormData and Content-Type is multipart/form-data without boundary,
    	      // delete it so fetch can set it correctly with the boundary
    	      if (utils$1.isFormData(data)) {
    	        const contentType = headers.getContentType();
    	        if (
    	          contentType &&
    	          /^multipart\/form-data/i.test(contentType) &&
    	          !/boundary=/i.test(contentType)
    	        ) {
    	          headers.delete('content-type');
    	        }
    	      }

    	      // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
    	      headers.set('User-Agent', 'axios/' + VERSION, false);

    	      const resolvedOptions = {
    	        ...fetchOptions,
    	        signal: composedSignal,
    	        method: method.toUpperCase(),
    	        headers: toByteStringHeaderObject(headers.normalize()),
    	        body: data,
    	        duplex: 'half',
    	        credentials: isCredentialsSupported ? withCredentials : undefined,
    	      };

    	      request = isRequestSupported && new Request(url, resolvedOptions);

    	      let response = await (isRequestSupported
    	        ? _fetch(request, fetchOptions)
    	        : _fetch(url, resolvedOptions));

    	      const responseHeaders = AxiosHeaders.from(response.headers);

    	      // Cheap pre-check: if the server honestly declares a content-length that
    	      // already exceeds the cap, reject before we start streaming.
    	      if (hasMaxContentLength) {
    	        const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
    	        if (declaredLength != null && declaredLength > maxContentLength) {
    	          throw new AxiosError(
    	            'maxContentLength size of ' + maxContentLength + ' exceeded',
    	            AxiosError.ERR_BAD_RESPONSE,
    	            config,
    	            request
    	          );
    	        }
    	      }

    	      const isStreamResponse =
    	        supportsResponseStream && (responseType === 'stream' || responseType === 'response');

    	      if (
    	        supportsResponseStream &&
    	        response.body &&
    	        (onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe))
    	      ) {
    	        const options = {};

    	        ['status', 'statusText', 'headers'].forEach((prop) => {
    	          options[prop] = response[prop];
    	        });

    	        const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());

    	        const [onProgress, flush] =
    	          (onDownloadProgress &&
    	            progressEventDecorator(
    	              responseContentLength,
    	              progressEventReducer(asyncDecorator(onDownloadProgress), true)
    	            )) ||
    	          [];

    	        let bytesRead = 0;
    	        const onChunkProgress = (loadedBytes) => {
    	          if (hasMaxContentLength) {
    	            bytesRead = loadedBytes;
    	            if (bytesRead > maxContentLength) {
    	              throw new AxiosError(
    	                'maxContentLength size of ' + maxContentLength + ' exceeded',
    	                AxiosError.ERR_BAD_RESPONSE,
    	                config,
    	                request
    	              );
    	            }
    	          }
    	          onProgress && onProgress(loadedBytes);
    	        };

    	        response = new Response(
    	          trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
    	            flush && flush();
    	            unsubscribe && unsubscribe();
    	          }),
    	          options
    	        );
    	      }

    	      responseType = responseType || 'text';

    	      let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](
    	        response,
    	        config
    	      );

    	      // Fallback enforcement for environments without ReadableStream support
    	      // (legacy runtimes). Detect materialized size from typed output; skip
    	      // streams/Response passthrough since the user will read those themselves.
    	      if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
    	        let materializedSize;
    	        if (responseData != null) {
    	          if (typeof responseData.byteLength === 'number') {
    	            materializedSize = responseData.byteLength;
    	          } else if (typeof responseData.size === 'number') {
    	            materializedSize = responseData.size;
    	          } else if (typeof responseData === 'string') {
    	            materializedSize =
    	              typeof TextEncoder === 'function'
    	                ? new TextEncoder().encode(responseData).byteLength
    	                : responseData.length;
    	          }
    	        }
    	        if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
    	          throw new AxiosError(
    	            'maxContentLength size of ' + maxContentLength + ' exceeded',
    	            AxiosError.ERR_BAD_RESPONSE,
    	            config,
    	            request
    	          );
    	        }
    	      }

    	      !isStreamResponse && unsubscribe && unsubscribe();

    	      return await new Promise((resolve, reject) => {
    	        settle(resolve, reject, {
    	          data: responseData,
    	          headers: AxiosHeaders.from(response.headers),
    	          status: response.status,
    	          statusText: response.statusText,
    	          config,
    	          request,
    	        });
    	      });
    	    } catch (err) {
    	      unsubscribe && unsubscribe();

    	      // Safari can surface fetch aborts as a DOMException-like object whose
    	      // branded getters throw. Prefer our composed signal reason before reading
    	      // the caught error, preserving timeout vs cancellation semantics.
    	      if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
    	        const canceledError = composedSignal.reason;
    	        canceledError.config = config;
    	        request && (canceledError.request = request);
    	        err !== canceledError && (canceledError.cause = err);
    	        throw canceledError;
    	      }

    	      // Surface a maxBodyLength violation we raised while the request body was
    	      // being streamed. Matching by identity (rather than reading
    	      // `err.cause.isAxiosError`) keeps the error deterministic across runtimes
    	      // and avoids both prototype-pollution reads and mis-attributing a foreign
    	      // AxiosError that merely happened to land in `err.cause`.
    	      if (pendingBodyError) {
    	        request && !pendingBodyError.request && (pendingBodyError.request = request);
    	        throw pendingBodyError;
    	      }

    	      // Re-throw AxiosErrors we raised synchronously (data: URL / content-length
    	      // pre-checks, response size enforcement) without re-wrapping them.
    	      if (err instanceof AxiosError) {
    	        request && !err.request && (err.request = request);
    	        throw err;
    	      }

    	      if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
    	        throw Object.assign(
    	          new AxiosError(
    	            'Network Error',
    	            AxiosError.ERR_NETWORK,
    	            config,
    	            request,
    	            err && err.response
    	          ),
    	          {
    	            cause: err.cause || err,
    	          }
    	        );
    	      }

    	      throw AxiosError.from(err, err && err.code, config, request, err && err.response);
    	    }
    	  };
    	};

    	const seedCache = new Map();

    	const getFetch = (config) => {
    	  let env = (config && config.env) || {};
    	  const { fetch, Request, Response } = env;
    	  const seeds = [Request, Response, fetch];

    	  let len = seeds.length,
    	    i = len,
    	    seed,
    	    target,
    	    map = seedCache;

    	  while (i--) {
    	    seed = seeds[i];
    	    target = map.get(seed);

    	    target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));

    	    map = target;
    	  }

    	  return target;
    	};

    	getFetch();

    	/**
    	 * Known adapters mapping.
    	 * Provides environment-specific adapters for Axios:
    	 * - `http` for Node.js
    	 * - `xhr` for browsers
    	 * - `fetch` for fetch API-based requests
    	 *
    	 * @type {Object<string, Function|Object>}
    	 */
    	const knownAdapters = {
    	  http: httpAdapter,
    	  xhr: xhrAdapter,
    	  fetch: {
    	    get: getFetch,
    	  },
    	};

    	// Assign adapter names for easier debugging and identification
    	utils$1.forEach(knownAdapters, (fn, value) => {
    	  if (fn) {
    	    try {
    	      // Null-proto descriptors so a polluted Object.prototype.get cannot turn
    	      // these data descriptors into accessor descriptors on the way in.
    	      Object.defineProperty(fn, 'name', { __proto__: null, value });
    	    } catch (e) {
    	      // eslint-disable-next-line no-empty
    	    }
    	    Object.defineProperty(fn, 'adapterName', { __proto__: null, value });
    	  }
    	});

    	/**
    	 * Render a rejection reason string for unknown or unsupported adapters
    	 *
    	 * @param {string} reason
    	 * @returns {string}
    	 */
    	const renderReason = (reason) => `- ${reason}`;

    	/**
    	 * Check if the adapter is resolved (function, null, or false)
    	 *
    	 * @param {Function|null|false} adapter
    	 * @returns {boolean}
    	 */
    	const isResolvedHandle = (adapter) =>
    	  utils$1.isFunction(adapter) || adapter === null || adapter === false;

    	/**
    	 * Get the first suitable adapter from the provided list.
    	 * Tries each adapter in order until a supported one is found.
    	 * Throws an AxiosError if no adapter is suitable.
    	 *
    	 * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
    	 * @param {Object} config - Axios request configuration
    	 * @throws {AxiosError} If no suitable adapter is available
    	 * @returns {Function} The resolved adapter function
    	 */
    	function getAdapter(adapters, config) {
    	  adapters = utils$1.isArray(adapters) ? adapters : [adapters];

    	  const { length } = adapters;
    	  let nameOrAdapter;
    	  let adapter;

    	  const rejectedReasons = {};

    	  for (let i = 0; i < length; i++) {
    	    nameOrAdapter = adapters[i];
    	    let id;

    	    adapter = nameOrAdapter;

    	    if (!isResolvedHandle(nameOrAdapter)) {
    	      adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];

    	      if (adapter === undefined) {
    	        throw new AxiosError(`Unknown adapter '${id}'`);
    	      }
    	    }

    	    if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
    	      break;
    	    }

    	    rejectedReasons[id || '#' + i] = adapter;
    	  }

    	  if (!adapter) {
    	    const reasons = Object.entries(rejectedReasons).map(
    	      ([id, state]) =>
    	        `adapter ${id} ` +
    	        (state === false ? 'is not supported by the environment' : 'is not available in the build')
    	    );

    	    let s = length
    	      ? reasons.length > 1
    	        ? 'since :\n' + reasons.map(renderReason).join('\n')
    	        : ' ' + renderReason(reasons[0])
    	      : 'as no adapter specified';

    	    throw new AxiosError(
    	      `There is no suitable adapter to dispatch the request ` + s,
    	      'ERR_NOT_SUPPORT'
    	    );
    	  }

    	  return adapter;
    	}

    	/**
    	 * Exports Axios adapters and utility to resolve an adapter
    	 */
    	var adapters = {
    	  /**
    	   * Resolve an adapter from a list of adapter names or functions.
    	   * @type {Function}
    	   */
    	  getAdapter,

    	  /**
    	   * Exposes all known adapters
    	   * @type {Object<string, Function|Object>}
    	   */
    	  adapters: knownAdapters,
    	};

    	/**
    	 * Throws a `CanceledError` if cancellation has been requested.
    	 *
    	 * @param {Object} config The config that is to be used for the request
    	 *
    	 * @returns {void}
    	 */
    	function throwIfCancellationRequested(config) {
    	  if (config.cancelToken) {
    	    config.cancelToken.throwIfRequested();
    	  }

    	  if (config.signal && config.signal.aborted) {
    	    throw new CanceledError(null, config);
    	  }
    	}

    	/**
    	 * Dispatch a request to the server using the configured adapter.
    	 *
    	 * @param {object} config The config that is to be used for the request
    	 *
    	 * @returns {Promise} The Promise to be fulfilled
    	 */
    	function dispatchRequest(config) {
    	  throwIfCancellationRequested(config);

    	  config.headers = AxiosHeaders.from(config.headers);

    	  // Transform request data
    	  config.data = transformData.call(config, config.transformRequest);

    	  if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
    	    config.headers.setContentType('application/x-www-form-urlencoded', false);
    	  }

    	  const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);

    	  return adapter(config).then(
    	    function onAdapterResolution(response) {
    	      throwIfCancellationRequested(config);

    	      // Expose the current response on config so that transformResponse can
    	      // attach it to any AxiosError it throws (e.g. on JSON parse failure).
    	      // We clean it up afterwards to avoid polluting the config object.
    	      config.response = response;
    	      try {
    	        response.data = transformData.call(config, config.transformResponse, response);
    	      } finally {
    	        delete config.response;
    	      }

    	      response.headers = AxiosHeaders.from(response.headers);

    	      return response;
    	    },
    	    function onAdapterRejection(reason) {
    	      if (!isCancel(reason)) {
    	        throwIfCancellationRequested(config);

    	        // Transform response data
    	        if (reason && reason.response) {
    	          config.response = reason.response;
    	          try {
    	            reason.response.data = transformData.call(
    	              config,
    	              config.transformResponse,
    	              reason.response
    	            );
    	          } finally {
    	            delete config.response;
    	          }
    	          reason.response.headers = AxiosHeaders.from(reason.response.headers);
    	        }
    	      }

    	      return Promise.reject(reason);
    	    }
    	  );
    	}

    	const validators$1 = {};

    	// eslint-disable-next-line func-names
    	['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
    	  validators$1[type] = function validator(thing) {
    	    return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
    	  };
    	});

    	const deprecatedWarnings = {};

    	/**
    	 * Transitional option validator
    	 *
    	 * @param {function|boolean?} validator - set to false if the transitional option has been removed
    	 * @param {string?} version - deprecated version / removed since version
    	 * @param {string?} message - some message with additional info
    	 *
    	 * @returns {function}
    	 */
    	validators$1.transitional = function transitional(validator, version, message) {
    	  function formatMessage(opt, desc) {
    	    return (
    	      '[Axios v' +
    	      VERSION +
    	      "] Transitional option '" +
    	      opt +
    	      "'" +
    	      desc +
    	      (message ? '. ' + message : '')
    	    );
    	  }

    	  // eslint-disable-next-line func-names
    	  return (value, opt, opts) => {
    	    if (validator === false) {
    	      throw new AxiosError(
    	        formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
    	        AxiosError.ERR_DEPRECATED
    	      );
    	    }

    	    if (version && !deprecatedWarnings[opt]) {
    	      deprecatedWarnings[opt] = true;
    	      // eslint-disable-next-line no-console
    	      console.warn(
    	        formatMessage(
    	          opt,
    	          ' has been deprecated since v' + version + ' and will be removed in the near future'
    	        )
    	      );
    	    }

    	    return validator ? validator(value, opt, opts) : true;
    	  };
    	};

    	validators$1.spelling = function spelling(correctSpelling) {
    	  return (value, opt) => {
    	    // eslint-disable-next-line no-console
    	    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    	    return true;
    	  };
    	};

    	/**
    	 * Assert object's properties type
    	 *
    	 * @param {object} options
    	 * @param {object} schema
    	 * @param {boolean?} allowUnknown
    	 *
    	 * @returns {object}
    	 */

    	function assertOptions(options, schema, allowUnknown) {
    	  if (typeof options !== 'object') {
    	    throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
    	  }
    	  const keys = Object.keys(options);
    	  let i = keys.length;
    	  while (i-- > 0) {
    	    const opt = keys[i];
    	    // Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
    	    // a non-function validator and cause a TypeError.
    	    const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
    	    if (validator) {
    	      const value = options[opt];
    	      const result = value === undefined || validator(value, opt, options);
    	      if (result !== true) {
    	        throw new AxiosError(
    	          'option ' + opt + ' must be ' + result,
    	          AxiosError.ERR_BAD_OPTION_VALUE
    	        );
    	      }
    	      continue;
    	    }
    	    if (allowUnknown !== true) {
    	      throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
    	    }
    	  }
    	}

    	var validator = {
    	  assertOptions,
    	  validators: validators$1,
    	};

    	const validators = validator.validators;

    	/**
    	 * Create a new instance of Axios
    	 *
    	 * @param {Object} instanceConfig The default config for the instance
    	 *
    	 * @return {Axios} A new instance of Axios
    	 */
    	class Axios {
    	  constructor(instanceConfig) {
    	    this.defaults = instanceConfig || {};
    	    this.interceptors = {
    	      request: new InterceptorManager(),
    	      response: new InterceptorManager(),
    	    };
    	  }

    	  /**
    	   * Dispatch a request
    	   *
    	   * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
    	   * @param {?Object} config
    	   *
    	   * @returns {Promise} The Promise to be fulfilled
    	   */
    	  async request(configOrUrl, config) {
    	    try {
    	      return await this._request(configOrUrl, config);
    	    } catch (err) {
    	      if (err instanceof Error) {
    	        let dummy = {};

    	        Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());

    	        // slice off the Error: ... line
    	        const stack = (() => {
    	          if (!dummy.stack) {
    	            return '';
    	          }

    	          const firstNewlineIndex = dummy.stack.indexOf('\n');

    	          return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
    	        })();
    	        try {
    	          if (!err.stack) {
    	            err.stack = stack;
    	            // match without the 2 top stack lines
    	          } else if (stack) {
    	            const firstNewlineIndex = stack.indexOf('\n');
    	            const secondNewlineIndex =
    	              firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
    	            const stackWithoutTwoTopLines =
    	              secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);

    	            if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
    	              err.stack += '\n' + stack;
    	            }
    	          }
    	        } catch (e) {
    	          // ignore the case where "stack" is an un-writable property
    	        }
    	      }

    	      throw err;
    	    }
    	  }

    	  _request(configOrUrl, config) {
    	    /*eslint no-param-reassign:0*/
    	    // Allow for axios('example/url'[, config]) a la fetch API
    	    if (typeof configOrUrl === 'string') {
    	      config = config || {};
    	      config.url = configOrUrl;
    	    } else {
    	      config = configOrUrl || {};
    	    }

    	    config = mergeConfig(this.defaults, config);

    	    const { transitional, paramsSerializer, headers } = config;

    	    if (transitional !== undefined) {
    	      validator.assertOptions(
    	        transitional,
    	        {
    	          silentJSONParsing: validators.transitional(validators.boolean),
    	          forcedJSONParsing: validators.transitional(validators.boolean),
    	          clarifyTimeoutError: validators.transitional(validators.boolean),
    	          legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
    	          advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
    	          validateStatusUndefinedResolves: validators.transitional(validators.boolean),
    	        },
    	        false
    	      );
    	    }

    	    if (paramsSerializer != null) {
    	      if (utils$1.isFunction(paramsSerializer)) {
    	        config.paramsSerializer = {
    	          serialize: paramsSerializer,
    	        };
    	      } else {
    	        validator.assertOptions(
    	          paramsSerializer,
    	          {
    	            encode: validators.function,
    	            serialize: validators.function,
    	          },
    	          true
    	        );
    	      }
    	    }

    	    // Set config.allowAbsoluteUrls
    	    if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
    	      config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
    	    } else {
    	      config.allowAbsoluteUrls = true;
    	    }

    	    validator.assertOptions(
    	      config,
    	      {
    	        baseUrl: validators.spelling('baseURL'),
    	        withXsrfToken: validators.spelling('withXSRFToken'),
    	      },
    	      true
    	    );

    	    // Set config.method
    	    config.method = (config.method || this.defaults.method || 'get').toLowerCase();

    	    // Flatten headers
    	    let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);

    	    headers &&
    	      utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => {
    	        delete headers[method];
    	      });

    	    config.headers = AxiosHeaders.concat(contextHeaders, headers);

    	    // filter out skipped interceptors
    	    const requestInterceptorChain = [];
    	    let synchronousRequestInterceptors = true;
    	    this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
    	      if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
    	        return;
    	      }

    	      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;

    	      const transitional = config.transitional || transitionalDefaults;
    	      const legacyInterceptorReqResOrdering =
    	        transitional && transitional.legacyInterceptorReqResOrdering;

    	      if (legacyInterceptorReqResOrdering) {
    	        requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
    	      } else {
    	        requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    	      }
    	    });

    	    const responseInterceptorChain = [];
    	    this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
    	      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    	    });

    	    let promise;
    	    let i = 0;
    	    let len;

    	    if (!synchronousRequestInterceptors) {
    	      const chain = [dispatchRequest.bind(this), undefined];
    	      chain.unshift(...requestInterceptorChain);
    	      chain.push(...responseInterceptorChain);
    	      len = chain.length;

    	      promise = Promise.resolve(config);

    	      while (i < len) {
    	        promise = promise.then(chain[i++], chain[i++]);
    	      }

    	      return promise;
    	    }

    	    len = requestInterceptorChain.length;

    	    let newConfig = config;

    	    while (i < len) {
    	      const onFulfilled = requestInterceptorChain[i++];
    	      const onRejected = requestInterceptorChain[i++];
    	      try {
    	        newConfig = onFulfilled(newConfig);
    	      } catch (error) {
    	        onRejected.call(this, error);
    	        break;
    	      }
    	    }

    	    try {
    	      promise = dispatchRequest.call(this, newConfig);
    	    } catch (error) {
    	      return Promise.reject(error);
    	    }

    	    i = 0;
    	    len = responseInterceptorChain.length;

    	    while (i < len) {
    	      promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
    	    }

    	    return promise;
    	  }

    	  getUri(config) {
    	    config = mergeConfig(this.defaults, config);
    	    const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
    	    return buildURL(fullPath, config.params, config.paramsSerializer);
    	  }
    	}

    	// Provide aliases for supported request methods
    	utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
    	  /*eslint func-names:0*/
    	  Axios.prototype[method] = function (url, config) {
    	    return this.request(
    	      mergeConfig(config || {}, {
    	        method,
    	        url,
    	        data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined,
    	      })
    	    );
    	  };
    	});

    	utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
    	  function generateHTTPMethod(isForm) {
    	    return function httpMethod(url, data, config) {
    	      return this.request(
    	        mergeConfig(config || {}, {
    	          method,
    	          headers: isForm
    	            ? {
    	                'Content-Type': 'multipart/form-data',
    	              }
    	            : {},
    	          url,
    	          data,
    	        })
    	      );
    	    };
    	  }

    	  Axios.prototype[method] = generateHTTPMethod();

    	  // QUERY is a safe/idempotent read method; multipart form bodies don't fit
    	  // its semantics, so no queryForm shorthand is generated.
    	  if (method !== 'query') {
    	    Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
    	  }
    	});

    	/**
    	 * A `CancelToken` is an object that can be used to request cancellation of an operation.
    	 *
    	 * @param {Function} executor The executor function.
    	 *
    	 * @returns {CancelToken}
    	 */
    	class CancelToken {
    	  constructor(executor) {
    	    if (typeof executor !== 'function') {
    	      throw new TypeError('executor must be a function.');
    	    }

    	    let resolvePromise;

    	    this.promise = new Promise(function promiseExecutor(resolve) {
    	      resolvePromise = resolve;
    	    });

    	    const token = this;

    	    // eslint-disable-next-line func-names
    	    this.promise.then((cancel) => {
    	      if (!token._listeners) return;

    	      let i = token._listeners.length;

    	      while (i-- > 0) {
    	        token._listeners[i](cancel);
    	      }
    	      token._listeners = null;
    	    });

    	    // eslint-disable-next-line func-names
    	    this.promise.then = (onfulfilled) => {
    	      let _resolve;
    	      // eslint-disable-next-line func-names
    	      const promise = new Promise((resolve) => {
    	        token.subscribe(resolve);
    	        _resolve = resolve;
    	      }).then(onfulfilled);

    	      promise.cancel = function reject() {
    	        token.unsubscribe(_resolve);
    	      };

    	      return promise;
    	    };

    	    executor(function cancel(message, config, request) {
    	      if (token.reason) {
    	        // Cancellation has already been requested
    	        return;
    	      }

    	      token.reason = new CanceledError(message, config, request);
    	      resolvePromise(token.reason);
    	    });
    	  }

    	  /**
    	   * Throws a `CanceledError` if cancellation has been requested.
    	   */
    	  throwIfRequested() {
    	    if (this.reason) {
    	      throw this.reason;
    	    }
    	  }

    	  /**
    	   * Subscribe to the cancel signal
    	   */

    	  subscribe(listener) {
    	    if (this.reason) {
    	      listener(this.reason);
    	      return;
    	    }

    	    if (this._listeners) {
    	      this._listeners.push(listener);
    	    } else {
    	      this._listeners = [listener];
    	    }
    	  }

    	  /**
    	   * Unsubscribe from the cancel signal
    	   */

    	  unsubscribe(listener) {
    	    if (!this._listeners) {
    	      return;
    	    }
    	    const index = this._listeners.indexOf(listener);
    	    if (index !== -1) {
    	      this._listeners.splice(index, 1);
    	    }
    	  }

    	  toAbortSignal() {
    	    const controller = new AbortController();

    	    const abort = (err) => {
    	      controller.abort(err);
    	    };

    	    this.subscribe(abort);

    	    controller.signal.unsubscribe = () => this.unsubscribe(abort);

    	    return controller.signal;
    	  }

    	  /**
    	   * Returns an object that contains a new `CancelToken` and a function that, when called,
    	   * cancels the `CancelToken`.
    	   */
    	  static source() {
    	    let cancel;
    	    const token = new CancelToken(function executor(c) {
    	      cancel = c;
    	    });
    	    return {
    	      token,
    	      cancel,
    	    };
    	  }
    	}

    	/**
    	 * Syntactic sugar for invoking a function and expanding an array for arguments.
    	 *
    	 * Common use case would be to use `Function.prototype.apply`.
    	 *
    	 *  ```js
    	 *  function f(x, y, z) {}
    	 *  const args = [1, 2, 3];
    	 *  f.apply(null, args);
    	 *  ```
    	 *
    	 * With `spread` this example can be re-written.
    	 *
    	 *  ```js
    	 *  spread(function(x, y, z) {})([1, 2, 3]);
    	 *  ```
    	 *
    	 * @param {Function} callback
    	 *
    	 * @returns {Function}
    	 */
    	function spread(callback) {
    	  return function wrap(arr) {
    	    return callback.apply(null, arr);
    	  };
    	}

    	/**
    	 * Determines whether the payload is an error thrown by Axios
    	 *
    	 * @param {*} payload The value to test
    	 *
    	 * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
    	 */
    	function isAxiosError(payload) {
    	  return utils$1.isObject(payload) && payload.isAxiosError === true;
    	}

    	const HttpStatusCode = {
    	  Continue: 100,
    	  SwitchingProtocols: 101,
    	  Processing: 102,
    	  EarlyHints: 103,
    	  Ok: 200,
    	  Created: 201,
    	  Accepted: 202,
    	  NonAuthoritativeInformation: 203,
    	  NoContent: 204,
    	  ResetContent: 205,
    	  PartialContent: 206,
    	  MultiStatus: 207,
    	  AlreadyReported: 208,
    	  ImUsed: 226,
    	  MultipleChoices: 300,
    	  MovedPermanently: 301,
    	  Found: 302,
    	  SeeOther: 303,
    	  NotModified: 304,
    	  UseProxy: 305,
    	  Unused: 306,
    	  TemporaryRedirect: 307,
    	  PermanentRedirect: 308,
    	  BadRequest: 400,
    	  Unauthorized: 401,
    	  PaymentRequired: 402,
    	  Forbidden: 403,
    	  NotFound: 404,
    	  MethodNotAllowed: 405,
    	  NotAcceptable: 406,
    	  ProxyAuthenticationRequired: 407,
    	  RequestTimeout: 408,
    	  Conflict: 409,
    	  Gone: 410,
    	  LengthRequired: 411,
    	  PreconditionFailed: 412,
    	  PayloadTooLarge: 413,
    	  UriTooLong: 414,
    	  UnsupportedMediaType: 415,
    	  RangeNotSatisfiable: 416,
    	  ExpectationFailed: 417,
    	  ImATeapot: 418,
    	  MisdirectedRequest: 421,
    	  UnprocessableEntity: 422,
    	  Locked: 423,
    	  FailedDependency: 424,
    	  TooEarly: 425,
    	  UpgradeRequired: 426,
    	  PreconditionRequired: 428,
    	  TooManyRequests: 429,
    	  RequestHeaderFieldsTooLarge: 431,
    	  UnavailableForLegalReasons: 451,
    	  InternalServerError: 500,
    	  NotImplemented: 501,
    	  BadGateway: 502,
    	  ServiceUnavailable: 503,
    	  GatewayTimeout: 504,
    	  HttpVersionNotSupported: 505,
    	  VariantAlsoNegotiates: 506,
    	  InsufficientStorage: 507,
    	  LoopDetected: 508,
    	  NotExtended: 510,
    	  NetworkAuthenticationRequired: 511,
    	  WebServerIsDown: 521,
    	  ConnectionTimedOut: 522,
    	  OriginIsUnreachable: 523,
    	  TimeoutOccurred: 524,
    	  SslHandshakeFailed: 525,
    	  InvalidSslCertificate: 526,
    	};

    	Object.entries(HttpStatusCode).forEach(([key, value]) => {
    	  HttpStatusCode[value] = key;
    	});

    	/**
    	 * Create an instance of Axios
    	 *
    	 * @param {Object} defaultConfig The default config for the instance
    	 *
    	 * @returns {Axios} A new instance of Axios
    	 */
    	function createInstance(defaultConfig) {
    	  const context = new Axios(defaultConfig);
    	  const instance = bind(Axios.prototype.request, context);

    	  // Copy axios.prototype to instance
    	  utils$1.extend(instance, Axios.prototype, context, { allOwnKeys: true });

    	  // Copy context to instance
    	  utils$1.extend(instance, context, null, { allOwnKeys: true });

    	  // Factory for creating new instances
    	  instance.create = function create(instanceConfig) {
    	    return createInstance(mergeConfig(defaultConfig, instanceConfig));
    	  };

    	  return instance;
    	}

    	// Create the default instance to be exported
    	const axios = createInstance(defaults);

    	// Expose Axios class to allow class inheritance
    	axios.Axios = Axios;

    	// Expose Cancel & CancelToken
    	axios.CanceledError = CanceledError;
    	axios.CancelToken = CancelToken;
    	axios.isCancel = isCancel;
    	axios.VERSION = VERSION;
    	axios.toFormData = toFormData;

    	// Expose AxiosError class
    	axios.AxiosError = AxiosError;

    	// alias for CanceledError for backward compatibility
    	axios.Cancel = axios.CanceledError;

    	// Expose all/spread
    	axios.all = function all(promises) {
    	  return Promise.all(promises);
    	};

    	axios.spread = spread;

    	// Expose isAxiosError
    	axios.isAxiosError = isAxiosError;

    	// Expose mergeConfig
    	axios.mergeConfig = mergeConfig;

    	axios.AxiosHeaders = AxiosHeaders;

    	axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);

    	axios.getAdapter = adapters.getAdapter;

    	axios.HttpStatusCode = HttpStatusCode;

    	axios.default = axios;

    	axios_1 = axios;
    	
    	return axios_1;
    }

    var axiosExports = /*@__PURE__*/ requireAxios();
    var axios = /*@__PURE__*/getDefaultExportFromCjs(axiosExports);

    /* eslint-disable @typescript-eslint/no-explicit-any */
    function getBaseUrl$D(http) {
        return http.defaults.baseURL?.split('/spaces')[0];
    }
    function get$1f(http, url, config) {
        return http
            .get(url, {
            baseURL: getBaseUrl$D(http),
            ...config,
        })
            .then((response) => response.data, errorHandler);
    }
    function patch$5(http, url, payload, config) {
        return http
            .patch(url, payload, {
            baseURL: getBaseUrl$D(http),
            ...config,
        })
            .then((response) => response.data, errorHandler);
    }
    function post$1(http, url, payload, config) {
        return http
            .post(url, payload, {
            baseURL: getBaseUrl$D(http),
            ...config,
        })
            .then((response) => response.data, errorHandler);
    }
    function put$1(http, url, payload, config) {
        return http
            .put(url, payload, {
            baseURL: getBaseUrl$D(http),
            ...config,
        })
            .then((response) => response.data, errorHandler);
    }
    function del$S(http, url, config) {
        return http
            .delete(url, {
            baseURL: getBaseUrl$D(http),
            ...config,
        })
            .then((response) => response.data, errorHandler);
    }
    function http(http, url, config) {
        return http(url, {
            baseURL: getBaseUrl$D(http),
            ...config,
        }).then((response) => response.data, errorHandler);
    }

    const get$1e = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}`, {
            headers,
        });
    };
    const getMany$$ = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/ai/actions`, {
            params: params.query,
            headers,
        });
    };
    const create$P = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/ai/actions`, data, { headers });
    };
    const update$A = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        const { sys, ...payload } = data;
        return put$1(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}`, payload, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$R = (http, params, headers) => {
        return del$S(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}`, { headers });
    };
    const publish$f = (http, params, rawData, headers) => {
        return put$1(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$f = (http, params, headers) => {
        return del$S(http, `/spaces/${params.spaceId}/ai/actions/${params.aiActionId}/published`, {
            headers,
        });
    };
    const invoke = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/actions/${params.aiActionId}/invoke`, data, { headers, params: params.query });
    };

    var AiAction = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$P,
        del: del$R,
        get: get$1e,
        getMany: getMany$$,
        invoke: invoke,
        publish: publish$f,
        unpublish: unpublish$f,
        update: update$A
    });

    const get$1d = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/actions/${params.aiActionId}/invocations/${params.invocationId}`, { headers });
    };

    var AiActionInvocation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$1d
    });

    const AgentAlphaHeaders = {
        'x-contentful-enable-alpha-feature': 'agents-api',
    };
    const get$1c = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/${params.agentId}`, {
            headers: {
                ...AgentAlphaHeaders,
                ...headers,
            },
        });
    };
    const getMany$_ = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents`, {
            headers: {
                ...AgentAlphaHeaders,
                ...headers,
            },
        });
    };
    const generate = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/${params.agentId}/generate`, data, {
            headers: {
                ...AgentAlphaHeaders,
                ...headers,
            },
        });
    };

    var Agent = /*#__PURE__*/Object.freeze({
        __proto__: null,
        generate: generate,
        get: get$1c,
        getMany: getMany$_
    });

    const AgentRunAlphaHeaders = {
        'x-contentful-enable-alpha-feature': 'agents-api',
    };
    const get$1b = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/runs/${params.runId}`, {
            headers: {
                ...AgentRunAlphaHeaders,
                ...headers,
            },
        });
    };
    const getMany$Z = (http, params, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/runs`, {
            params: params.query,
            headers: {
                ...AgentRunAlphaHeaders,
                ...headers,
            },
        });
    };
    const resumeRun = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/ai/agents/runs/${params.runId}/resume`, data, {
            headers: {
                ...AgentRunAlphaHeaders,
                ...headers,
            },
        });
    };

    var AgentRun = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$1b,
        getMany: getMany$Z,
        resumeRun: resumeRun
    });

    /**
     * Retrieves an access token by its unique token ID for the currently authenticated user.
     *
     * @param {AxiosInstance} http - An Axios HTTP client instance.
     * @param {Object} params - Parameters for the request.
     * @param {string} params.tokenId - The unique token ID of the access token to retrieve.
     * @returns {Promise<AccessTokenProps>} A Promise that resolves with the retrieved access token information.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *   accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.get({tokenId: 'TestTokenTd'})
     *  .then(token => console.log(token))
     *  .catch(console.error)
     * ```
     */
    const get$1a = (http, params) => {
        return get$1f(http, `/users/me/access_tokens/${params.tokenId}`);
    };
    /**
     * Retrieves multiple access tokens associated with the currently authenticated user.
     *
     * @param {AxiosInstance} http - An Axios HTTP client instance.
     * @param {QueryParams} params - Query parameters to filter and customize the request.
     * @returns {Promise<CollectionProp<AccessTokenProps>>} A Promise that resolves with a collection of access token properties.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.getMany()
     *  .then(result => console.log(result.items))
     *  .catch(console.error)
     * ```
     */
    const getMany$Y = (http, params) => {
        return get$1f(http, '/users/me/access_tokens', {
            params: params.query,
        });
    };
    /**
     * Creates a personal access token for the currently authenticated user.
     *
     * @param {AxiosInstance} http - Axios instance for making the HTTP request.
     * @param {Object} _params - Unused parameters (can be an empty object).
     * @param {CreatePersonalAccessTokenProps} rawData - Data for creating the personal access token.
     * @param {RawAxiosRequestHeaders} [headers] - Optional HTTP headers for the request.
     * @returns {Promise<AccessTokenProps>} A Promise that resolves with the created personal access token.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>',
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.createPersonalAccessToken({name: 'Test-Name', scope: ['content_management_manage'], expiresIn: 777596.92})
     *  .then(token => console.log(token))
     *  .catch(console.error)
     * ```
     */
    const createPersonalAccessToken = (http, _params, rawData, headers) => {
        return post$1(http, '/users/me/access_tokens', rawData, {
            headers,
        });
    };
    /**
     * Revokes an access token associated with the currently authenticated user.
     *
     * @param {AxiosInstance} http - The Axios HTTP client instance.
     * @param {Object} params - The parameters for revoking the access token.
     * @param {string} params.tokenId - The unique identifier of the access token to revoke.
     * @returns {Promise<AccessTokenProps>} A Promise that resolves with the updated access token information after revocation.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.revoke({tokenId: 'TestTokenTd'})
     *  .then(token => console.log(token))
     *  .catch(console.error)
     * ```
     */
    const revoke$1 = (http, params) => {
        return put$1(http, `/users/me/access_tokens/${params.tokenId}/revoked`, null);
    };
    /**
     * Retrieves a list of redacted versions of access tokens for an organization, accessible to owners or administrators of an organization.
     *
     * @param {AxiosInstance} http - The Axios HTTP client instance.
     * @param {GetOrganizationParams & QueryParams} params - Parameters for the request, including organization ID and query parameters.
     * @param {string} params.organizationId - The unique identifier of the organization.
     * @returns {Promise<CollectionProp<AccessTokenProps>>} A promise that resolves to a collection of access tokens.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.getManyForOrganization({organizationId: 'OrgId'})
     *  .then(result => console.log(result.items))
     *  .catch(console.error)
     * ```
     */
    const getManyForOrganization$8 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/access_tokens`, {
            params: params.query,
        });
    };

    var AccessToken = /*#__PURE__*/Object.freeze({
        __proto__: null,
        createPersonalAccessToken: createPersonalAccessToken,
        get: get$1a,
        getMany: getMany$Y,
        getManyForOrganization: getManyForOrganization$8,
        revoke: revoke$1
    });

    const getBaseUrl$C = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/automation_definitions`;
    const getAutomationDefinitionUrl = (params) => `${getBaseUrl$C(params)}/${params.automationDefinitionId}`;
    const get$19 = (http, params, headers) => get$1f(http, getAutomationDefinitionUrl(params), {
        headers,
    });
    const getMany$X = (http, params, headers) => get$1f(http, getBaseUrl$C(params), {
        headers,
        params: params.query,
    });
    const create$O = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$C(params), data, {
            headers,
        });
    };
    const update$z = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getAutomationDefinitionUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$Q = (http, params, headers) => {
        return del$S(http, getAutomationDefinitionUrl(params), {
            headers: { 'X-Contentful-Version': params.version, ...headers },
        });
    };

    var AutomationDefinition = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$O,
        del: del$Q,
        get: get$19,
        getMany: getMany$X,
        update: update$z
    });

    const getBaseUrl$B = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/automation_executions`;
    const getAutomationExecutionUrl = (params) => `${getBaseUrl$B(params)}/${params.automationExecutionId}`;
    const getExecutionsByDefinitionUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/automation_definitions/${params.automationDefinitionId}/automation_executions`;
    const get$18 = (http, params, headers) => get$1f(http, getAutomationExecutionUrl(params), {
        headers,
    });
    const getMany$W = (http, params, headers) => get$1f(http, getBaseUrl$B(params), {
        headers,
        params: params.query,
    });
    const getForAutomationDefinition = (http, params, headers) => get$1f(http, getExecutionsByDefinitionUrl(params), {
        headers,
        params: params.query,
    });

    var AutomationExecution = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$18,
        getForAutomationDefinition: getForAutomationDefinition,
        getMany: getMany$W
    });

    const get$17 = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`);
    };
    const getMany$V = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/api_keys`, {
            params: params.query,
        });
    };
    const create$N = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/api_keys`, data, { headers });
    };
    const createWithId$e = (http, params, data, headers) => {
        return put$1(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`, data, {
            headers,
        });
    };
    const update$y = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        if ('accessToken' in data) {
            delete data.accessToken;
        }
        if ('preview_api_key' in data) {
            delete data.preview_api_key;
        }
        if ('policies' in data) {
            delete data.policies;
        }
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$P = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/api_keys/${params.apiKeyId}`);
    };

    var ApiKey = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$N,
        createWithId: createWithId$e,
        del: del$P,
        get: get$17,
        getMany: getMany$V,
        update: update$y
    });

    const create$M = (http, params, data) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/access_tokens`, undefined, { headers: { Authorization: `Bearer ${data.jwt}` } });
    };

    var AppAccessToken = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$M
    });

    function normalizeSelect(query) {
        if (query && query.select && !/sys/i.test(query.select)) {
            return {
                ...query,
                select: query.select + ',sys',
            };
        }
        return query;
    }
    function normalizeSpaceId(query) {
        if (query && query.spaceId) {
            const { spaceId, ...rest } = query;
            return {
                ...rest,
                'sys.space.sys.id[in]': spaceId,
            };
        }
        return query;
    }

    const getBaseUrl$A = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/actions`;
    const getAppActionUrl = (params) => `${getBaseUrl$A(params)}/${params.appActionId}`;
    const getAppActionsEnvUrl = (params) => {
        if (params.environmentId) {
            return `/spaces/${params.spaceId}/environments/${params.environmentId}/actions`;
        }
        return `/spaces/${params.spaceId}/actions`;
    };
    const get$16 = (http, params) => {
        return get$1f(http, getAppActionUrl(params));
    };
    const getMany$U = (http, params) => {
        return get$1f(http, getBaseUrl$A(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getManyForEnvironment$2 = (http, params) => {
        return get$1f(http, getAppActionsEnvUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const del$O = (http, params) => {
        return del$S(http, getAppActionUrl(params));
    };
    const create$L = (http, params, data) => {
        return post$1(http, getBaseUrl$A(params), data);
    };
    const update$x = (http, params, data) => {
        return put$1(http, getAppActionUrl(params), data);
    };

    var AppAction = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$L,
        del: del$O,
        get: get$16,
        getMany: getMany$U,
        getManyForEnvironment: getManyForEnvironment$2,
        update: update$x
    });

    /**
     * @internal
     */
    const wrapCollection = (fn) => (makeRequest, data, ...rest) => {
        const collectionData = toPlainObject(index$2(data));
        // @ts-expect-error toPlainObject adds non-enumerable toPlainObject method that would be lost with spread
        collectionData.items = collectionData.items.map((entity) => fn(makeRequest, entity, ...rest));
        // @ts-expect-error
        return collectionData;
    };
    const wrapCursorPaginatedCollection = (fn) => (makeRequest, data, ...rest) => {
        const collectionData = toPlainObject(index$2(data));
        // @ts-expect-error toPlainObject adds non-enumerable toPlainObject method that would be lost with spread
        collectionData.items = collectionData.items.map((entity) => fn(makeRequest, entity, ...rest));
        // @ts-expect-error
        return collectionData;
    };
    function isSuccessful(statusCode) {
        return statusCode < 300;
    }
    function shouldRePoll(statusCode) {
        return [404, 422, 429, 400].includes(statusCode);
    }
    async function waitFor(ms = 1000) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    function normalizeCursorPaginationParameters(query) {
        const { pagePrev, pageNext, ...rest } = query;
        return {
            ...rest,
            cursor: true,
            // omit pagePrev and pageNext if the value is falsy
            ...(pagePrev ? { pagePrev } : null),
            ...(pageNext ? { pageNext } : null),
        };
    }
    function extractQueryParam(key, url) {
        if (!url)
            return;
        const queryIndex = url.indexOf('?');
        if (queryIndex === -1)
            return;
        const queryString = url.slice(queryIndex + 1);
        return new URLSearchParams(queryString).get(key) ?? undefined;
    }
    const Pages = {
        prev: 'pagePrev',
        next: 'pageNext',
    };
    const PAGE_KEYS = ['prev', 'next'];
    function normalizeCursorPaginationResponse(data) {
        const pages = {};
        for (const key of PAGE_KEYS) {
            const token = extractQueryParam(Pages[key], data.pages?.[key]);
            if (token)
                pages[key] = token;
        }
        return {
            ...data,
            pages,
        };
    }

    const create$K = (http, params, data) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls`, data);
    };
    const getCallDetails$1 = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/actions/${params.appActionId}/calls/${params.callId}`);
    };
    const APP_ACTION_CALL_RETRY_INTERVAL = 2000;
    const APP_ACTION_CALL_RETRIES = 15;
    async function callAppActionResult(http, params, { callId, }) {
        let checkCount = 1;
        const retryInterval = params.retryInterval || APP_ACTION_CALL_RETRY_INTERVAL;
        const retries = params.retries || APP_ACTION_CALL_RETRIES;
        return new Promise((resolve, reject) => {
            const poll = async () => {
                try {
                    const result = await getCallDetails$1(http, { ...params, callId: callId });
                    // The lambda failed or returned a 404, so we shouldn't re-poll anymore
                    if (result?.response?.statusCode && !isSuccessful(result?.response?.statusCode)) {
                        const error = new Error('App action not found or lambda fails');
                        reject(error);
                    }
                    else if (isSuccessful(result.statusCode)) {
                        resolve(result);
                    }
                    // The logs are not ready yet. Continue waiting for them
                    else if (shouldRePoll(result.statusCode) && checkCount < retries) {
                        checkCount++;
                        await waitFor(retryInterval);
                        poll();
                    }
                    // If the response status code is not successful and is not a status code that should be repolled, reject with an error immediately
                    else {
                        const error = new Error('The app action response is taking longer than expected to process.');
                        reject(error);
                    }
                }
                catch (error) {
                    checkCount++;
                    if (checkCount > retries) {
                        reject(new Error('The app action response is taking longer than expected to process.'));
                        return;
                    }
                    // If `appActionCalls.getCallDetails` throws, we re-poll as it might mean that the lambda result is not available in the webhook logs yet
                    await waitFor(retryInterval);
                    poll();
                }
            };
            poll();
        });
    }
    const createWithResponse = async (http, params, data) => {
        const createResponse = await post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls`, data);
        const callId = createResponse.sys.id;
        return callAppActionResult(http, params, { callId });
    };
    // Get structured AppActionCall (status/result/error) via new route that includes app installation context
    const get$15 = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls/${params.callId}`);
    };
    // Get raw AppActionCall response (headers/body) for a completed call
    const getResponse = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls/${params.callId}/response`);
    };
    async function pollStructuredAppActionCall(http, params, { callId }) {
        let checkCount = 1;
        const retryInterval = params.retryInterval || APP_ACTION_CALL_RETRY_INTERVAL;
        const retries = params.retries || APP_ACTION_CALL_RETRIES;
        return new Promise((resolve, reject) => {
            const poll = async () => {
                try {
                    const result = await get$15(http, { ...params, callId });
                    // If backend has not yet written the record, keep polling up to retries
                    // Otherwise, resolve when status is terminal
                    if (result?.sys.status === 'succeeded' || result?.sys.status === 'failed') {
                        resolve(result);
                    }
                    else if (result?.sys.status === 'processing' && checkCount < retries) {
                        checkCount++;
                        await waitFor(retryInterval);
                        poll();
                    }
                    else {
                        // Status not terminal and no more retries
                        reject(new Error('The app action result is taking longer than expected to process.'));
                    }
                }
                catch (error) {
                    checkCount++;
                    if (checkCount > retries) {
                        reject(new Error('The app action result is taking longer than expected to process.'));
                        return;
                    }
                    // Similar to legacy behavior: transient errors (e.g., 404 during propagation) → re-poll
                    await waitFor(retryInterval);
                    poll();
                }
            };
            poll();
        });
    }
    // Create and poll the structured AppActionCall until completion (succeeded/failed)
    const createWithResult = async (http, params, data) => {
        const createResponse = await post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/actions/${params.appActionId}/calls`, data);
        const callId = createResponse.sys.id;
        return pollStructuredAppActionCall(http, params, { callId });
    };

    var AppActionCall = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$K,
        createWithResponse: createWithResponse,
        createWithResult: createWithResult,
        get: get$15,
        getCallDetails: getCallDetails$1,
        getResponse: getResponse
    });

    const getBaseUrl$z = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/app_bundles`;
    const getAppBundleUrl = (params) => `${getBaseUrl$z(params)}/${params.appBundleId}`;
    const get$14 = (http, params) => {
        return get$1f(http, getAppBundleUrl(params));
    };
    const getMany$T = (http, params) => {
        return get$1f(http, getBaseUrl$z(params), {
            params: normalizeSelect(params.query),
        });
    };
    const del$N = (http, params) => {
        return del$S(http, getAppBundleUrl(params));
    };
    const create$J = (http, params, payload) => {
        const { appUploadId, comment, actions, functions } = payload;
        const data = {
            upload: {
                sys: {
                    type: 'Link',
                    linkType: 'AppUpload',
                    id: appUploadId,
                },
            },
            comment,
            actions,
            functions,
        };
        return post$1(http, getBaseUrl$z(params), data);
    };

    var AppBundle = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$J,
        del: del$N,
        get: get$14,
        getMany: getMany$T
    });

    const getBaseUrl$y = (params) => `/organizations/${params.organizationId}/app_definitions`;
    const getAppDefinitionUrl = (params) => getBaseUrl$y(params) + `/${params.appDefinitionId}`;
    const getBaseUrlForOrgInstallations$1 = (params) => `/app_definitions/${params.appDefinitionId}/app_installations`;
    const get$13 = (http, params) => {
        return get$1f(http, getAppDefinitionUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getMany$S = (http, params) => {
        return get$1f(http, getBaseUrl$y(params), {
            params: params.query,
        });
    };
    const create$I = (http, params, rawData) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$y(params), data);
    };
    const update$w = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getAppDefinitionUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$M = (http, params) => {
        return del$S(http, getAppDefinitionUrl(params));
    };
    const getInstallationsForOrg = (http, params) => {
        return get$1f(http, getBaseUrlForOrgInstallations$1(params), {
            params: {
                ...normalizeSpaceId(normalizeSelect(params.query)),
                'sys.organization.sys.id[in]': params.organizationId,
            },
        });
    };

    var AppDefinition = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$I,
        del: del$M,
        get: get$13,
        getAppDefinitionUrl: getAppDefinitionUrl,
        getInstallationsForOrg: getInstallationsForOrg,
        getMany: getMany$S,
        update: update$w
    });

    const get$12 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/details`);
    };
    const upsert$f = (http, params, data) => {
        return put$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/details`, data);
    };
    const del$L = (http, params) => {
        return del$S(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/details`);
    };

    var AppDetails = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$L,
        get: get$12,
        upsert: upsert$f
    });

    const get$11 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/event_subscription`);
    };
    const upsert$e = (http, params, data) => {
        return put$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/event_subscription`, data);
    };
    const del$K = (http, params) => {
        return del$S(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/event_subscription`);
    };

    var AppEventSubscription = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$K,
        get: get$11,
        upsert: upsert$e
    });

    const getBaseUrl$x = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations`;
    const getBaseUrlForOrgInstallations = (params) => `/app_definitions/${params.appDefinitionId}/app_installations`;
    const getAppInstallationUrl = (params) => getBaseUrl$x(params) + `/${params.appDefinitionId}`;
    const get$10 = (http, params) => {
        return get$1f(http, getAppInstallationUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getMany$R = (http, params) => {
        return get$1f(http, getBaseUrl$x(params), {
            params: normalizeSelect(params.query),
        });
    };
    const upsert$d = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getAppInstallationUrl(params), data, {
            headers: {
                ...headers,
                ...(params.acceptAllTerms && {
                    'X-Contentful-Marketplace': 'i-accept-end-user-license-agreement,i-accept-marketplace-terms-of-service,i-accept-privacy-policy',
                }),
            },
        });
    };
    const del$J = (http, params) => {
        return del$S(http, getAppInstallationUrl(params));
    };
    const getForOrganization$3 = (http, params) => {
        return get$1f(http, getBaseUrlForOrgInstallations(params), {
            params: {
                ...normalizeSpaceId(normalizeSelect(params.query)),
                'sys.organization.sys.id[in]': params.organizationId,
            },
        });
    };

    var AppInstallation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$J,
        get: get$10,
        getAppInstallationUrl: getAppInstallationUrl,
        getForOrganization: getForOrganization$3,
        getMany: getMany$R,
        upsert: upsert$d
    });

    const get$$ = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys/${params.fingerprint}`);
    };
    const getMany$Q = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys`);
    };
    const create$H = (http, params, data) => {
        return post$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys`, data);
    };
    const del$I = (http, params) => {
        return del$S(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/keys/${params.fingerprint}`);
    };

    var AppKey = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$H,
        del: del$I,
        get: get$$,
        getMany: getMany$Q
    });

    const create$G = (http, params, data) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appDefinitionId}/signed_requests`, data);
    };

    var AppSignedRequest = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$G
    });

    const get$_ = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/signing_secret`);
    };
    const upsert$c = (http, params, data) => {
        return put$1(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/signing_secret`, data);
    };
    const del$H = (http, params) => {
        return del$S(http, `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/signing_secret`);
    };

    var AppSigningSecret = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$H,
        get: get$_,
        upsert: upsert$c
    });

    /**
     * @internal
     */
    function getUploadHttpClient(http, options) {
        const { hostUpload, defaultHostnameUpload, timeout } = http.httpClientParams;
        const uploadHttp = http.cloneWithNewParams({
            host: hostUpload || defaultHostnameUpload,
            // Using client presets, options or 5 minute default timeout
            timeout: timeout ?? options?.uploadTimeout ?? 300000,
        });
        return uploadHttp;
    }

    const getBaseUrl$w = (params) => `/organizations/${params.organizationId}/app_uploads`;
    const getAppUploadUrl = (params) => `${getBaseUrl$w(params)}/${params.appUploadId}`;
    const get$Z = (http, params) => {
        const httpUpload = getUploadHttpClient(http);
        return get$1f(httpUpload, getAppUploadUrl(params));
    };
    const del$G = (http, params) => {
        const httpUpload = getUploadHttpClient(http);
        return del$S(httpUpload, getAppUploadUrl(params));
    };
    const create$F = (http, params, payload) => {
        const httpUpload = getUploadHttpClient(http);
        const { file } = payload;
        return post$1(httpUpload, getBaseUrl$w(params), file, {
            headers: {
                'Content-Type': 'application/octet-stream',
            },
        });
    };

    var AppUpload = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$F,
        del: del$G,
        get: get$Z
    });

    const getBaseUploadUrl = (params) => {
        const spacePath = `/spaces/${params.spaceId}/uploads`;
        const environmentPath = `/spaces/${params.spaceId}/environments/${params.environmentId}/uploads`;
        const path = params.environmentId ? environmentPath : spacePath;
        return path;
    };
    const getEntityUploadUrl = (params) => {
        const path = getBaseUploadUrl(params);
        return path + `/${params.uploadId}`;
    };
    const create$E = (http, params, data) => {
        const httpUpload = getUploadHttpClient(http);
        const { file } = data;
        if (!file) {
            return Promise.reject(new Error('Unable to locate a file to upload.'));
        }
        const path = getBaseUploadUrl(params);
        return post$1(httpUpload, path, file, {
            headers: {
                'Content-Type': 'application/octet-stream',
            },
        });
    };
    const del$F = (http, params) => {
        const httpUpload = getUploadHttpClient(http);
        const path = getEntityUploadUrl(params);
        return del$S(httpUpload, path);
    };
    const get$Y = (http, params) => {
        const httpUpload = getUploadHttpClient(http);
        const path = getEntityUploadUrl(params);
        return get$1f(httpUpload, path);
    };

    var Upload = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$E,
        del: del$F,
        get: get$Y
    });

    const get$X = (http, params, rawData, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets/${params.assetId}`, {
            params: normalizeSelect(params.query),
            headers: headers ? { ...headers } : undefined,
        });
    };
    const getMany$P = (http, params, rawData, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets`, {
            params: normalizeSelect(params.query),
            headers: headers ? { ...headers } : undefined,
        });
    };
    const update$v = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets/${params.assetId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const create$D = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets`, data, {
            headers,
        });
    };
    const createWithId$d = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/assets/${params.assetId}`, data, {
            headers,
        });
    };
    const createFromFiles$1 = async (http, params, data) => {
        const httpUpload = getUploadHttpClient(http, { uploadTimeout: params.uploadTimeout });
        const { file } = data.fields;
        return Promise.all(Object.keys(file).map(async (locale) => {
            const { contentType, fileName } = file[locale];
            return create$E(httpUpload, params, file[locale]).then((upload) => {
                return {
                    [locale]: {
                        contentType,
                        fileName,
                        uploadFrom: {
                            sys: {
                                type: 'Link',
                                linkType: 'Upload',
                                id: upload.sys.id,
                            },
                        },
                    },
                };
            });
        }))
            .then((uploads) => {
            const file = uploads.reduce((fieldsData, upload) => ({ ...fieldsData, ...upload }), {});
            const asset = {
                ...data,
                fields: {
                    ...data.fields,
                    file,
                },
            };
            return create$D(http, params, asset, {});
        })
            .catch(errorHandler);
    };
    /**
     * Asset processing
     */
    const ASSET_PROCESSING_CHECK_WAIT$1 = 3000;
    const ASSET_PROCESSING_CHECK_RETRIES$1 = 10;
    async function checkIfAssetHasUrl$1(http, params, { resolve, reject, locale, processingCheckWait = ASSET_PROCESSING_CHECK_WAIT$1, processingCheckRetries = ASSET_PROCESSING_CHECK_RETRIES$1, checkCount = 0, }) {
        return get$X(http, params).then((asset) => {
            if (asset.fields.file[locale].url) {
                resolve(asset);
            }
            else if (checkCount === processingCheckRetries) {
                const error = new Error();
                error.name = 'AssetProcessingTimeout';
                error.message = 'Asset is taking longer then expected to process.';
                reject(error);
            }
            else {
                checkCount++;
                setTimeout(() => checkIfAssetHasUrl$1(http, params, {
                    resolve: resolve,
                    reject: reject,
                    locale: locale,
                    checkCount: checkCount,
                    processingCheckWait,
                    processingCheckRetries,
                }), processingCheckWait);
            }
        });
    }
    const processForLocale$1 = async (http, { asset, locale, options: { processingCheckRetries, processingCheckWait } = {}, ...params }) => {
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${asset.sys.release.sys.id}/assets/${asset.sys.id}/files/${locale}/process`, null, {
            headers: {
                'X-Contentful-Version': asset.sys.version,
            },
        })
            .then(() => {
            return new Promise((resolve, reject) => checkIfAssetHasUrl$1(http, {
                spaceId: params.spaceId,
                environmentId: params.environmentId,
                assetId: asset.sys.id,
                releaseId: asset.sys.release.sys.id,
            }, {
                resolve,
                reject,
                locale,
                processingCheckWait,
                processingCheckRetries,
            }));
        });
    };
    const processForAllLocales$1 = async (http, { asset, options = {}, ...params }) => {
        const locales = Object.keys(asset.fields.file || {});
        let mostUpToDateAssetVersion = asset;
        // Let all the locales process
        // Since they all resolve at different times,
        // we need to pick the last resolved value
        // to reflect the most recent state
        const allProcessingLocales = locales.map((locale) => processForLocale$1(http, { ...params, asset, locale, options }).then((result) => {
            // Side effect of always setting the most up to date asset version
            // The last one to call this will be the last one that finished
            // and thus the most up to date
            mostUpToDateAssetVersion = result;
        }));
        return Promise.all(allProcessingLocales).then(() => mostUpToDateAssetVersion);
    };

    var ReleaseAsset = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$D,
        createFromFiles: createFromFiles$1,
        createWithId: createWithId$d,
        get: get$X,
        getMany: getMany$P,
        processForAllLocales: processForAllLocales$1,
        processForLocale: processForLocale$1,
        update: update$v
    });

    const get$W = (http, params, rawData, headers) => {
        if (params.releaseId) {
            return get$X(http, params);
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`, {
            params: normalizeSelect(params.query),
            headers: headers ? { ...headers } : undefined,
        });
    };
    const getPublished$2 = (http, params, rawData, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/public/assets`, {
            params: normalizeSelect(params.query),
            headers: headers ? { ...headers } : undefined,
        });
    };
    const getMany$O = (http, params, rawData, headers) => {
        if (params.releaseId) {
            return getMany$P(http, params);
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`, {
            params: normalizeSelect(params.query),
            headers: headers ? { ...headers } : undefined,
        });
    };
    const getManyWithCursor$2 = (http, params, rawData, headers) => {
        if (params.releaseId) {
            throw new Error('getManyWithCursor is not supported for release-scoped assets');
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`, {
            params: { cursor: true, ...(params.query ?? {}) },
            headers: headers ? { ...headers } : undefined,
        })
            .then(normalizeCursorPaginationResponse);
    };
    const update$u = (http, params, rawData, headers) => {
        if (params.releaseId) {
            return update$v(http, params, rawData, headers ?? {});
        }
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$E = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`);
    };
    const publish$e = (http, params, rawData) => {
        const payload = params.locales?.length ? { add: { fields: { '*': params.locales } } } : null;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`, payload, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const unpublish$e = (http, params, rawData) => {
        if (params.locales?.length) {
            const payload = { remove: { fields: { '*': params.locales } } };
            return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`, payload, {
                headers: {
                    'X-Contentful-Version': rawData?.sys.version,
                },
            });
        }
        else {
            return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`);
        }
    };
    const archive$4 = (http, params) => {
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/archived`);
    };
    const unarchive$5 = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/archived`);
    };
    const create$C = (http, params, rawData) => {
        if (params.releaseId) {
            return create$D(http, params, rawData, {});
        }
        const data = index$2(rawData);
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`, data);
    };
    const createWithId$c = (http, params, rawData) => {
        if (params.releaseId) {
            return createWithId$d(http, params, rawData, {});
        }
        const data = index$2(rawData);
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`, data);
    };
    const createFromFiles = async (http, params, data) => {
        if (params.releaseId) {
            return createFromFiles$1(http, params, data);
        }
        const httpUpload = getUploadHttpClient(http, { uploadTimeout: params.uploadTimeout });
        const { file } = data.fields;
        return Promise.all(Object.keys(file).map(async (locale) => {
            const { contentType, fileName } = file[locale];
            return create$E(httpUpload, params, file[locale]).then((upload) => {
                return {
                    [locale]: {
                        contentType,
                        fileName,
                        uploadFrom: {
                            sys: {
                                type: 'Link',
                                linkType: 'Upload',
                                id: upload.sys.id,
                            },
                        },
                    },
                };
            });
        }))
            .then((uploads) => {
            const file = uploads.reduce((fieldsData, upload) => ({ ...fieldsData, ...upload }), {});
            const asset = {
                ...data,
                fields: {
                    ...data.fields,
                    file,
                },
            };
            return create$C(http, params, asset);
        })
            .catch(errorHandler);
    };
    /**
     * Asset processing
     */
    const ASSET_PROCESSING_CHECK_WAIT = 3000;
    const ASSET_PROCESSING_CHECK_RETRIES = 10;
    async function checkIfAssetHasUrl(http, params, { resolve, reject, locale, processingCheckWait = ASSET_PROCESSING_CHECK_WAIT, processingCheckRetries = ASSET_PROCESSING_CHECK_RETRIES, checkCount = 0, }) {
        return get$W(http, params).then((asset) => {
            if (asset.fields.file[locale].url) {
                resolve(asset);
            }
            else if (checkCount === processingCheckRetries) {
                const error = new Error();
                error.name = 'AssetProcessingTimeout';
                error.message = 'Asset is taking longer then expected to process.';
                reject(error);
            }
            else {
                checkCount++;
                setTimeout(() => checkIfAssetHasUrl(http, params, {
                    resolve: resolve,
                    reject: reject,
                    locale: locale,
                    checkCount: checkCount,
                    processingCheckWait,
                    processingCheckRetries,
                }), processingCheckWait);
            }
        });
    }
    const processForLocale = async (http, { asset, locale, options: { processingCheckRetries, processingCheckWait } = {}, ...params }) => {
        if (asset.sys.release) {
            return processForLocale$1(http, {
                asset: asset,
                locale,
                options: { processingCheckRetries, processingCheckWait },
                ...params,
            });
        }
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${asset.sys.id}/files/${locale}/process`, null, {
            headers: {
                'X-Contentful-Version': asset.sys.version,
            },
        })
            .then(() => {
            return new Promise((resolve, reject) => checkIfAssetHasUrl(http, {
                spaceId: params.spaceId,
                environmentId: params.environmentId,
                assetId: asset.sys.id,
            }, {
                resolve,
                reject,
                locale,
                processingCheckWait,
                processingCheckRetries,
            }));
        });
    };
    const processForAllLocales = async (http, { asset, options = {}, ...params }) => {
        if (asset.sys.release) {
            return processForAllLocales$1(http, {
                asset: asset,
                options,
                ...params,
            });
        }
        const locales = Object.keys(asset.fields.file || {});
        let mostUpToDateAssetVersion = asset;
        // Let all the locales process
        // Since they all resolve at different times,
        // we need to pick the last resolved value
        // to reflect the most recent state
        const allProcessingLocales = locales.map((locale) => processForLocale(http, { ...params, asset, locale, options }).then((result) => {
            // Side effect of always setting the most up to date asset version
            // The last one to call this will be the last one that finished
            // and thus the most up to date
            mostUpToDateAssetVersion = result;
        }));
        return Promise.all(allProcessingLocales).then(() => mostUpToDateAssetVersion);
    };

    var Asset = /*#__PURE__*/Object.freeze({
        __proto__: null,
        archive: archive$4,
        create: create$C,
        createFromFiles: createFromFiles,
        createWithId: createWithId$c,
        del: del$E,
        get: get$W,
        getMany: getMany$O,
        getManyWithCursor: getManyWithCursor$2,
        getPublished: getPublished$2,
        processForAllLocales: processForAllLocales,
        processForLocale: processForLocale,
        publish: publish$e,
        unarchive: unarchive$5,
        unpublish: unpublish$e,
        update: update$u
    });

    const ASSET_KEY_MAX_LIFETIME = 48 * 60 * 60;
    class ValidationError extends Error {
        constructor(name, message) {
            super(`Invalid "${name}" provided, ` + message);
            this.name = 'ValidationError';
        }
    }
    const validateTimestamp = (name, timestamp, options) => {
        options = options || {};
        if (typeof timestamp !== 'number') {
            throw new ValidationError(name, `only numeric values are allowed for timestamps, provided type was "${typeof timestamp}"`);
        }
        if (options.maximum && timestamp > options.maximum) {
            throw new ValidationError(name, `value (${timestamp}) cannot be further in the future than expected maximum (${options.maximum})`);
        }
        if (options.now && timestamp < options.now) {
            throw new ValidationError(name, `value (${timestamp}) cannot be in the past, current time was ${options.now}`);
        }
    };
    const create$B = (http, params, data) => {
        const expiresAt = data.expiresAt;
        const now = Math.floor(Date.now() / 1000);
        const currentMaxLifetime = now + ASSET_KEY_MAX_LIFETIME;
        validateTimestamp('expiresAt', expiresAt, { maximum: currentMaxLifetime, now });
        const postParams = { expiresAt };
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/asset_keys`, postParams);
    };

    var AssetKey = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ValidationError: ValidationError,
        create: create$B
    });

    const getBaseUrl$v = (params) => `/organizations/${params.organizationId}/available_licenses`;
    const getMany$N = (http, params) => {
        return get$1f(http, getBaseUrl$v(params), {
            params: params.query,
        });
    };

    var AvailableLicense = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getMany: getMany$N
    });

    const get$V = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions/actions/${params.bulkActionId}`);
    };
    const publish$d = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions/publish`, payload);
    };
    const unpublish$d = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions/unpublish`, payload);
    };
    const validate$2 = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions/validate`, payload);
    };
    const getV2 = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions/${params.bulkActionId}`);
    };
    const publishV2 = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions`, payload);
    };
    const unpublishV2 = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions`, payload);
    };
    const validateV2 = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/bulk_actions`, payload);
    };

    var BulkAction = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$V,
        getV2: getV2,
        publish: publish$d,
        publishV2: publishV2,
        unpublish: unpublish$d,
        unpublishV2: unpublishV2,
        validate: validate$2,
        validateV2: validateV2
    });

    const VERSION_HEADER = 'X-Contentful-Version';
    const BODY_FORMAT_HEADER = 'x-contentful-comment-body-format';
    const PARENT_ENTITY_REFERENCE_HEADER = 'x-contentful-parent-entity-reference';
    const PARENT_COMMENT_ID_HEADER = 'x-contentful-parent-id';
    const getSpaceEnvBaseUrl$1 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}`;
    const getEntityCommentUrl = (params) => `${getEntityBaseUrl(params)}/${params.commentId}`;
    function getParentPlural$1(parentEntityType) {
        switch (parentEntityType) {
            case 'ContentType':
                return 'content_types';
            case 'Entry':
                return 'entries';
            case 'Workflow':
                return 'workflows';
            case 'Experience':
                return 'experiences';
            case 'ExperienceFragment':
                return 'experience_fragments';
            case 'Component':
                return 'components';
            case 'ExperienceTemplate':
                return 'experience_templates';
        }
    }
    /**
     * Comments can be added to a content type, an entry, a workflow, or ExO entities. Workflow comments requires a version
     * to be set as part of the URL path for versioned operations. Workflow comments only support `create` (with
     * versionized URL) and `getMany` (without version). The API might support more methods
     * in the future with new use cases being discovered.
     */
    const getEntityBaseUrl = (paramsOrg) => {
        const params = 'entryId' in paramsOrg
            ? {
                spaceId: paramsOrg.spaceId,
                environmentId: paramsOrg.environmentId,
                parentEntityType: 'Entry',
                parentEntityId: paramsOrg.entryId,
            }
            : paramsOrg;
        const { parentEntityId, parentEntityType } = params;
        const parentPlural = getParentPlural$1(parentEntityType);
        const versionPath = 'parentEntityVersion' in params ? `/versions/${params.parentEntityVersion}` : '';
        return `${getSpaceEnvBaseUrl$1(params)}/${parentPlural}/${parentEntityId}${versionPath}/comments`;
    };
    const get$U = (http, params) => get$1f(http, getEntityCommentUrl(params), {
        headers: params.bodyFormat === 'rich-text'
            ? {
                [BODY_FORMAT_HEADER]: params.bodyFormat,
            }
            : {},
    });
    const getMany$M = (http, params) => get$1f(http, getEntityBaseUrl(params), {
        params: normalizeSelect(params.query),
        headers: params.bodyFormat === 'rich-text'
            ? {
                [BODY_FORMAT_HEADER]: params.bodyFormat,
            }
            : {},
    });
    const create$A = (http, params, rawData) => {
        const data = index$2(rawData);
        return post$1(http, getEntityBaseUrl(params), data, {
            headers: {
                ...(typeof rawData.body !== 'string' ? { [BODY_FORMAT_HEADER]: 'rich-text' } : {}),
                ...('parentEntityReference' in params && params.parentEntityReference
                    ? { [PARENT_ENTITY_REFERENCE_HEADER]: params.parentEntityReference }
                    : {}),
                ...(params.parentCommentId ? { [PARENT_COMMENT_ID_HEADER]: params.parentCommentId } : {}),
            },
        });
    };
    const update$t = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getEntityCommentUrl(params), data, {
            headers: {
                [VERSION_HEADER]: rawData.sys.version ?? 0,
                ...(typeof rawData.body !== 'string' ? { [BODY_FORMAT_HEADER]: 'rich-text' } : {}),
                ...headers,
            },
        });
    };
    const del$D = (http, { version, ...params }) => {
        return del$S(http, getEntityCommentUrl(params), {
            headers: { [VERSION_HEADER]: version },
        });
    };
    // Add a deprecation notice. But `getAll` may never be removed for app compatibility reasons.
    /**
     * @deprecated use `getMany` instead.
     */
    const getAll$1 = getMany$M;

    var Comment = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$A,
        del: del$D,
        get: get$U,
        getAll: getAll$1,
        getMany: getMany$M,
        update: update$t
    });

    const getBaseUrl$u = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/components`;
    const getMany$L = (http, params, headers) => {
        return get$1f(http, getBaseUrl$u(params), {
            params: params.query,
            headers,
        });
    };
    const get$T = (http, params, headers) => {
        return get$1f(http, getBaseUrl$u(params) + `/${params.componentId}`, {
            headers,
        });
    };
    const create$z = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$u(params), data, { headers });
    };
    const upsert$b = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$u(params) + `/${params.componentId}`, body, {
            headers: {
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$C = (http, params) => {
        return del$S(http, getBaseUrl$u(params) + `/${params.componentId}`);
    };
    const publish$c = (http, params, headers) => {
        return put$1(http, `${getBaseUrl$u(params)}/${params.componentId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$c = (http, params, headers) => {
        return del$S(http, `${getBaseUrl$u(params)}/${params.componentId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var Component = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$z,
        del: del$C,
        get: get$T,
        getMany: getMany$L,
        publish: publish$c,
        unpublish: unpublish$c,
        upsert: upsert$b
    });

    const getBaseUrl$t = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/component_types`;
    const getMany$K = (http, params, headers) => {
        return get$1f(http, getBaseUrl$t(params), {
            params: params.query,
            headers,
        });
    };
    const get$S = (http, params, headers) => {
        return get$1f(http, getBaseUrl$t(params) + `/${params.componentTypeId}`, {
            headers,
        });
    };
    const create$y = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$t(params), data, { headers });
    };
    const upsert$a = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$t(params) + `/${params.componentTypeId}`, body, {
            headers: {
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$B = (http, params) => {
        return del$S(http, getBaseUrl$t(params) + `/${params.componentTypeId}`);
    };
    const publish$b = (http, params, headers) => {
        return put$1(http, `${getBaseUrl$t(params)}/${params.componentTypeId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$b = (http, params, headers) => {
        return del$S(http, `${getBaseUrl$t(params)}/${params.componentTypeId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var ComponentType = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$y,
        del: del$B,
        get: get$S,
        getMany: getMany$K,
        publish: publish$b,
        unpublish: unpublish$b,
        upsert: upsert$a
    });

    function basePath$1(organizationId) {
        return `/organizations/${organizationId}/taxonomy/concepts`;
    }
    const create$x = (http, params, data) => {
        return post$1(http, basePath$1(params.organizationId), data);
    };
    const createWithId$b = (http, params, data) => {
        return put$1(http, `${basePath$1(params.organizationId)}/${params.conceptId}`, data);
    };
    const patch$4 = (http, params, data, headers) => {
        return patch$5(http, `${basePath$1(params.organizationId)}/${params.conceptId}`, data, {
            headers: {
                'X-Contentful-Version': params.version,
                'Content-Type': 'application/json-patch+json',
                ...headers,
            },
        });
    };
    const update$s = (http, params, data, headers) => {
        return put$1(http, `${basePath$1(params.organizationId)}/${params.conceptId}`, data, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const get$R = (http, params) => get$1f(http, `${basePath$1(params.organizationId)}/${params.conceptId}`);
    const del$A = (http, params, headers) => del$S(http, `${basePath$1(params.organizationId)}/${params.conceptId}`, {
        headers: {
            'X-Contentful-Version': params.version ?? 0,
            ...headers,
        },
    });
    const getMany$J = (http, params) => {
        const { url, queryParams } = cursorBasedCollection('', params);
        return get$1f(http, url, {
            params: queryParams,
        });
    };
    const getDescendants = (http, params) => {
        const { url, queryParams } = cursorBasedCollection(`/${params.conceptId}/descendants`, params);
        return get$1f(http, url, { params: queryParams });
    };
    const getAncestors = (http, params) => {
        const { url, queryParams } = cursorBasedCollection(`/${params.conceptId}/ancestors`, params);
        return get$1f(http, url, { params: queryParams });
    };
    const getTotal$1 = (http, params) => get$1f(http, `${basePath$1(params.organizationId)}/total`);
    function cursorBasedCollection(path, params) {
        return params.query?.pageUrl
            ? { url: params.query?.pageUrl }
            : {
                url: `${basePath$1(params.organizationId)}${path}`,
                queryParams: params.query,
            };
    }

    var Concept = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$x,
        createWithId: createWithId$b,
        del: del$A,
        get: get$R,
        getAncestors: getAncestors,
        getDescendants: getDescendants,
        getMany: getMany$J,
        getTotal: getTotal$1,
        patch: patch$4,
        update: update$s
    });

    function basePath(orgId) {
        return `/organizations/${orgId}/taxonomy/concept-schemes`;
    }
    const get$Q = (http, params) => get$1f(http, `${basePath(params.organizationId)}/${params.conceptSchemeId}`);
    const del$z = (http, params, headers) => del$S(http, `${basePath(params.organizationId)}/${params.conceptSchemeId}`, {
        headers: {
            'X-Contentful-Version': params.version,
            ...headers,
        },
    });
    const getMany$I = (http, params) => {
        const url = params.query?.pageUrl ?? basePath(params.organizationId);
        return get$1f(http, url, {
            params: params.query?.pageUrl ? undefined : params.query,
        });
    };
    const getTotal = (http, params) => get$1f(http, `${basePath(params.organizationId)}/total`);
    const create$w = (http, params, data) => {
        return post$1(http, basePath(params.organizationId), data);
    };
    const createWithId$a = (http, params, data) => {
        return put$1(http, `${basePath(params.organizationId)}/${params.conceptSchemeId}`, data);
    };
    const patch$3 = (http, params, data, headers) => {
        return patch$5(http, `${basePath(params.organizationId)}/${params.conceptSchemeId}`, data, {
            headers: {
                'X-Contentful-Version': params.version,
                'Content-Type': 'application/json-patch+json',
                ...headers,
            },
        });
    };
    const update$r = (http, params, data, headers) => {
        return put$1(http, `${basePath(params.organizationId)}/${params.conceptSchemeId}`, data, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var ConceptScheme = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$w,
        createWithId: createWithId$a,
        del: del$z,
        get: get$Q,
        getMany: getMany$I,
        getTotal: getTotal,
        patch: patch$3,
        update: update$r
    });

    const getBaseUrl$s = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/content_types`;
    const getContentTypeUrl$1 = (params) => getBaseUrl$s(params) + `/${params.contentTypeId}`;
    const get$P = (http, params, headers) => {
        return get$1f(http, getContentTypeUrl$1(params), {
            params: normalizeSelect(params.query),
            headers,
        });
    };
    const getMany$H = (http, params, headers) => {
        return get$1f(http, getBaseUrl$s(params), {
            params: params.query,
            headers,
        });
    };
    const getManyWithCursor$1 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$s(params), {
            params: { cursor: true, ...(params.query ?? {}) },
            headers,
        })
            .then(normalizeCursorPaginationResponse);
    };
    const create$v = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$s(params), data, { headers });
    };
    const createWithId$9 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getContentTypeUrl$1(params), data, { headers });
    };
    const update$q = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getContentTypeUrl$1(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$y = (http, params, headers) => {
        return del$S(http, getContentTypeUrl$1(params), { headers });
    };
    const publish$a = (http, params, rawData, headers) => {
        return put$1(http, getContentTypeUrl$1(params) + '/published', null, {
            headers: {
                'X-Contentful-Version': rawData.sys.version,
                ...headers,
            },
        });
    };
    const unpublish$a = (http, params, headers) => {
        return del$S(http, getContentTypeUrl$1(params) + '/published', { headers });
    };

    var ContentType = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$v,
        createWithId: createWithId$9,
        del: del$y,
        get: get$P,
        getMany: getMany$H,
        getManyWithCursor: getManyWithCursor$1,
        publish: publish$a,
        unpublish: unpublish$a,
        update: update$q
    });

    const getBaseUrl$r = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/data_assemblies`;
    const getPublicUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/public/data_assemblies`;
    const getMany$G = (http, params, headers) => {
        return get$1f(http, getBaseUrl$r(params), {
            params: params.query,
            headers,
        });
    };
    const get$O = (http, params, headers) => {
        return get$1f(http, getBaseUrl$r(params) + `/${params.dataAssemblyId}`, {
            headers,
        });
    };
    const create$u = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$r(params), data, { headers });
    };
    const update$p = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getBaseUrl$r(params) + `/${params.dataAssemblyId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$x = (http, params) => {
        return del$S(http, getBaseUrl$r(params) + `/${params.dataAssemblyId}`);
    };
    const publish$9 = (http, params, headers) => {
        return put$1(http, `${getBaseUrl$r(params)}/${params.dataAssemblyId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const getPublished$1 = (http, params, headers) => {
        return get$1f(http, getPublicUrl(params) + `/${params.dataAssemblyId}`, {
            headers,
        });
    };
    const getManyPublished = (http, params, headers) => {
        return get$1f(http, getPublicUrl(params), {
            params: params.query,
            headers,
        });
    };
    const unpublish$9 = (http, params, headers) => {
        return del$S(http, `${getBaseUrl$r(params)}/${params.dataAssemblyId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var DataAssembly = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$u,
        del: del$x,
        get: get$O,
        getMany: getMany$G,
        getManyPublished: getManyPublished,
        getPublished: getPublished$1,
        publish: publish$9,
        unpublish: unpublish$9,
        update: update$p
    });

    const getBaseUrl$q = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/design_tokens`;
    const getMany$F = (http, params, headers) => {
        return get$1f(http, getBaseUrl$q(params), {
            params: params.query,
            headers,
        });
    };
    const get$N = (http, params, headers) => {
        return get$1f(http, getBaseUrl$q(params) + `/${params.designTokenId}`, {
            headers,
        });
    };
    const upsert$9 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$q(params) + `/${params.designTokenId}`, body, {
            headers: {
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$w = (http, params) => {
        return del$S(http, getBaseUrl$q(params) + `/${params.designTokenId}`);
    };

    var DesignToken = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$w,
        get: get$N,
        getMany: getMany$F,
        upsert: upsert$9
    });

    const getBaseUrl$p = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/content_types/${params.contentTypeId}/editor_interface`;
    const get$M = (http, params) => {
        return get$1f(http, getBaseUrl$p(params));
    };
    const getMany$E = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/editor_interfaces`);
    };
    const update$o = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getBaseUrl$p(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };

    var EditorInterface = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$M,
        getMany: getMany$E,
        update: update$o
    });

    const getBaseUrl$o = (params) => `/spaces/${params.spaceId}/eligible_licenses`;
    const getMany$D = (http, params) => {
        return get$1f(http, getBaseUrl$o(params), {
            params: params.query,
        });
    };

    var EligibleLicense = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getMany: getMany$D
    });

    const get$L = (http, params, rawData, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/entries/${params.entryId}`, {
            params: normalizeSelect(params.query),
            headers: { ...headers },
        });
    };
    const getMany$C = (http, params, rawData, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/entries`, {
            params: normalizeSelect(params.query),
            headers: { ...headers },
        });
    };
    const update$n = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/entries/${params.entryId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const patch$2 = (http, params, data, headers) => {
        return patch$5(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/entries/${params.entryId}`, data, {
            headers: {
                'X-Contentful-Version': params.version,
                'Content-Type': 'application/json-patch+json',
                ...headers,
            },
        });
    };
    const create$t = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/entries`, data, {
            headers: {
                'X-Contentful-Content-Type': params.contentTypeId,
                ...headers,
            },
        });
    };
    const createWithId$8 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/entries/${params.entryId}`, data, {
            headers: {
                'X-Contentful-Content-Type': params.contentTypeId,
                ...headers,
            },
        });
    };

    var ReleaseEntry = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$t,
        createWithId: createWithId$8,
        get: get$L,
        getMany: getMany$C,
        patch: patch$2,
        update: update$n
    });

    const get$K = (http, params, rawData, headers) => {
        if (params.releaseId) {
            return get$L(http, params);
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}`, {
            params: normalizeSelect(params.query),
            headers: { ...headers },
        });
    };
    const getPublished = (http, params, rawData, headers) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/public/entries`, {
            params: normalizeSelect(params.query),
            headers: { ...headers },
        });
    };
    const getMany$B = (http, params, rawData, headers) => {
        if (params.releaseId) {
            return getMany$C(http, params);
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries`, {
            params: normalizeSelect(params.query),
            headers: { ...headers },
        });
    };
    const getManyWithCursor = (http, params, rawData, headers) => {
        if (params.releaseId) {
            throw new Error('getManyWithCursor is not supported for release-scoped entries');
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries`, {
            params: { cursor: true, ...(params.query ?? {}) },
            headers: { ...headers },
        })
            .then(normalizeCursorPaginationResponse);
    };
    const patch$1 = (http, params, data, headers) => {
        if (params.releaseId) {
            return patch$2(http, params, data, headers ?? {});
        }
        return patch$5(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}`, data, {
            headers: {
                'X-Contentful-Version': params.version,
                'Content-Type': 'application/json-patch+json',
                ...headers,
            },
        });
    };
    const update$m = (http, params, rawData, headers) => {
        if (params.releaseId) {
            return update$n(http, params, rawData, headers ?? {});
        }
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$v = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}`);
    };
    const publish$8 = (http, params, rawData) => {
        const payload = params.locales?.length ? { add: { fields: { '*': params.locales } } } : null;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}/published`, payload, {
            headers: {
                'X-Contentful-Version': rawData.sys.version,
            },
        });
    };
    const unpublish$8 = (http, params, rawData) => {
        if (params.locales?.length) {
            const payload = { remove: { fields: { '*': params.locales } } };
            return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}/published`, payload, {
                headers: {
                    'X-Contentful-Version': rawData?.sys.version,
                },
            });
        }
        else {
            return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}/published`);
        }
    };
    const archive$3 = (http, params) => {
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}/archived`);
    };
    const unarchive$4 = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}/archived`);
    };
    const create$s = (http, params, rawData) => {
        if (params.releaseId) {
            return create$t(http, params, rawData, {});
        }
        const data = index$2(rawData);
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries`, data, {
            headers: {
                'X-Contentful-Content-Type': params.contentTypeId,
            },
        });
    };
    const createWithId$7 = (http, params, rawData) => {
        if (params.releaseId) {
            return createWithId$8(http, params, rawData, {});
        }
        const data = index$2(rawData);
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}`, data, {
            headers: {
                'X-Contentful-Content-Type': params.contentTypeId,
            },
        });
    };
    const references = (http, params) => {
        const { spaceId, environmentId, entryId, include } = params;
        const level = include || 2;
        return get$1f(http, `/spaces/${spaceId}/environments/${environmentId}/entries/${entryId}/references?include=${level}`);
    };

    var Entry = /*#__PURE__*/Object.freeze({
        __proto__: null,
        archive: archive$3,
        create: create$s,
        createWithId: createWithId$7,
        del: del$v,
        get: get$K,
        getMany: getMany$B,
        getManyWithCursor: getManyWithCursor,
        getPublished: getPublished,
        patch: patch$1,
        publish: publish$8,
        references: references,
        unarchive: unarchive$4,
        unpublish: unpublish$8,
        update: update$m
    });

    const get$J = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}`);
    };
    const getMany$A = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments`, {
            params: params.query,
        });
    };
    const update$l = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}`, data, {
            headers: {
                ...headers,
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const del$u = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}`);
    };
    const create$r = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, `/spaces/${params.spaceId}/environments`, data, {
            headers,
        });
    };
    const createWithId$6 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}`, data, {
            headers: {
                ...headers,
                ...(params.sourceEnvironmentId
                    ? {
                        'X-Contentful-Source-Environment': params.sourceEnvironmentId,
                    }
                    : {}),
            },
        });
    };

    var Environment = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$r,
        createWithId: createWithId$6,
        del: del$u,
        get: get$J,
        getMany: getMany$A,
        update: update$l
    });

    /**
     * Urls
     */
    const getBaseUrl$n = (params) => `/spaces/${params.spaceId}/environment_aliases`;
    const getEnvironmentAliasUrl = (params) => getBaseUrl$n(params) + `/${params.environmentAliasId}`;
    /**
     * Endpoints
     */
    const get$I = (http, params) => {
        return get$1f(http, getEnvironmentAliasUrl(params));
    };
    const getMany$z = (http, params) => {
        return get$1f(http, getBaseUrl$n(params), {
            params: params.query,
        });
    };
    const createWithId$5 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getEnvironmentAliasUrl(params), data, {
            headers: headers,
        });
    };
    const update$k = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getEnvironmentAliasUrl(params), data, {
            headers: {
                ...headers,
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const del$t = (http, params) => {
        return del$S(http, getEnvironmentAliasUrl(params));
    };

    var EnvironmentAlias = /*#__PURE__*/Object.freeze({
        __proto__: null,
        createWithId: createWithId$5,
        del: del$t,
        get: get$I,
        getMany: getMany$z,
        update: update$k
    });

    const apiPath$1 = (organizationId, ...pathSegments) => `/organizations/${organizationId}/environment_templates/` + pathSegments.join('/');
    const get$H = (http, { organizationId, environmentTemplateId, version, query = {} }, headers) => version
        ? get$1f(http, apiPath$1(organizationId, environmentTemplateId, 'versions', version), {
            params: query,
            headers,
        })
        : get$1f(http, apiPath$1(organizationId, environmentTemplateId), {
            params: query,
            headers,
        });
    const getMany$y = (http, { organizationId, query = {} }, headers) => get$1f(http, apiPath$1(organizationId), { params: query, headers });
    const create$q = (http, { organizationId }, payload, headers) => post$1(http, apiPath$1(organizationId), payload, { headers });
    const update$j = (http, { organizationId, environmentTemplateId }, payload, headers) => {
        const data = index$2(payload);
        delete data.sys;
        return put$1(http, apiPath$1(organizationId, environmentTemplateId), data, {
            headers: {
                'X-Contentful-Version': payload.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const versionUpdate = (http, { organizationId, version, environmentTemplateId }, payload, headers) => patch$5(http, apiPath$1(organizationId, environmentTemplateId, 'versions', version), payload, {
        headers,
    });
    const del$s = (http, { organizationId, environmentTemplateId }, headers) => del$S(http, apiPath$1(organizationId, environmentTemplateId), { headers });
    const versions = (http, { organizationId, environmentTemplateId, query = {} }, headers) => get$1f(http, apiPath$1(organizationId, environmentTemplateId, 'versions'), {
        params: query,
        headers,
    });
    const validate$1 = (http, { spaceId, environmentId, environmentTemplateId, version }, payload, headers) => put$1(http, version
        ? `/spaces/${spaceId}/environments/${environmentId}/template_installations/${environmentTemplateId}/versions/${version}/validated`
        : `/spaces/${spaceId}/environments/${environmentId}/template_installations/${environmentTemplateId}/validated`, payload, { headers });
    const install = (http, { spaceId, environmentId, environmentTemplateId }, payload, headers) => post$1(http, `/spaces/${spaceId}/environments/${environmentId}/template_installations/${environmentTemplateId}/versions`, payload, { headers });
    const disconnect = (http, { spaceId, environmentId, environmentTemplateId }, headers) => del$S(http, `/spaces/${spaceId}/environments/${environmentId}/template_installations/${environmentTemplateId}`, { headers });

    var EnvironmentTemplate = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$q,
        del: del$s,
        disconnect: disconnect,
        get: get$H,
        getMany: getMany$y,
        install: install,
        update: update$j,
        validate: validate$1,
        versionUpdate: versionUpdate,
        versions: versions
    });

    const apiPath = (organizationId, ...pathSegments) => `/organizations/${organizationId}/environment_templates/` + pathSegments.join('/');
    const getMany$x = (http, { organizationId, environmentTemplateId, spaceId, environmentId, ...otherProps }, headers) => get$1f(http, apiPath(organizationId, environmentTemplateId, 'template_installations'), {
        params: {
            ...otherProps,
            ...(environmentId && { 'environment.sys.id': environmentId }),
            ...(spaceId && { 'space.sys.id': spaceId }),
        },
        headers,
    });
    const getForEnvironment$1 = (http, { spaceId, environmentId, environmentTemplateId, installationId, ...paginationProps }, headers) => get$1f(http, `/spaces/${spaceId}/environments/${environmentId}/template_installations/${environmentTemplateId}`, {
        params: {
            ...(installationId && { 'sys.id': installationId }),
            ...paginationProps,
        },
        headers,
    });

    var EnvironmentTemplateInstallation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getForEnvironment: getForEnvironment$1,
        getMany: getMany$x
    });

    const getBaseUrl$m = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/extensions`;
    const getExtensionUrl = (params) => getBaseUrl$m(params) + `/${params.extensionId}`;
    const get$G = (http, params) => {
        return get$1f(http, getExtensionUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getMany$w = (http, params) => {
        return get$1f(http, getBaseUrl$m(params), {
            params: normalizeSelect(params.query),
        });
    };
    const create$p = (http, params, rawData, headers) => {
        return post$1(http, getBaseUrl$m(params), rawData, { headers });
    };
    const createWithId$4 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getExtensionUrl(params), data, { headers });
    };
    const update$i = async (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getExtensionUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$r = (http, params) => {
        return del$S(http, getExtensionUrl(params));
    };

    var Extension = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$p,
        createWithId: createWithId$4,
        del: del$r,
        get: get$G,
        getExtensionUrl: getExtensionUrl,
        getMany: getMany$w,
        update: update$i
    });

    const getBaseUrl$l = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/fragments`;
    const getMany$v = (http, params, headers) => {
        return get$1f(http, getBaseUrl$l(params), {
            params: params.query,
            headers,
        });
    };
    const get$F = (http, params, headers) => {
        return get$1f(http, getBaseUrl$l(params) + `/${params.fragmentId}`, { headers });
    };
    const create$o = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$l(params), data, { headers });
    };
    const upsert$8 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$l(params) + `/${params.fragmentId}`, body, {
            headers: {
                ...(sys?.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$q = (http, params) => {
        return del$S(http, getBaseUrl$l(params) + `/${params.fragmentId}`);
    };
    const publish$7 = (http, params, headers) => {
        return put$1(http, getBaseUrl$l(params) + `/${params.fragmentId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$7 = (http, params, headers) => {
        return del$S(http, getBaseUrl$l(params) + `/${params.fragmentId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var Fragment = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$o,
        del: del$q,
        get: get$F,
        getMany: getMany$v,
        publish: publish$7,
        unpublish: unpublish$7,
        upsert: upsert$8
    });

    // Base URL
    const getManyUrl = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/functions`;
    const getFunctionUrl = (params) => `${getManyUrl(params)}/${params.functionId}`;
    const getFunctionsEnvURL = (params) => {
        return `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appInstallationId}/functions`;
    };
    const get$E = (http, params) => {
        return get$1f(http, getFunctionUrl(params));
    };
    const getMany$u = (http, params) => {
        return get$1f(http, getManyUrl(params), { params: params.query });
    };
    const getManyForEnvironment$1 = (http, params) => {
        return get$1f(http, getFunctionsEnvURL(params), {
            params: params.query,
        });
    };

    var Function$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$E,
        getMany: getMany$u,
        getManyForEnvironment: getManyForEnvironment$1
    });

    const FunctionLogAlphaHeaders = {
        'x-contentful-enable-alpha-feature': 'function-logs',
    };
    const baseURL = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appInstallationId}/functions/${params.functionId}/logs`;
    const getURL = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/app_installations/${params.appInstallationId}/functions/${params.functionId}/logs/${params.logId}`;
    const get$D = (http, params) => {
        return get$1f(http, getURL(params), {
            headers: {
                ...FunctionLogAlphaHeaders,
            },
        });
    };
    const getMany$t = (http, params) => {
        return get$1f(http, baseURL(params), {
            params: params.query,
            headers: {
                ...FunctionLogAlphaHeaders,
            },
        });
    };

    var FunctionLog = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$D,
        getMany: getMany$t
    });

    const get$C = (http, { url, config }) => {
        return get$1f(http, url, config);
    };
    const post = (http, { url, config }, payload) => {
        return post$1(http, url, payload, config);
    };
    const put = (http, { url, config }, payload) => {
        return put$1(http, url, payload, config);
    };
    const patch = (http, { url, config }, payload) => {
        return patch$5(http, url, payload, config);
    };
    const del$p = (http, { url, config }) => {
        return del$S(http, url, config);
    };
    const request = (http$1, { url, config }) => {
        return http(http$1, url, config);
    };

    var Http = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$p,
        get: get$C,
        patch: patch,
        post: post,
        put: put,
        request: request
    });

    const get$B = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/locales/${params.localeId}`);
    };
    const getMany$s = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/locales`, {
            params: normalizeSelect(params.query),
        });
    };
    const create$n = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/locales`, data, {
            headers,
        });
    };
    const update$h = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        delete data.default; // we should not send this back
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/locales/${params.localeId}`, data, {
            headers: {
                ...headers,
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const del$o = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/locales/${params.localeId}`);
    };

    var Locale = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$n,
        del: del$o,
        get: get$B,
        getMany: getMany$s,
        update: update$h
    });

    const getMany$r = (http, params) => {
        return get$1f(http, `/organizations`, {
            params: params?.query,
        });
    };
    const get$A = (http, params) => {
        return getMany$r(http, { query: { limit: 100 } }).then((data) => {
            const org = data.items.find((org) => org.sys.id === params.organizationId);
            if (!org) {
                const error = new Error(`No organization was found with the ID ${params.organizationId} instead got ${JSON.stringify(data)}`);
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                error.status = 404;
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore
                error.statusText = 'Not Found';
                return Promise.reject(error);
            }
            return org;
        });
    };

    var Organization = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$A,
        getMany: getMany$r
    });

    const OrganizationUserManagementAlphaHeaders = {
        'x-contentful-enable-alpha-feature': 'organization-user-management-api',
    };
    const InvitationAlphaHeaders = {
        'x-contentful-enable-alpha-feature': 'pending-org-membership',
    };
    const create$m = (http, params, data, headers) => {
        return post$1(http, `/organizations/${params.organizationId}/invitations`, data, {
            headers: {
                ...InvitationAlphaHeaders,
                ...headers,
            },
        });
    };
    const get$z = (http, params, headers) => {
        return get$1f(http, `/organizations/${params.organizationId}/invitations/${params.invitationId}`, {
            headers: {
                ...OrganizationUserManagementAlphaHeaders,
                ...headers,
            },
        });
    };

    var OrganizationInvitation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$m,
        get: get$z
    });

    const getBaseUrl$k = (params) => `/organizations/${params.organizationId}/organization_memberships`;
    const getEntityUrl$5 = (params) => `${getBaseUrl$k(params)}/${params.organizationMembershipId}`;
    const get$y = (http, params) => {
        return get$1f(http, getEntityUrl$5(params));
    };
    const getMany$q = (http, params) => {
        return get$1f(http, getBaseUrl$k(params), {
            params: params.query,
        });
    };
    const update$g = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        const { role } = data;
        return put$1(http, getEntityUrl$5(params), { role }, {
            headers: {
                ...headers,
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const del$n = (http, params) => {
        return del$S(http, getEntityUrl$5(params));
    };

    var OrganizationMembership = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$n,
        get: get$y,
        getMany: getMany$q,
        update: update$g
    });

    /**
     * Retrieves details of a specific OAuth application. by its unique user ID and oauth application ID.
     *
     * @param {AxiosInstance} http - An Axios HTTP client instance.
     * @param {Object} params - Parameters for the request.
     * @param {string} params.userId - The unique user ID of the user.
     * @param {string} params.oauthApplicationId - The unique application ID of the OAuth application.
     * @returns {Promise<OAuthApplicationProps>} A Promise that resolves with the retrieved OAuth Application.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *   accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.get({userId: 'TestUserId', oauthApplicationId: 'TestOAuthAppId'})
     *  .then(oauthApplication => console.log(oauthApplication))
     *  .catch(console.error)
     * ```
     */
    const get$x = (http, params) => {
        return get$1f(http, `/users/${params.userId}/oauth_applications/${params.oauthApplicationId}`);
    };
    /**
     * Retrieves a list of OAuth applications associated with the current user.
     *
     * @param {AxiosInstance} http - An Axios HTTP client instance.
     * @param {Object} params - Parameters for the request.
     * @param {string} params.userId - The unique user ID of the user.
     * @param {QueryParams} params - Query parameters to filter and customize the request.
     * @returns {Promise<CursorPaginatedCollectionProp<OAuthApplicationProps>>} A Promise that resolves with a collection of oauth application properties.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.getManyForUser({userId: 'TestUserId'})
     *  .then(result => console.log(result.items))
     *  .catch(console.error)
     * ```
     */
    const getManyForUser = (http, params) => {
        return get$1f(http, `/users/${params.userId}/oauth_applications`, {
            params: params.query,
        });
    };
    /**
     * Creates a new OAuth application for current authenticated user.
     *
     * @param {AxiosInstance} http - Axios instance for making the HTTP request.
     * @param {Object} params - Parameters for the request.
     * @param {string} params.userId - The unique user ID of the user.
     * @param {RawAxiosRequestHeaders} [headers] - Optional HTTP headers for the request.
     * @returns {Promise<OAuthApplicationProps>} A Promise that resolves with the created oauth application.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>',
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.create(
     *  {userId: 'TestUserId'},
     *  {name: 'Test-Name', description: 'Test-Desc', scopes: ['content_management_manage'], redirectUri: 'https://redirect.uri.com', confidential: true}
     *  )
     *  .then(oauthApplication => console.log(oauthApplication))
     *  .catch(console.error)
     * ```
     */
    const create$l = (http, params, rawData, headers) => {
        return post$1(http, `/users/${params.userId}/oauth_applications`, rawData, {
            headers,
        });
    };
    /**
     * Updates details of a specific OAuth application.
     *
     * @param {AxiosInstance} http - The Axios HTTP client instance.
     * @param {Object} params - The parameters for updating oauth application.
     * @param {string} params.userId - The unique user ID of the user.
     * @param {string} params.oauthApplicationId - The unique application ID of the OAuth application.
     * @returns {Promise<OAuthApplicationProps>} A Promise that resolves with the updated oauth application.
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.update(
     * {userId: 'TestUserId', oauthApplicationId: 'TestOAuthAppId'},
     * {name: 'Test-Name', description: 'Test-Desc', scope: ['content_management_manage'], redirectUri: 'https://redirect.uri.com', confidential: true}
     * )
     *  .then(oauthApplication => console.log(oauthApplication))
     *  .catch(console.error)
     * ```
     */
    const update$f = (http, params, rawData, headers) => {
        return put$1(http, `/users/${params.userId}/oauth_applications/${params.oauthApplicationId}`, rawData, {
            headers,
        });
    };
    /**
     * Deletes a specific OAuth application.
     *
     * @param {AxiosInstance} http - The Axios HTTP client instance.
     * @param {Object} params - The parameters for deleting oauth application.
     * @param {string} params.userId - The unique user ID of the user.
     * @param {string} params.oauthApplicationId - The unique application ID of the OAuth application.
     * @returns {Promise<void>}
     * @example ```javascript
     * const contentful = require('contentful-management')
     *
     * const plainClient = contentful.createClient(
     *  {
     *    accessToken: '<content_management_api_key>'
     *  },
     *  { type: 'plain' }
     * )
     * plainClient.del({userId: 'TestUserId', oauthApplicationId: 'TestOAuthAppId'}) })
     *  .then(result => console.log(result.items))
     *  .catch(console.error)
     * ```
     */
    const del$m = (http, params) => {
        return del$S(http, `/users/${params.userId}/oauth_applications/${params.oauthApplicationId}`);
    };

    var OAuthApplication = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$l,
        del: del$m,
        get: get$x,
        getManyForUser: getManyForUser,
        update: update$f
    });

    /**
     * @deprecated use `access-token.get` instead `personal-access-token.get`
     */
    const get$w = (http, params) => {
        return get$1f(http, `/users/me/access_tokens/${params.tokenId}`);
    };
    /**
     * @deprecated use `access-token.getMany` instead `personal-access-token.getMany`
     */
    const getMany$p = (http, params) => {
        return get$1f(http, '/users/me/access_tokens', {
            params: params.query,
        });
    };
    /**
     * @deprecated use `access-token.createPersonalAccessToken` instead. `personal-access-token.create`
     */
    const create$k = (http, _params, rawData, headers) => {
        return post$1(http, '/users/me/access_tokens', rawData, {
            headers,
        });
    };
    /**
     * @deprecated use `access-token.rovoke` instead. `personal-access-token.revoke`
     */
    const revoke = (http, params) => {
        return put$1(http, `/users/me/access_tokens/${params.tokenId}/revoked`, null);
    };

    var PersonalAccessToken = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$k,
        get: get$w,
        getMany: getMany$p,
        revoke: revoke
    });

    const get$v = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/preview_api_keys/${params.previewApiKeyId}`);
    };
    const getMany$o = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/preview_api_keys`, {
            params: params.query,
        });
    };

    var PreviewApiKey = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$v,
        getMany: getMany$o
    });

    const get$u = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}`);
    };
    const query = (http, params) => {
        // Set the schema version in the query if provided in params or query options
        const releaseSchemaVersion = params.query?.['sys.schemaVersion'] ?? params.releaseSchemaVersion ?? undefined;
        if (releaseSchemaVersion !== undefined) {
            params.query = { ...params.query, 'sys.schemaVersion': releaseSchemaVersion };
        }
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases`, {
            params: params.query,
        });
    };
    const create$j = (http, params, payload) => {
        const releaseSchemaVersion = payload.sys?.schemaVersion ?? params.releaseSchemaVersion;
        if (releaseSchemaVersion === 'Release.v2') {
            payload.sys = { ...payload.sys, type: 'Release', schemaVersion: 'Release.v2' };
        }
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases`, payload);
    };
    const update$e = (http, params, payload, headers) => {
        const releaseSchemaVersion = payload.sys?.schemaVersion ?? params.releaseSchemaVersion;
        if (releaseSchemaVersion === 'Release.v2') {
            payload.sys = { ...payload.sys, type: 'Release', schemaVersion: 'Release.v2' };
        }
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}`, payload, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const del$l = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}`);
    };
    const publish$6 = (http, params, headers) => {
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$6 = (http, params, headers) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const validate = (http, params, payload) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/validate`, payload);
    };
    const archive$2 = (http, params) => {
        return put$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/archived`, null, {
            headers: {
                'X-Contentful-Version': params.version,
            },
        });
    };
    const unarchive$3 = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/archived`, {
            headers: {
                'X-Contentful-Version': params.version,
            },
        });
    };

    var Release = /*#__PURE__*/Object.freeze({
        __proto__: null,
        archive: archive$2,
        create: create$j,
        del: del$l,
        get: get$u,
        publish: publish$6,
        query: query,
        unarchive: unarchive$3,
        unpublish: unpublish$6,
        update: update$e,
        validate: validate
    });

    const get$t = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/releases/${params.releaseId}/actions/${params.actionId}`);
    };
    const getMany$n = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/release_actions`, {
            params: params.query,
        });
    };
    const queryForRelease = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/release_actions`, {
            params: {
                'sys.release.sys.id[in]': params.releaseId,
                ...params.query,
            },
        });
    };

    var ReleaseAction = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$t,
        getMany: getMany$n,
        queryForRelease: queryForRelease
    });

    const getBaseUrl$j = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/resource_types/${params.resourceTypeId}/resources`;
    const getMany$m = (http, params) => get$1f(http, getBaseUrl$j(params), {
        params: params.query,
    });

    var Resource = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getMany: getMany$m
    });

    const getBaseUrl$i = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/resource_provider`;
    const get$s = (http, params) => {
        return get$1f(http, getBaseUrl$i(params));
    };
    const upsert$7 = (http, params, rawData, headers) => {
        return put$1(http, getBaseUrl$i(params), rawData, { headers });
    };
    const del$k = (http, params) => {
        return del$S(http, getBaseUrl$i(params));
    };

    var ResourceProvider = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$k,
        get: get$s,
        upsert: upsert$7
    });

    const getBaseUrl$h = (params) => `/organizations/${params.organizationId}/app_definitions/${params.appDefinitionId}/resource_provider/resource_types`;
    const getEntityUrl$4 = (params) => `${getBaseUrl$h(params)}/${params.resourceTypeId}`;
    const getSpaceEnvUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/resource_types`;
    const get$r = (http, params) => {
        return get$1f(http, getEntityUrl$4(params));
    };
    const upsert$6 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getEntityUrl$4(params), data, { headers });
    };
    const del$j = (http, params) => {
        return del$S(http, getEntityUrl$4(params));
    };
    const getMany$l = (http, params) => {
        return get$1f(http, getBaseUrl$h(params));
    };
    const getForEnvironment = (http, params) => {
        return get$1f(http, getSpaceEnvUrl(params));
    };

    var ResourceType = /*#__PURE__*/Object.freeze({
        __proto__: null,
        del: del$j,
        get: get$r,
        getForEnvironment: getForEnvironment,
        getMany: getMany$l,
        upsert: upsert$6
    });

    const get$q = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/roles/${params.roleId}`);
    };
    const getMany$k = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/roles`, {
            params: normalizeSelect(params.query),
        });
    };
    const getManyForOrganization$7 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/roles`, {
            params: normalizeSelect(params.query),
        });
    };
    const create$i = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/roles`, data, {
            headers,
        });
    };
    const createWithId$3 = (http, params, data, headers) => {
        return put$1(http, `/spaces/${params.spaceId}/roles/${params.roleId}`, data, {
            headers,
        });
    };
    const update$d = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}/roles/${params.roleId}`, data, {
            headers: {
                ...headers,
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const del$i = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/roles/${params.roleId}`);
    };

    var Role = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$i,
        createWithId: createWithId$3,
        del: del$i,
        get: get$q,
        getMany: getMany$k,
        getManyForOrganization: getManyForOrganization$7,
        update: update$d
    });

    const get$p = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/scheduled_actions/${params.scheduledActionId}`, {
            params: {
                'environment.sys.id': params.environmentId,
            },
        });
    };
    const getMany$j = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/scheduled_actions`, {
            params: normalizeSelect(params.query),
        });
    };
    const create$h = (http, params, data) => {
        return post$1(http, `/spaces/${params.spaceId}/scheduled_actions`, data);
    };
    const del$h = (http, params) => {
        return del$S(http, `/spaces/${params.spaceId}/scheduled_actions/${params.scheduledActionId}`, {
            params: {
                'environment.sys.id': params.environmentId,
            },
        });
    };
    const update$c = (http, params, data) => {
        return put$1(http, `/spaces/${params.spaceId}/scheduled_actions/${params.scheduledActionId}`, data, {
            params: {
                'environment.sys.id': data.environment?.sys.id,
            },
            headers: {
                'X-Contentful-Version': params.version,
            },
        });
    };

    var ScheduledAction = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$h,
        del: del$h,
        get: get$p,
        getMany: getMany$j,
        update: update$c
    });

    const get$o = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/semantic/search-index/${params.indexId}`);
    };
    const getMany$i = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/semantic/search-index`, { params: params.status ? { status: params.status } : undefined });
    };
    const getManyForEnvironment = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/semantic/search-index`, { params: params.status ? { status: params.status } : undefined });
    };
    const create$g = (http, params, data) => {
        return post$1(http, `/organizations/${params.organizationId}/semantic/search-index`, data);
    };
    const del$g = (http, params) => {
        return del$S(http, `/organizations/${params.organizationId}/semantic/search-index/${params.indexId}`);
    };

    var ContentSemanticsIndex = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$g,
        del: del$g,
        get: get$o,
        getMany: getMany$i,
        getManyForEnvironment: getManyForEnvironment
    });

    const get$n = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/semantic/duplicates`, data, { headers });
    };

    var SemanticDuplicates = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$n
    });

    const get$m = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/semantic/recommendations`, data, { headers });
    };

    var SemanticRecommendations = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$m
    });

    const get$l = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/semantic/reference-suggestions`, data, { headers });
    };

    var SemanticReferenceSuggestions = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$l
    });

    const get$k = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/environments/${params.environmentId}/semantic/search`, data, { headers });
    };

    var SemanticSearch = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$k
    });

    const get$j = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/semantic/settings`);
    };

    var SemanticSettings = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$j
    });

    const getBaseEntryUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/entries/${params.entryId}/snapshots`;
    const getEntryUrl = (params) => getBaseEntryUrl(params) + `/${params.snapshotId}`;
    const getManyForEntry = (http, params) => {
        return get$1f(http, getBaseEntryUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getForEntry = (http, params) => {
        return get$1f(http, getEntryUrl(params));
    };
    const getBaseContentTypeUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/content_types/${params.contentTypeId}/snapshots`;
    const getContentTypeUrl = (params) => getBaseContentTypeUrl(params) + `/${params.snapshotId}`;
    const getManyForContentType = (http, params) => {
        return get$1f(http, getBaseContentTypeUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getForContentType = (http, params) => {
        return get$1f(http, getContentTypeUrl(params));
    };

    var Snapshot = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getForContentType: getForContentType,
        getForEntry: getForEntry,
        getManyForContentType: getManyForContentType,
        getManyForEntry: getManyForEntry
    });

    const get$i = (http, params) => get$1f(http, `/spaces/${params.spaceId}`, {
        params: params.include ? { include: params.include } : undefined,
    });
    const getMany$h = (http, params) => get$1f(http, `/spaces`, {
        params: { ...params.query, ...(params.include ? { include: params.include } : {}) },
        headers: params.organizationId
            ? { 'X-Contentful-Organization': params.organizationId }
            : undefined,
    });
    const getManyForOrganization$6 = (http, params) => get$1f(http, `/organizations/${params.organizationId}/spaces`, {
        params: params.query,
    });
    const create$f = (http, params, payload, headers) => {
        return post$1(http, `/spaces`, payload, {
            headers: params.organizationId
                ? { ...headers, 'X-Contentful-Organization': params.organizationId }
                : headers,
        });
    };
    const update$b = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, `/spaces/${params.spaceId}`, data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const unarchive$2 = (http, params, data, headers) => {
        return post$1(http, `/spaces/${params.spaceId}/unarchive`, data, {
            headers,
        });
    };
    const del$f = (http, params) => del$S(http, `/spaces/${params.spaceId}`);

    var Space = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$f,
        del: del$f,
        get: get$i,
        getMany: getMany$h,
        getManyForOrganization: getManyForOrganization$6,
        unarchive: unarchive$2,
        update: update$b
    });

    const getMany$g = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/space_add_ons`, {
            params: normalizeSelect(params.query),
        });
    };
    const getManyForOrganization$5 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/space_add_ons`, {
            params: normalizeSelect(params.query),
        });
    };
    const updateAllocations = (http, params, data, headers) => {
        return put$1(http, `/spaces/${params.spaceId}/space_add_ons`, data, {
            headers,
        });
    };

    var SpaceAddOn = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getMany: getMany$g,
        getManyForOrganization: getManyForOrganization$5,
        updateAllocations: updateAllocations
    });

    const get$h = (http, params) => get$1f(http, `/spaces/${params.spaceId}/space_members/${params.spaceMemberId}`);
    const getMany$f = (http, params) => get$1f(http, `/spaces/${params.spaceId}/space_members`, {
        params: params.query,
    });

    var SpaceMember = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$h,
        getMany: getMany$f
    });

    function spaceMembershipDeprecationWarning() {
        console.warn('The user attribute in the space membership root is deprecated. The attribute has been moved inside the sys  object (i.e. sys.user)');
    }
    const getBaseUrl$g = (params) => `/spaces/${params.spaceId}/space_memberships`;
    const getEntityUrl$3 = (params) => `${getBaseUrl$g(params)}/${params.spaceMembershipId}`;
    const get$g = (http, params) => {
        spaceMembershipDeprecationWarning();
        return get$1f(http, getEntityUrl$3(params));
    };
    const getMany$e = (http, params) => {
        spaceMembershipDeprecationWarning();
        return get$1f(http, getBaseUrl$g(params), {
            params: params.query,
        });
    };
    const getForOrganization$2 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/space_memberships/${params.spaceMembershipId}`);
    };
    const getManyForOrganization$4 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/space_memberships`, {
            params: params.query,
        });
    };
    const create$e = (http, params, data, headers) => {
        spaceMembershipDeprecationWarning();
        return post$1(http, getBaseUrl$g(params), data, {
            headers,
        });
    };
    const createWithId$2 = (http, params, data, headers) => {
        spaceMembershipDeprecationWarning();
        return put$1(http, getEntityUrl$3(params), data, {
            headers,
        });
    };
    const update$a = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getEntityUrl$3(params), data, {
            headers: {
                ...headers,
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };
    const del$e = (http, params) => {
        return del$S(http, getEntityUrl$3(params));
    };

    var SpaceMembership = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$e,
        createWithId: createWithId$2,
        del: del$e,
        get: get$g,
        getForOrganization: getForOrganization$2,
        getMany: getMany$e,
        getManyForOrganization: getManyForOrganization$4,
        update: update$a
    });

    const getBaseUrl$f = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/tags`;
    const getTagUrl = (params) => getBaseUrl$f(params) + `/${params.tagId}`;
    const get$f = (http, params) => get$1f(http, getTagUrl(params));
    const getMany$d = (http, params) => get$1f(http, getBaseUrl$f(params), {
        params: params.query,
    });
    const createWithId$1 = (http, params, rawData) => {
        const data = index$2(rawData);
        return put$1(http, getTagUrl(params), data, {
            headers: { 'X-Contentful-Tag-Visibility': rawData.sys.visibility ?? 'private' },
        });
    };
    const update$9 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getTagUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$d = (http, { version, ...params }) => {
        return del$S(http, getTagUrl(params), { headers: { 'X-Contentful-Version': version } });
    };

    var Tag = /*#__PURE__*/Object.freeze({
        __proto__: null,
        createWithId: createWithId$1,
        del: del$d,
        get: get$f,
        getMany: getMany$d,
        update: update$9
    });

    const getSpaceEnvBaseUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}`;
    function getParentPlural(parentEntityType) {
        switch (parentEntityType) {
            case 'Entry':
                return 'entries';
            case 'Experience':
                return 'experiences';
            case 'ExperienceFragment':
                return 'experience_fragments';
            case 'ExperienceTemplate':
                return 'experience_templates';
            case 'Component':
                return 'components';
        }
    }
    const normalizeTaskParentParams = (paramsOrg) => 'entryId' in paramsOrg
        ? {
            spaceId: paramsOrg.spaceId,
            environmentId: paramsOrg.environmentId,
            parentEntityType: 'Entry',
            parentEntityId: paramsOrg.entryId,
        }
        : paramsOrg;
    const getBaseUrl$e = (paramsOrg) => {
        const params = normalizeTaskParentParams(paramsOrg);
        const parentPlural = getParentPlural(params.parentEntityType);
        return `${getSpaceEnvBaseUrl(params)}/${parentPlural}/${params.parentEntityId}/tasks`;
    };
    const getTaskUrl = (params) => `${getBaseUrl$e(params)}/${params.taskId}`;
    const get$e = (http, params) => get$1f(http, getTaskUrl(params));
    const getMany$c = (http, params) => get$1f(http, getBaseUrl$e(params), {
        params: normalizeSelect(params.query),
    });
    /**
     * @deprecated use `getMany` instead. `getAll` may never be removed for app compatibility reasons.
     */
    const getAll = getMany$c;
    const create$d = (http, params, rawData) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$e(params), data);
    };
    const update$8 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getTaskUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$c = (http, { version, ...params }) => {
        return del$S(http, getTaskUrl(params), { headers: { 'X-Contentful-Version': version } });
    };

    var Task = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$d,
        del: del$c,
        get: get$e,
        getAll: getAll,
        getMany: getMany$c,
        update: update$8
    });

    const getBaseUrl$d = (params) => `/organizations/${params.organizationId}/teams`;
    const getEntityUrl$2 = (params) => `${getBaseUrl$d(params)}/${params.teamId}`;
    const get$d = (http, params) => get$1f(http, getEntityUrl$2(params));
    const getMany$b = (http, params) => get$1f(http, getBaseUrl$d(params), {
        params: normalizeSelect(params.query),
    });
    const getManyForSpace$2 = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/teams`, {
            params: normalizeSelect(params.query),
        });
    };
    const create$c = (http, params, rawData, headers) => {
        return post$1(http, getBaseUrl$d(params), rawData, { headers });
    };
    const update$7 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getEntityUrl$2(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$b = (http, params) => del$S(http, getEntityUrl$2(params));

    var Team = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$c,
        del: del$b,
        get: get$d,
        getMany: getMany$b,
        getManyForSpace: getManyForSpace$2,
        update: update$7
    });

    const getBaseUrl$c = (params) => `/organizations/${params.organizationId}/teams/${params.teamId}/team_memberships`;
    const getEntityUrl$1 = (params) => `/organizations/${params.organizationId}/teams/${params.teamId}/team_memberships/${params.teamMembershipId}`;
    const get$c = (http, params) => get$1f(http, getEntityUrl$1(params));
    const getManyForOrganization$3 = (http, params) => get$1f(http, `/organizations/${params.organizationId}/team_memberships`, {
        params: normalizeSelect(params.query),
    });
    const getManyForTeam = (http, params) => {
        return get$1f(http, getBaseUrl$c(params), {
            params: normalizeSelect(params.query),
        });
    };
    const create$b = (http, params, rawData, headers) => {
        return post$1(http, getBaseUrl$c(params), rawData, { headers });
    };
    const update$6 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getEntityUrl$1(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version || 0,
                ...headers,
            },
        });
    };
    const del$a = (http, params) => del$S(http, getEntityUrl$1(params));

    var TeamMembership = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$b,
        del: del$a,
        get: get$c,
        getManyForOrganization: getManyForOrganization$3,
        getManyForTeam: getManyForTeam,
        update: update$6
    });

    const getBaseUrl$b = (params) => `/spaces/${params.spaceId}/team_space_memberships`;
    const getEntityUrl = (params) => `${getBaseUrl$b(params)}/${params.teamSpaceMembershipId}`;
    const get$b = (http, params) => get$1f(http, getEntityUrl(params));
    const getMany$a = (http, params) => get$1f(http, getBaseUrl$b(params), {
        params: params.query,
    });
    const getForOrganization$1 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/team_space_memberships/${params.teamSpaceMembershipId}`);
    };
    const getManyForOrganization$2 = (http, params) => {
        const query = params.query || {};
        if (params.teamId) {
            query['sys.team.sys.id'] = params.teamId;
        }
        return get$1f(http, `/organizations/${params.organizationId}/team_space_memberships`, {
            params: params.query,
        });
    };
    const create$a = (http, params, rawData, headers) => {
        return post$1(http, getBaseUrl$b(params), rawData, {
            headers: {
                'x-contentful-team': params.teamId,
                ...headers,
            },
        });
    };
    const update$5 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getEntityUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version || 0,
                'x-contentful-team': rawData.sys.team.sys.id,
                ...headers,
            },
        });
    };
    const del$9 = (http, params) => {
        return del$S(http, getEntityUrl(params));
    };

    var TeamSpaceMembership = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$a,
        del: del$9,
        get: get$b,
        getForOrganization: getForOrganization$1,
        getMany: getMany$a,
        getManyForOrganization: getManyForOrganization$2,
        update: update$5
    });

    const getBaseUrl$a = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/templates`;
    const getMany$9 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$a(params), {
            params: params.query,
            headers,
        });
    };
    const get$a = (http, params, headers) => {
        return get$1f(http, getBaseUrl$a(params) + `/${params.templateId}`, { headers });
    };
    const create$9 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$a(params), data, { headers });
    };
    const upsert$5 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$a(params) + `/${params.templateId}`, body, {
            headers: {
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$8 = (http, params) => {
        return del$S(http, getBaseUrl$a(params) + `/${params.templateId}`);
    };
    const publish$5 = (http, params, headers) => {
        return put$1(http, getBaseUrl$a(params) + `/${params.templateId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$5 = (http, params, headers) => {
        return del$S(http, getBaseUrl$a(params) + `/${params.templateId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var Template = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$9,
        del: del$8,
        get: get$a,
        getMany: getMany$9,
        publish: publish$5,
        unpublish: unpublish$5,
        upsert: upsert$5
    });

    const getUrl$1 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/ui_config`;
    const get$9 = (http, params) => {
        return get$1f(http, getUrl$1(params));
    };
    const update$4 = (http, params, rawData) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getUrl$1(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };

    var UIConfig = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$9,
        update: update$4
    });

    const getBaseUrl$9 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/experiences`;
    // Opts into the renamed ("new ExO entity types") Experience shape: sys.experienceTemplate
    // instead of sys.template, and ExperienceFragment slot nodes. The renamed family shares the
    // `/experiences` URLs with the legacy routes and is discriminated server-side on this header.
    const ExperienceAlphaHeaders = {
        'x-contentful-enable-alpha-feature': 'new-exo-entity-types',
    };
    const getMany$8 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$9(params), {
            params: params.query,
            headers: {
                ...ExperienceAlphaHeaders,
                ...headers,
            },
        });
    };
    const get$8 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$9(params) + `/${params.experienceId}`, {
            headers: {
                ...ExperienceAlphaHeaders,
                ...headers,
            },
        });
    };
    const create$8 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$9(params), data, {
            headers: {
                ...ExperienceAlphaHeaders,
                ...headers,
            },
        });
    };
    const upsert$4 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$9(params) + `/${params.experienceId}`, body, {
            headers: {
                ...ExperienceAlphaHeaders,
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$7 = (http, params) => {
        return del$S(http, getBaseUrl$9(params) + `/${params.experienceId}`, {
            headers: {
                ...ExperienceAlphaHeaders,
            },
        });
    };
    const publish$4 = (http, params, payload, headers) => {
        return put$1(http, getBaseUrl$9(params) + `/${params.experienceId}/published`, payload ?? null, {
            headers: {
                ...ExperienceAlphaHeaders,
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$4 = (http, params, headers) => {
        return del$S(http, getBaseUrl$9(params) + `/${params.experienceId}/published`, {
            headers: {
                ...ExperienceAlphaHeaders,
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var Experience = /*#__PURE__*/Object.freeze({
        __proto__: null,
        ExperienceAlphaHeaders: ExperienceAlphaHeaders,
        create: create$8,
        del: del$7,
        get: get$8,
        getMany: getMany$8,
        publish: publish$4,
        unpublish: unpublish$4,
        upsert: upsert$4
    });

    const getBaseUrl$8 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/experiences/${params.experienceId}/optimization_variants`;
    const getVariantUrl$1 = (params) => `${getBaseUrl$8(params)}/${params.variantId}`;
    const actionHeaders$1 = (version, headers) => ({
        ...ExperienceAlphaHeaders,
        'X-Contentful-Version': version,
        ...headers,
    });
    const getMany$7 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$8(params), {
            params: params.query,
            headers: {
                ...ExperienceAlphaHeaders,
                ...headers,
            },
        });
    };
    const get$7 = (http, params, headers) => {
        return get$1f(http, getVariantUrl$1(params), {
            headers: {
                ...ExperienceAlphaHeaders,
                ...headers,
            },
        });
    };
    const create$7 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$8(params), data, {
            headers: {
                ...ExperienceAlphaHeaders,
                ...headers,
            },
        });
    };
    const upsert$3 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getVariantUrl$1(params), body, {
            headers: {
                ...ExperienceAlphaHeaders,
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$6 = (http, params) => {
        return del$S(http, getVariantUrl$1(params), {
            headers: {
                ...ExperienceAlphaHeaders,
            },
        });
    };
    const publish$3 = (http, params, headers) => {
        return put$1(http, `${getVariantUrl$1(params)}/published`, null, {
            headers: actionHeaders$1(params.version, headers),
        });
    };
    const unpublish$3 = (http, params, headers) => {
        return del$S(http, `${getVariantUrl$1(params)}/published`, {
            headers: actionHeaders$1(params.version, headers),
        });
    };
    const archive$1 = (http, params, headers) => {
        return put$1(http, `${getVariantUrl$1(params)}/archived`, null, {
            headers: actionHeaders$1(params.version, headers),
        });
    };
    const unarchive$1 = (http, params, headers) => {
        return del$S(http, `${getVariantUrl$1(params)}/archived`, {
            headers: actionHeaders$1(params.version, headers),
        });
    };

    var ExperienceVariant = /*#__PURE__*/Object.freeze({
        __proto__: null,
        archive: archive$1,
        create: create$7,
        del: del$6,
        get: get$7,
        getMany: getMany$7,
        publish: publish$3,
        unarchive: unarchive$1,
        unpublish: unpublish$3,
        upsert: upsert$3
    });

    const getBaseUrl$7 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/experience_fragments`;
    const getMany$6 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$7(params), {
            params: params.query,
            headers,
        });
    };
    const get$6 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$7(params) + `/${params.experienceFragmentId}`, { headers });
    };
    const create$6 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$7(params), data, { headers });
    };
    const upsert$2 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$7(params) + `/${params.experienceFragmentId}`, body, {
            headers: {
                ...(sys?.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$5 = (http, params) => {
        return del$S(http, getBaseUrl$7(params) + `/${params.experienceFragmentId}`);
    };
    const publish$2 = (http, params, headers) => {
        return put$1(http, getBaseUrl$7(params) + `/${params.experienceFragmentId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$2 = (http, params, headers) => {
        return del$S(http, getBaseUrl$7(params) + `/${params.experienceFragmentId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var ExperienceFragment = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$6,
        del: del$5,
        get: get$6,
        getMany: getMany$6,
        publish: publish$2,
        unpublish: unpublish$2,
        upsert: upsert$2
    });

    const getBaseUrl$6 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/experience_templates`;
    const getMany$5 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$6(params), {
            params: params.query,
            headers,
        });
    };
    const get$5 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$6(params) + `/${params.experienceTemplateId}`, { headers });
    };
    const create$5 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$6(params), data, { headers });
    };
    const upsert$1 = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getBaseUrl$6(params) + `/${params.experienceTemplateId}`, body, {
            headers: {
                ...(sys.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$4 = (http, params) => {
        return del$S(http, getBaseUrl$6(params) + `/${params.experienceTemplateId}`);
    };
    const publish$1 = (http, params, headers) => {
        return put$1(http, getBaseUrl$6(params) + `/${params.experienceTemplateId}/published`, null, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };
    const unpublish$1 = (http, params, headers) => {
        return del$S(http, getBaseUrl$6(params) + `/${params.experienceTemplateId}/published`, {
            headers: {
                'X-Contentful-Version': params.version,
                ...headers,
            },
        });
    };

    var ExperienceTemplate = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$5,
        del: del$4,
        get: get$5,
        getMany: getMany$5,
        publish: publish$1,
        unpublish: unpublish$1,
        upsert: upsert$1
    });

    const getBaseUrl$5 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/experience_fragments/${params.experienceFragmentId}/optimization_variants`;
    const getVariantUrl = (params) => `${getBaseUrl$5(params)}/${params.variantId}`;
    const actionHeaders = (version, headers) => ({
        'X-Contentful-Version': version,
        ...headers,
    });
    const getMany$4 = (http, params, headers) => {
        return get$1f(http, getBaseUrl$5(params), {
            params: params.query,
            headers,
        });
    };
    const get$4 = (http, params, headers) => {
        return get$1f(http, getVariantUrl(params), { headers });
    };
    const create$4 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$5(params), data, { headers });
    };
    const upsert = (http, params, rawData, headers) => {
        const { sys, ...body } = index$2(rawData);
        return put$1(http, getVariantUrl(params), body, {
            headers: {
                ...(sys?.version !== undefined && {
                    'X-Contentful-Version': sys.version,
                }),
                ...headers,
            },
        });
    };
    const del$3 = (http, params) => {
        return del$S(http, getVariantUrl(params));
    };
    const publish = (http, params, headers) => {
        return put$1(http, `${getVariantUrl(params)}/published`, null, {
            headers: actionHeaders(params.version, headers),
        });
    };
    const unpublish = (http, params, headers) => {
        return del$S(http, `${getVariantUrl(params)}/published`, {
            headers: actionHeaders(params.version, headers),
        });
    };
    const archive = (http, params, headers) => {
        return put$1(http, `${getVariantUrl(params)}/archived`, null, {
            headers: actionHeaders(params.version, headers),
        });
    };
    const unarchive = (http, params, headers) => {
        return del$S(http, `${getVariantUrl(params)}/archived`, {
            headers: actionHeaders(params.version, headers),
        });
    };

    var ExperienceFragmentVariant = /*#__PURE__*/Object.freeze({
        __proto__: null,
        archive: archive,
        create: create$4,
        del: del$3,
        get: get$4,
        getMany: getMany$4,
        publish: publish,
        unarchive: unarchive,
        unpublish: unpublish,
        upsert: upsert
    });

    const getBaseUrl$4 = (params) => {
        return `/spaces/${params.spaceId}/environments/${params.environmentId ?? 'master'}/upload_credentials`;
    };
    const create$3 = (http, params) => {
        const httpUpload = getUploadHttpClient(http);
        const path = getBaseUrl$4(params);
        return post$1(httpUpload, path);
    };

    var UploadCredential = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$3
    });

    /**
     * @deprecated Use {@link getAggregated} instead, calling it once per metric key and
     * filtering by `filter[sys.dimensions.space.sys.id]` to scope to a space. Sunset: 2027-02-28.
     */
    const getManyForSpace$1 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/space_periodic_usages`, {
            params: params.query,
        });
    };
    /**
     * @deprecated Use {@link getAggregated} instead, calling it once per metric key
     * (this endpoint accepted multiple metrics per call via `metric[in]`; {@link getAggregated}
     * is scoped to a single `metricKey` per request). Sunset: 2027-02-28.
     */
    const getManyForOrganization$1 = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/organization_periodic_usages`, {
            params: params.query,
        });
    };
    const getAggregated = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/usages/${params.metricKey}`, {
            params: params.query,
        });
    };
    const getAssetBandwidthUsageDetailed = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/usages-detailed/asset_bandwidth`, {
            params: params.query,
        });
    };

    var Usage = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getAggregated: getAggregated,
        getAssetBandwidthUsageDetailed: getAssetBandwidthUsageDetailed,
        getManyForOrganization: getManyForOrganization$1,
        getManyForSpace: getManyForSpace$1
    });

    const getForSpace = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/users/${params.userId}`);
    };
    const getCurrent = (http, params) => get$1f(http, `/users/me`, { params: params?.query });
    const getManyForSpace = (http, params) => {
        return get$1f(http, `/spaces/${params.spaceId}/users`, {
            params: params.query,
        });
    };
    const getForOrganization = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/users/${params.userId}`);
    };
    const getManyForOrganization = (http, params) => {
        return get$1f(http, `/organizations/${params.organizationId}/users`, {
            params: params.query,
        });
    };

    var User = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getCurrent: getCurrent,
        getForOrganization: getForOrganization,
        getForSpace: getForSpace,
        getManyForOrganization: getManyForOrganization,
        getManyForSpace: getManyForSpace
    });

    const getUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/ui_config/me`;
    const get$3 = (http, params) => {
        return get$1f(http, getUrl(params));
    };
    const update$3 = (http, params, rawData) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
            },
        });
    };

    var UserUIConfig = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get: get$3,
        update: update$3
    });

    const getBaseUrl$3 = (params) => `/spaces/${params.spaceId}/webhook_definitions`;
    const getWebhookCallBaseUrl = (params) => `/spaces/${params.spaceId}/webhooks`;
    const getWebhookUrl = (params) => `${getBaseUrl$3(params)}/${params.webhookDefinitionId}`;
    const getWebhookCallUrl = (params) => `${getWebhookCallBaseUrl(params)}/${params.webhookDefinitionId}/calls`;
    const getWebhookCallDetailsUrl = (params) => `${getWebhookCallBaseUrl(params)}/${params.webhookDefinitionId}/calls/${params.callId}`;
    const getWebhookHealthUrl = (params) => `${getWebhookCallBaseUrl(params)}/${params.webhookDefinitionId}/health`;
    const getWebhookSettingsUrl = (params) => `/spaces/${params.spaceId}/webhook_settings`;
    const getWebhookSigningSecretUrl = (params) => `${getWebhookSettingsUrl(params)}/signing_secret`;
    const getWebhookRetryPolicyUrl = (params) => `${getWebhookSettingsUrl(params)}/retry_policy`;
    const get$2 = (http, params) => {
        return get$1f(http, getWebhookUrl(params));
    };
    const getManyCallDetails = (http, params) => {
        return get$1f(http, getWebhookCallUrl(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getCallDetails = (http, params) => {
        return get$1f(http, getWebhookCallDetailsUrl(params));
    };
    const getHealthStatus = (http, params) => {
        return get$1f(http, getWebhookHealthUrl(params));
    };
    const getMany$3 = (http, params) => {
        return get$1f(http, getBaseUrl$3(params), {
            params: normalizeSelect(params.query),
        });
    };
    const getSigningSecret = (http, params) => {
        return get$1f(http, getWebhookSigningSecretUrl(params));
    };
    /**
     * @deprecated The EAP for this feature has ended. This method will be removed in the next major version.
     */
    const getRetryPolicy = (http, params) => {
        return get$1f(http, getWebhookRetryPolicyUrl(params));
    };
    const create$2 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$3(params), data, { headers });
    };
    const createWithId = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return put$1(http, getWebhookUrl(params), data, { headers });
    };
    const update$2 = async (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getWebhookUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const upsertSigningSecret = async (http, params, rawData) => {
        const data = index$2(rawData);
        return put$1(http, getWebhookSigningSecretUrl(params), data);
    };
    /**
     * @deprecated The EAP for this feature has ended. This method will be removed in the next major version.
     */
    const upsertRetryPolicy = async (http, params, rawData) => {
        const data = index$2(rawData);
        return put$1(http, getWebhookRetryPolicyUrl(params), data);
    };
    const del$2 = (http, params) => {
        return del$S(http, getWebhookUrl(params));
    };
    const deleteSigningSecret = async (http, params) => {
        return del$S(http, getWebhookSigningSecretUrl(params));
    };
    /**
     * @deprecated The EAP for this feature has ended. This method will be removed in the next major version.
     */
    const deleteRetryPolicy = async (http, params) => {
        return del$S(http, getWebhookRetryPolicyUrl(params));
    };

    var Webhook = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create$2,
        createWithId: createWithId,
        del: del$2,
        deleteRetryPolicy: deleteRetryPolicy,
        deleteSigningSecret: deleteSigningSecret,
        get: get$2,
        getCallDetails: getCallDetails,
        getHealthStatus: getHealthStatus,
        getMany: getMany$3,
        getManyCallDetails: getManyCallDetails,
        getRetryPolicy: getRetryPolicy,
        getSigningSecret: getSigningSecret,
        update: update$2,
        upsertRetryPolicy: upsertRetryPolicy,
        upsertSigningSecret: upsertSigningSecret
    });

    const getBaseUrl$2 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/workflows`;
    const getWorkflowUrl = (params) => `${getBaseUrl$2(params)}/${params.workflowId}`;
    const completeWorkflowUrl = (params) => `${getWorkflowUrl(params)}/complete`;
    const getMany$2 = (http, params, headers) => get$1f(http, getBaseUrl$2(params), {
        headers,
        params: params.query,
    });
    const get$1 = (http, params, headers) => get$1f(http, getWorkflowUrl(params), {
        headers,
    });
    const create$1 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$2(params), data, {
            headers,
        });
    };
    const update$1 = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getWorkflowUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del$1 = (http, { version, ...params }, headers) => {
        return del$S(http, getWorkflowUrl(params), {
            headers: { 'X-Contentful-Version': version, ...headers },
        });
    };
    const complete = (http, { version, ...params }, headers) => {
        return put$1(http, completeWorkflowUrl(params), null, {
            headers: { 'X-Contentful-Version': version, ...headers },
        });
    };

    var Workflow = /*#__PURE__*/Object.freeze({
        __proto__: null,
        complete: complete,
        create: create$1,
        del: del$1,
        get: get$1,
        getMany: getMany$2,
        update: update$1
    });

    const getBaseUrl$1 = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/workflow_definitions`;
    const getWorkflowDefinitionUrl = (params) => `${getBaseUrl$1(params)}/${params.workflowDefinitionId}`;
    const get = (http, params, headers) => get$1f(http, getWorkflowDefinitionUrl(params), {
        headers,
    });
    const getMany$1 = (http, params, headers) => get$1f(http, getBaseUrl$1(params), {
        headers,
        params: params.query,
    });
    const create = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        return post$1(http, getBaseUrl$1(params), data, {
            headers,
        });
    };
    const update = (http, params, rawData, headers) => {
        const data = index$2(rawData);
        delete data.sys;
        return put$1(http, getWorkflowDefinitionUrl(params), data, {
            headers: {
                'X-Contentful-Version': rawData.sys.version ?? 0,
                ...headers,
            },
        });
    };
    const del = (http, { version, ...params }, headers) => {
        return del$S(http, getWorkflowDefinitionUrl(params), {
            headers: { 'X-Contentful-Version': version, ...headers },
        });
    };

    var WorkflowDefinition = /*#__PURE__*/Object.freeze({
        __proto__: null,
        create: create,
        del: del,
        get: get,
        getMany: getMany$1,
        update: update
    });

    const getBaseUrl = (params) => `/spaces/${params.spaceId}/environments/${params.environmentId}/workflows_changelog`;
    const getMany = (http, params, headers) => get$1f(http, getBaseUrl(params), {
        headers,
        params: params.query,
    });

    var WorkflowsChangelog = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getMany: getMany
    });

    var endpoints = {
        AiAction,
        AiActionInvocation,
        Agent,
        AgentRun,
        ApiKey,
        AutomationDefinition,
        AutomationExecution,
        AppAction,
        AppActionCall,
        AppBundle,
        AppDefinition,
        AppInstallation,
        AppUpload,
        AppSignedRequest,
        AppSigningSecret,
        AppEventSubscription,
        AppKey,
        AppAccessToken,
        AppDetails,
        Asset,
        AssetKey,
        AvailableLicense,
        BulkAction,
        Comment,
        Component,
        ComponentType,
        Concept,
        ConceptScheme,
        ContentType,
        DataAssembly,
        DesignToken,
        EditorInterface,
        EligibleLicense,
        Entry,
        Environment,
        EnvironmentAlias,
        EnvironmentTemplate,
        EnvironmentTemplateInstallation,
        Extension,
        Fragment,
        Function: Function$1,
        FunctionLog,
        Http,
        Locale,
        Organization,
        OrganizationInvitation,
        OrganizationMembership,
        OAuthApplication,
        PersonalAccessToken,
        AccessToken,
        PreviewApiKey,
        Release,
        ReleaseAsset,
        ReleaseEntry,
        ReleaseAction,
        Resource,
        ResourceProvider,
        ResourceType,
        Role,
        ScheduledAction,
        ContentSemanticsIndex,
        SemanticDuplicates,
        SemanticRecommendations,
        SemanticReferenceSuggestions,
        SemanticSearch,
        SemanticSettings,
        Snapshot,
        Space,
        SpaceAddOn,
        SpaceMember,
        SpaceMembership,
        Tag,
        Task,
        Team,
        TeamMembership,
        TeamSpaceMembership,
        Template,
        UIConfig,
        Upload,
        UploadCredential,
        Experience,
        ExperienceVariant,
        ExperienceFragment,
        ExperienceTemplate,
        ExperienceFragmentVariant,
        Usage,
        User,
        UserUIConfig,
        Webhook,
        WorkflowDefinition,
        Workflow,
        WorkflowsChangelog,
    };

    const makeRequest = async ({ axiosInstance, entityType, action: actionInput, params, payload, headers, userAgent, }) => {
        // `delete` is a reserved keyword. Therefore, the methods are called `del`.
        const action = actionInput === 'delete' ? 'del' : actionInput;
        const endpoint = 
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        endpoints[entityType]?.[action];
        if (endpoint === undefined) {
            throw new Error('Unknown endpoint');
        }
        return await endpoint(axiosInstance, params, payload, {
            ...headers,
            // overwrite the userAgent with the one passed in the request
            ...(userAgent ? { 'X-Contentful-User-Agent': userAgent } : {}),
        });
    };

    /**
     * @internal
     */
    const defaultHostParameters = {
        defaultHostname: 'api.contentful.com',
        defaultHostnameUpload: 'upload.contentful.com',
    };
    class RestAdapter {
        constructor(params) {
            if (!params.accessToken) {
                throw new TypeError('Expected parameter accessToken');
            }
            const copiedParams = index$2(params);
            // httpAgent and httpsAgent cannot be copied because they can contain private fields
            copiedParams.httpAgent = params.httpAgent;
            copiedParams.httpsAgent = params.httpsAgent;
            this.params = {
                ...defaultHostParameters,
                ...copiedParams,
            };
            this.axiosInstance = createHttpClient(axios, {
                ...this.params,
                headers: {
                    'Content-Type': 'application/vnd.contentful.management.v1+json',
                    // possibly define a default user agent?
                    ...(params.userAgent ? { 'X-Contentful-User-Agent': params.userAgent } : {}),
                    ...this.params.headers,
                },
            });
        }
        async makeRequest(opts) {
            return makeRequest({ ...opts, axiosInstance: this.axiosInstance });
        }
    }

    /**
     * @packageDocumentation
     * @hidden
     */
    /**
     * @internal
     */
    function createAdapter(params) {
        if ('apiAdapter' in params) {
            return params.apiAdapter;
        }
        else {
            return new RestAdapter(params);
        }
    }

    /**
     * @internal
     * Wraps the raw eligible license data
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw eligible license data
     * @returns Wrapped eligible license data
     */
    function wrapEligibleLicense(makeRequest, data) {
        return toPlainObject(index$2(data));
    }
    /**
     * @internal
     */
    const wrapEligibleLicenseCollection = wrapCollection(wrapEligibleLicense);

    /**
     * This method enhances a base object which would normally contain data, with
     * methods from another object that might work on manipulating that data.
     * All the added methods are set as non enumerable, non configurable, and non
     * writable properties. This ensures that if we try to clone or stringify the
     * base object, we don't have to worry about these additional methods.
     * @internal
     * @param {object} baseObject - Base object with data
     * @param {object} methodsObject - Object with methods as properties. The key
     * values used here will be the same that will be defined on the baseObject.
     */
    function enhanceWithMethods(baseObject, methodsObject) {
        return Object.keys(methodsObject).reduce((enhancedObject, methodName) => {
            Object.defineProperty(enhancedObject, methodName, {
                enumerable: false,
                configurable: true,
                writable: false,
                value: methodsObject[methodName],
            });
            return enhancedObject;
        }, baseObject);
    }

    /**
     * Helper function that resolves a Promise after the specified duration (in milliseconds)
     * @internal
     */
    function sleep(durationMs) {
        return new Promise((resolve) => setTimeout(resolve, durationMs));
    }

    /* eslint-disable @typescript-eslint/no-explicit-any */
    const DEFAULT_MAX_RETRIES = 30;
    const DEFAULT_INITIAL_DELAY_MS = 1000;
    const DEFAULT_RETRY_INTERVAL_MS = 2000;
    class AsyncActionProcessingError extends Error {
        constructor(message, action) {
            super(message);
            this.action = action;
            this.name = this.constructor.name;
        }
    }
    class AsyncActionFailedError extends AsyncActionProcessingError {
    }
    /**
     * @description Waits for an Action to be completed and to be in one of the final states (failed or succeeded)
     * @param {Function} actionFunction - GET function that will be called every interval to fetch an Action status
     * @throws {ActionFailedError} throws an error if `throwOnFailedExecution = true` with the Action that failed.
     * @throws {AsyncActionProcessingError} throws an error with a Action when processing takes too long.
     */
    async function pollAsyncActionStatus(actionFunction, options) {
        let retryCount = 0;
        let done = false;
        let action;
        const maxRetries = options?.retryCount ?? DEFAULT_MAX_RETRIES;
        const retryIntervalMs = options?.retryIntervalMs ?? DEFAULT_RETRY_INTERVAL_MS;
        const initialDelayMs = options?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
        const throwOnFailedExecution = options?.throwOnFailedExecution ?? true;
        // Initial delay for short-running Actions
        await sleep(initialDelayMs);
        while (retryCount < maxRetries && !done) {
            action = await actionFunction();
            // Terminal states
            if (action && ['succeeded', 'failed'].includes(action.sys.status)) {
                done = true;
                if (action.sys.status === 'failed' && throwOnFailedExecution) {
                    throw new AsyncActionFailedError(`${action.sys.type} failed to execute.`, action);
                }
                return action;
            }
            await sleep(retryIntervalMs);
            retryCount += 1;
        }
        throw new AsyncActionProcessingError(`${action?.sys.type} didn't finish processing within the expected timeframe.`, action);
    }

    /* eslint-disable @typescript-eslint/no-explicit-any */
    /**
     * @internal
     */
    function createReleaseActionApi(makeRequest) {
        const getParams = (self) => {
            const action = self.toPlainObject();
            return {
                spaceId: action.sys.space.sys.id,
                environmentId: action.sys.environment.sys.id,
                releaseId: action.sys.release.sys.id,
                actionId: action.sys.id,
            };
        };
        return {
            async get() {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'ReleaseAction',
                    action: 'get',
                    params,
                }).then((releaseAction) => wrapReleaseAction(makeRequest, releaseAction));
            },
            /** Waits for a Release Action to complete */
            async waitProcessing(options) {
                return pollAsyncActionStatus(async () => this.get(), options);
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw Release data
     * @returns Wrapped Release data
     */
    function wrapReleaseAction(makeRequest, data) {
        const releaseAction = toPlainObject(index$2(data));
        const releaseActionWithApiMethods = enhanceWithMethods(releaseAction, createReleaseActionApi(makeRequest));
        return freezeSys(releaseActionWithApiMethods);
    }
    /**
     * @internal
     */
    const wrapReleaseActionCollection = wrapCollection(wrapReleaseAction);

    /** @internal */
    var ScheduledActionReferenceFilters;
    (function (ScheduledActionReferenceFilters) {
        ScheduledActionReferenceFilters["contentTypeAnnotationNotIn"] = "sys.contentType.metadata.annotations.ContentType[nin]";
    })(ScheduledActionReferenceFilters || (ScheduledActionReferenceFilters = {}));

    /* eslint-disable @typescript-eslint/no-explicit-any */
    /**
     * @internal
     */
    function createReleaseApi(makeRequest) {
        const getParams = (self) => {
            const release = self.toPlainObject();
            return {
                spaceId: release.sys.space.sys.id,
                environmentId: release.sys.environment.sys.id,
                releaseId: release.sys.id,
                version: release.sys.version,
            };
        };
        return {
            async archive() {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'Release',
                    action: 'archive',
                    params,
                }).then((release) => wrapRelease(makeRequest, release));
            },
            async unarchive() {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'Release',
                    action: 'unarchive',
                    params,
                }).then((release) => wrapRelease(makeRequest, release));
            },
            async update(payload) {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'Release',
                    action: 'update',
                    params,
                    payload,
                }).then((release) => wrapRelease(makeRequest, release));
            },
            async delete() {
                const params = getParams(this);
                await makeRequest({
                    entityType: 'Release',
                    action: 'delete',
                    params,
                });
            },
            async publish(options) {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'Release',
                    action: 'publish',
                    params,
                })
                    .then((data) => wrapReleaseAction(makeRequest, data))
                    .then((action) => action.waitProcessing(options));
            },
            async unpublish(options) {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'Release',
                    action: 'unpublish',
                    params,
                })
                    .then((data) => wrapReleaseAction(makeRequest, data))
                    .then((action) => action.waitProcessing(options));
            },
            async validate(options) {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'Release',
                    action: 'validate',
                    params,
                    payload: options?.payload,
                })
                    .then((data) => wrapReleaseAction(makeRequest, data))
                    .then((action) => action.waitProcessing(options?.processingOptions));
            },
        };
    }
    /**
     * Return a Release object enhanced with its own API helper functions.
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw Release data
     * @returns Wrapped Release data
     */
    function wrapRelease(makeRequest, data) {
        const release = toPlainObject(index$2(data));
        const releaseWithApiMethods = enhanceWithMethods(release, createReleaseApi(makeRequest));
        return freezeSys(releaseWithApiMethods);
    }
    /**
     * @internal
     */
    const wrapReleaseCollection = wrapCursorPaginatedCollection(wrapRelease);

    /**
     * @internal
     */
    function createTagApi(makeRequest) {
        const getParams = (tag) => ({
            spaceId: tag.sys.space.sys.id,
            environmentId: tag.sys.environment.sys.id,
            tagId: tag.sys.id,
        });
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Tag',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapTag(makeRequest, data));
            },
            delete: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Tag',
                    action: 'delete',
                    params: {
                        ...getParams(raw),
                        version: raw.sys.version,
                    },
                }).then(() => {
                    // noop
                });
            },
        };
    }
    /**
     * @internal
     */
    function wrapTag(makeRequest, data) {
        const tag = toPlainObject(index$2(data));
        const tagWithMethods = enhanceWithMethods(tag, createTagApi(makeRequest));
        return freezeSys(tagWithMethods);
    }
    /**
     * @internal
     */
    const wrapTagCollection = wrapCollection(wrapTag);

    /**
     * @internal
     */
    function createUIConfigApi(makeRequest) {
        const getParams = (self) => {
            const uiConfig = self.toPlainObject();
            return {
                params: {
                    spaceId: uiConfig.sys.space.sys.id,
                    environmentId: uiConfig.sys.environment.sys.id,
                },
                raw: uiConfig,
            };
        };
        return {
            /**
             * Sends an update to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getUIConfig())
             * .then((uiConfig) => {
             *   uiConfig.entryListViews = [...]
             *   return uiConfig.update()
             * })
             * .then((uiConfig) => console.log(`UIConfig updated.`))
             * .catch(console.error)
             * ```
             */
            update: async function update() {
                const { raw, params } = getParams(this);
                const data = await makeRequest({
                    entityType: 'UIConfig',
                    action: 'update',
                    params,
                    payload: raw,
                });
                return wrapUIConfig(makeRequest, data);
            },
        };
    }

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw data
     * @returns Wrapped UIConfig
     */
    function wrapUIConfig(makeRequest, data) {
        const user = toPlainObject(index$2(data));
        const userWithMethods = enhanceWithMethods(user, createUIConfigApi(makeRequest));
        return freezeSys(userWithMethods);
    }

    /**
     * @internal
     */
    function createUserUIConfigApi(makeRequest) {
        const getParams = (self) => {
            const userUIConfig = self.toPlainObject();
            return {
                params: {
                    spaceId: userUIConfig.sys.space.sys.id,
                    environmentId: userUIConfig.sys.environment.sys.id,
                },
                raw: userUIConfig,
            };
        };
        return {
            /**
             * Sends an update to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getUserUIConfig())
             * .then((uiConfig) => {
             *   uiConfig.entryListViews = [...]
             *   return uiConfig.update()
             * })
             * .then((uiConfig) => console.log(`UserUIConfig updated.`))
             * .catch(console.error)
             * ```
             */
            update: async function update() {
                const { raw, params } = getParams(this);
                const data = await makeRequest({
                    entityType: 'UserUIConfig',
                    action: 'update',
                    params,
                    payload: raw,
                });
                return wrapUserUIConfig(makeRequest, data);
            },
        };
    }

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw data
     * @returns Wrapped UserUIConfig
     */
    function wrapUserUIConfig(makeRequest, data) {
        const user = toPlainObject(index$2(data));
        const userWithMethods = enhanceWithMethods(user, createUserUIConfigApi(makeRequest));
        return freezeSys(userWithMethods);
    }

    var EnvironmentTemplateInstallationStatuses;
    (function (EnvironmentTemplateInstallationStatuses) {
        EnvironmentTemplateInstallationStatuses["created"] = "created";
        EnvironmentTemplateInstallationStatuses["inProgress"] = "inProgress";
        EnvironmentTemplateInstallationStatuses["failed"] = "failed";
        EnvironmentTemplateInstallationStatuses["succeeded"] = "succeeded";
        EnvironmentTemplateInstallationStatuses["disconnected"] = "disconnected";
        EnvironmentTemplateInstallationStatuses["inRetry"] = "inRetry";
    })(EnvironmentTemplateInstallationStatuses || (EnvironmentTemplateInstallationStatuses = {}));
    function wrapEnvironmentTemplateInstallation(makeRequest, data) {
        const environmentTemplate = toPlainObject(index$2(data));
        return freezeSys(environmentTemplate);
    }
    const wrapEnvironmentTemplateInstallationCollection = wrapCursorPaginatedCollection(wrapEnvironmentTemplateInstallation);

    /**
     * @internal
     */
    function createFunctionApi(makeRequest) {
        return {
            getFunction: function getFunction() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Function',
                    action: 'get',
                    params: {
                        organizationId: raw.sys.organization.sys.id,
                        appDefinitionId: raw.sys.appDefinition.sys.id,
                        functionId: raw.sys.id,
                    },
                }).then((data) => wrapFunction(makeRequest, data));
            },
            getManyFunctions: function getManyFunctions() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Function',
                    action: 'getMany',
                    params: {
                        appDefinitionId: raw.sys.appDefinition.sys.id,
                        organizationId: raw.sys.organization.sys.id,
                    },
                }).then((data) => wrapFunctionCollection(makeRequest, data));
            },
            getManyFunctionsForEnvironment(spaceId, environmentId, appInstallationId) {
                return makeRequest({
                    entityType: 'Function',
                    action: 'getManyForEnvironment',
                    params: {
                        spaceId: spaceId,
                        environmentId: environmentId,
                        appInstallationId: appInstallationId,
                    },
                }).then((data) => wrapFunctionCollection(makeRequest, data));
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - (real) function to make requests via an adapter
     * @param data - raw contentful-Function data
     * @returns Wrapped Function data
     */
    function wrapFunction(makeRequest, data) {
        const func = toPlainObject(index$2(data));
        const funcWithMethods = enhanceWithMethods(func, createFunctionApi(makeRequest));
        return freezeSys(funcWithMethods);
    }
    /**
     * @internal
     */
    const wrapFunctionCollection = wrapCollection(wrapFunction);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - raw contentful-Function data
     * @returns Wrapped Function data
     */
    function wrapFunctionLog(makeRequest, data) {
        const functionLog = toPlainObject(index$2(data));
        return freezeSys(functionLog);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - raw contentful-function data
     * @returns Wrapped App Function collection data
     */
    const wrapFunctionLogCollection = wrapCollection(wrapFunctionLog);

    const isPublished = (data) => !!data.sys.publishedVersion;
    const isUpdated = (data) => {
        // The act of publishing an entity increases its version by 1, so any entry which has
        // 2 versions higher or more than the publishedVersion has unpublished changes.
        return !!(data.sys.publishedVersion && data.sys.version > data.sys.publishedVersion + 1);
    };
    const isDraft = (data) => !data.sys.publishedVersion;
    const isArchived = (data) => !!data.sys.archivedVersion;

    /**
     * @internal
     */
    function createEditorInterfaceApi(makeRequest) {
        return {
            update: function () {
                const self = this;
                const raw = self.toPlainObject();
                return makeRequest({
                    entityType: 'EditorInterface',
                    action: 'update',
                    params: {
                        spaceId: self.sys.space.sys.id,
                        environmentId: self.sys.environment.sys.id,
                        contentTypeId: self.sys.contentType.sys.id,
                    },
                    payload: raw,
                }).then((response) => wrapEditorInterface(makeRequest, response));
            },
            getControlForField: function (fieldId) {
                const self = this;
                const result = (self.controls || []).filter((control) => {
                    return control.fieldId === fieldId;
                });
                return result && result.length > 0 ? result[0] : null;
            },
        };
    }
    /**
     * @internal
     */
    function wrapEditorInterface(makeRequest, data) {
        const editorInterface = toPlainObject(index$2(data));
        const editorInterfaceWithMethods = enhanceWithMethods(editorInterface, createEditorInterfaceApi(makeRequest));
        return freezeSys(editorInterfaceWithMethods);
    }
    /**
     * @internal
     */
    const wrapEditorInterfaceCollection = wrapCollection(wrapEditorInterface);

    /**
     * @internal
     */
    function createSnapshotApi() {
        return {
        /* In case the snapshot object evolve later */
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw snapshot data
     * @returns Wrapped snapshot data
     */
    function wrapSnapshot(_makeRequest, data) {
        const snapshot = toPlainObject(index$2(data));
        const snapshotWithMethods = enhanceWithMethods(snapshot, createSnapshotApi());
        return freezeSys(snapshotWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw snapshot collection data
     * @returns Wrapped snapshot collection data
     */
    const wrapSnapshotCollection = wrapCollection(wrapSnapshot);

    /**
     * @internal
     * @param id - unique ID of the field
     * @param key - the attribute on the field to change
     * @param value - the value to set the attribute to
     */
    const findAndUpdateField = function (contentType, fieldId, omitOrDelete) {
        const field = contentType.fields.find((field) => field.id === fieldId);
        if (!field) {
            return Promise.reject(new Error(`Tried to omitAndDeleteField on a nonexistent field, ${fieldId}, on the content type ${contentType.name}.`));
        }
        field[omitOrDelete] = true;
        return Promise.resolve(contentType);
    };
    const omitAndDeleteField = (makeRequest, { fieldId, ...params }, contentType) => {
        return findAndUpdateField(contentType, fieldId, 'omitted')
            .then((newContentType) => {
            return makeRequest({
                entityType: 'ContentType',
                action: 'update',
                params,
                payload: newContentType,
            });
        })
            .then((newContentType) => {
            return makeRequest({
                entityType: 'ContentType',
                action: 'publish',
                params,
                payload: newContentType,
            });
        })
            .then((newContentType) => {
            return findAndUpdateField(newContentType, fieldId, 'deleted');
        })
            .then((newContentType) => {
            return makeRequest({
                entityType: 'ContentType',
                action: 'update',
                params,
                payload: newContentType,
            });
        });
    };

    /**
     * @internal
     */
    function createContentTypeApi(makeRequest) {
        const getParams = (self) => {
            const contentType = self.toPlainObject();
            return {
                raw: contentType,
                params: {
                    spaceId: contentType.sys.space.sys.id,
                    environmentId: contentType.sys.environment.sys.id,
                    contentTypeId: contentType.sys.id,
                },
            };
        };
        return {
            update: function () {
                const { raw, params } = getParams(this);
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'update',
                    params,
                    payload: raw,
                }).then((data) => wrapContentType(makeRequest, data));
            },
            delete: function () {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'delete',
                    params,
                }).then(() => {
                    // noop
                });
            },
            publish: function () {
                const { raw, params } = getParams(this);
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'publish',
                    params,
                    payload: raw,
                }).then((data) => wrapContentType(makeRequest, data));
            },
            unpublish: function () {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'unpublish',
                    params,
                }).then((data) => wrapContentType(makeRequest, data));
            },
            getEditorInterface: function () {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'EditorInterface',
                    action: 'get',
                    params,
                }).then((data) => wrapEditorInterface(makeRequest, data));
            },
            getSnapshots: function (query = {}) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Snapshot',
                    action: 'getManyForContentType',
                    params: { ...params, query },
                }).then((data) => wrapSnapshotCollection(makeRequest, data));
            },
            getSnapshot: function (snapshotId) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Snapshot',
                    action: 'getForContentType',
                    params: { ...params, snapshotId },
                }).then((data) => wrapSnapshot(makeRequest, data));
            },
            isPublished: function () {
                return isPublished(this);
            },
            isUpdated: function () {
                return isUpdated(this);
            },
            isDraft: function () {
                return isDraft(this);
            },
            omitAndDeleteField: function (fieldId) {
                const { raw, params } = getParams(this);
                return omitAndDeleteField(makeRequest, { ...params, fieldId }, raw).then((data) => wrapContentType(makeRequest, data));
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw content type data
     * @returns Wrapped content type data
     */
    function wrapContentType(makeRequest, data) {
        const contentType = toPlainObject(index$2(data));
        const contentTypeWithMethods = enhanceWithMethods(contentType, createContentTypeApi(makeRequest));
        return freezeSys(contentTypeWithMethods);
    }
    /**
     * @internal
     */
    const wrapContentTypeCollection = wrapCollection(wrapContentType);
    /**
     * @internal
     */
    const wrapContentTypeCursorPaginatedCollection = wrapCursorPaginatedCollection(wrapContentType);

    /**
     * @internal
     */
    function createTaskApi(makeRequest) {
        const getParams = (task) => {
            const parentEntity = task.sys.parentEntity;
            return {
                spaceId: task.sys.space.sys.id,
                environmentId: task.sys.environment.sys.id,
                parentEntityType: parentEntity.sys.linkType,
                parentEntityId: parentEntity.sys.id,
                taskId: task.sys.id,
            };
        };
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Task',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapTask(makeRequest, data));
            },
            delete: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Task',
                    action: 'delete',
                    params: {
                        ...getParams(raw),
                        version: raw.sys.version,
                    },
                }).then(() => {
                    // noop
                });
            },
        };
    }
    /**
     * @internal
     */
    function wrapTask(makeRequest, data) {
        const task = toPlainObject(index$2(data));
        const taskWithMethods = enhanceWithMethods(task, createTaskApi(makeRequest));
        return freezeSys(taskWithMethods);
    }
    /**
     * @internal
     */
    const wrapTaskCollection = wrapCollection(wrapTask);

    // Remove and replace with BLOCKS as soon as rich-text-types supports mentions
    var CommentNode;
    (function (CommentNode) {
        CommentNode["Document"] = "document";
        CommentNode["Paragraph"] = "paragraph";
        CommentNode["Mention"] = "mention";
    })(CommentNode || (CommentNode = {}));
    /**
     * @internal
     */
    function createCommentApi(makeRequest) {
        const getParams = (comment) => {
            const parentEntity = comment.sys.parentEntity;
            return {
                spaceId: comment.sys.space.sys.id,
                environmentId: comment.sys.environment.sys.id,
                commentId: comment.sys.id,
                parentEntityType: parentEntity.sys.linkType,
                parentEntityId: parentEntity.sys.id,
            };
        };
        return {
            update: async function () {
                const raw = this.toPlainObject();
                const data = await makeRequest({
                    entityType: 'Comment',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                });
                return wrapComment(makeRequest, data);
            },
            delete: async function () {
                const raw = this.toPlainObject();
                await makeRequest({
                    entityType: 'Comment',
                    action: 'delete',
                    params: {
                        ...getParams(raw),
                        version: raw.sys.version,
                    },
                });
            },
        };
    }
    /**
     * @internal
     */
    function wrapComment(makeRequest, data) {
        const comment = toPlainObject(index$2(data));
        const commentWithMethods = enhanceWithMethods(comment, createCommentApi(makeRequest));
        return freezeSys(commentWithMethods);
    }
    /**
     * @internal
     */
    const wrapCommentCollection = wrapCollection(wrapComment);

    /**
     * @internal
     */
    function createEntryApi(makeRequest) {
        const getParams = (self) => {
            const entry = self.toPlainObject();
            return {
                params: {
                    spaceId: entry.sys.space.sys.id,
                    environmentId: entry.sys.environment.sys.id,
                    entryId: entry.sys.id,
                },
                raw: entry,
            };
        };
        return {
            /**
             * Sends an update to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => {
             *   entry.fields.title['en-US'] = 'New entry title'
             *   return entry.update()
             * })
             * .then((entry) => console.log(`Entry ${entry.sys.id} updated.`))
             * .catch(console.error)
             * ```
             */
            update: function update() {
                const { raw, params } = getParams(this);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'update',
                    params,
                    payload: raw,
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Sends an JSON patch to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.patch([
             *   {
             *     op: 'replace',
             *     path: '/fields/title/en-US',
             *     value: 'New entry title'
             *   }
             * ]))
             * .then((entry) => console.log(`Entry ${entry.sys.id} updated.`))
             * .catch(console.error)
             * ```
             */
            patch: function patch(ops) {
                const { raw, params } = getParams(this);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'patch',
                    params: {
                        ...params,
                        version: raw.sys.version,
                    },
                    payload: ops,
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Deletes this object on the server.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.delete())
             * .then(() => console.log(`Entry deleted.`))
             * .catch(console.error)
             * ```
             */
            delete: function del() {
                const { params } = getParams(this);
                return makeRequest({ entityType: 'Entry', action: 'delete', params });
            },
            /**
             * Publishes the object
             * @returns Object returned from the server with updated metadata.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.publish())
             * .then((entry) => console.log(`Entry ${entry.sys.id} published.`))
             * .catch(console.error)
             * ```
             */
            publish: function publish() {
                const { raw, params } = getParams(this);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'publish',
                    params,
                    payload: raw,
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Unpublishes the object
             * @returns Object returned from the server with updated metadata.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.unpublish())
             * .then((entry) => console.log(`Entry ${entry.sys.id} unpublished.`))
             * .catch(console.error)
             * ```
             */
            unpublish: function unpublish() {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'unpublish',
                    params,
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Archives the object
             * @returns Object returned from the server with updated metadata.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.archive())
             * .then((entry) => console.log(`Entry ${entry.sys.id} archived.`))
             * .catch(console.error)
             * ```
             */
            archive: function archive() {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'archive',
                    params,
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Unarchives the object
             * @returns Object returned from the server with updated metadata.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.unarchive())
             * .then((entry) => console.log(`Entry ${entry.sys.id} unarchived.`))
             * .catch(console.error)
             * ```
             */
            unarchive: function unarchive() {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'unarchive',
                    params,
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Gets all snapshots of an entry
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.getSnapshots())
             * .then((snapshots) => console.log(snapshots.items))
             * .catch(console.error)
             * ```
             */
            getSnapshots: function (query = {}) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Snapshot',
                    action: 'getManyForEntry',
                    params: { ...params, query },
                }).then((data) => wrapSnapshotCollection(makeRequest, data));
            },
            /**
             * Gets a snapshot of an entry
             * @param snapshotId - Id of the snapshot
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntry('<entry_id>'))
             * .then((entry) => entry.getSnapshot('<snapshot_id>'))
             * .then((snapshot) => console.log(snapshot))
             * .catch(console.error)
             * ```
             */
            getSnapshot: function (snapshotId) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Snapshot',
                    action: 'getForEntry',
                    params: { ...params, snapshotId },
                }).then((data) => wrapSnapshot(makeRequest, data));
            },
            /**
             * Creates a new comment for an entry
             * @param data Object representation of the Comment to be created
             * @returns Promise for the newly created Comment
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => entry.createComment({
             *   body: 'Something left to do'
             * }))
             * .then((comment) => console.log(comment))
             * .catch(console.error)
             * ```
             */
            createComment: function (data) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Comment',
                    action: 'create',
                    params: {
                        spaceId: params.spaceId,
                        environmentId: params.environmentId,
                        parentEntityId: params.entryId,
                        parentEntityType: 'Entry',
                    },
                    payload: data,
                }).then((data) => wrapComment(makeRequest, data));
            },
            /**
             * Gets all comments of an entry
             * @returns
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => entry.getComments())
             * .then((comments) => console.log(comments))
             * .catch(console.error)
             * ```
             */
            getComments: function () {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Comment',
                    action: 'getMany',
                    params,
                }).then((data) => wrapCommentCollection(makeRequest, data));
            },
            /**
             * Gets a comment of an entry
             * @returns
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => entry.getComment(`<comment-id>`))
             * .then((comment) => console.log(comment))
             * .catch(console.error)
             * ```
             */
            getComment: function (id) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Comment',
                    action: 'get',
                    params: {
                        ...params,
                        commentId: id,
                    },
                }).then((data) => wrapComment(makeRequest, data));
            },
            /**
             * Creates a new task for an entry
             * @param data Object representation of the Task to be created
             * @returns Promise for the newly created Task
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => entry.createTask({
             *   body: 'Something left to do',
             *   assignedTo: '<user-id>',
             *   status: 'active'
             * }))
             * .then((task) => console.log(task))
             * .catch(console.error)
             * ```
             */
            createTask: function (data) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Task',
                    action: 'create',
                    params,
                    payload: data,
                }).then((data) => wrapTask(makeRequest, data));
            },
            /**
             * Gets all tasks of an entry
             * @returns
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => entry.getTasks())
             * .then((tasks) => console.log(tasks))
             * .catch(console.error)
             * ```
             */
            getTasks: function (query = {}) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Task',
                    action: 'getMany',
                    params: { ...params, query },
                }).then((data) => wrapTaskCollection(makeRequest, data));
            },
            /**
             * Gets a task of an entry
             * @returns
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => entry.getTask(`<task-id>`))
             * .then((task) => console.log(task))
             * .catch(console.error)
             * ```
             */
            getTask: function (id) {
                const { params } = getParams(this);
                return makeRequest({
                    entityType: 'Task',
                    action: 'get',
                    params: {
                        ...params,
                        taskId: id,
                    },
                }).then((data) => wrapTask(makeRequest, data));
            },
            /**
             * Checks if the entry is published. A published entry might have unpublished changes
             */
            isPublished: function isPublished$1() {
                const raw = this.toPlainObject();
                return isPublished(raw);
            },
            /**
             * Checks if the entry is updated. This means the entry was previously published but has unpublished changes.
             */
            isUpdated: function isUpdated$1() {
                const raw = this.toPlainObject();
                return isUpdated(raw);
            },
            /**
             * Checks if the entry is in draft mode. This means it is not published.
             */
            isDraft: function isDraft$1() {
                const raw = this.toPlainObject();
                return isDraft(raw);
            },
            /**
             * Checks if entry is archived. This means it's not exposed to the Delivery/Preview APIs.
             */
            isArchived: function isArchived$1() {
                const raw = this.toPlainObject();
                return isArchived(raw);
            },
            /**
             * Recursively collects references of an entry and their descendants
             */
            references: function references(options) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'references',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.environment.sys.id,
                        entryId: raw.sys.id,
                        include: options?.include,
                    },
                }).then((response) => wrapEntryCollection(makeRequest, response));
            },
        };
    }

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw entry data
     * @returns Wrapped entry data
     */
    function wrapEntry(makeRequest, data) {
        const entry = toPlainObject(index$2(data));
        const entryWithMethods = enhanceWithMethods(entry, createEntryApi(makeRequest));
        return freezeSys(entryWithMethods);
    }
    /**
     * Data is also mixed in with link getters if links exist and includes were requested
     * @internal
     */
    const wrapEntryCollection = wrapCollection(wrapEntry);
    /**
     * @internal
     */
    const wrapEntryTypeCursorPaginatedCollection = wrapCursorPaginatedCollection(wrapEntry);

    /**
     * @internal
     */
    function createAssetApi(makeRequest) {
        const getParams = (raw) => {
            return {
                spaceId: raw.sys.space.sys.id,
                environmentId: raw.sys.environment.sys.id,
                assetId: raw.sys.id,
            };
        };
        return {
            processForLocale: function processForLocale(locale, options) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'processForLocale',
                    params: {
                        ...getParams(raw),
                        locale,
                        options,
                        asset: raw,
                    },
                }).then((data) => wrapAsset(makeRequest, data));
            },
            processForAllLocales: function processForAllLocales(options) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'processForAllLocales',
                    params: {
                        ...getParams(raw),
                        asset: raw,
                        options,
                    },
                }).then((data) => wrapAsset(makeRequest, data));
            },
            update: function update() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                    headers: {},
                }).then((data) => wrapAsset(makeRequest, data));
            },
            delete: function del() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'delete',
                    params: getParams(raw),
                });
            },
            publish: function publish() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'publish',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapAsset(makeRequest, data));
            },
            unpublish: function unpublish() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'unpublish',
                    params: getParams(raw),
                }).then((data) => wrapAsset(makeRequest, data));
            },
            archive: function archive() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'archive',
                    params: getParams(raw),
                }).then((data) => wrapAsset(makeRequest, data));
            },
            unarchive: function unarchive() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'unarchive',
                    params: getParams(raw),
                }).then((data) => wrapAsset(makeRequest, data));
            },
            isPublished: function isPublished$1() {
                const raw = this.toPlainObject();
                return isPublished(raw);
            },
            isUpdated: function isUpdated$1() {
                const raw = this.toPlainObject();
                return isUpdated(raw);
            },
            isDraft: function isDraft$1() {
                const raw = this.toPlainObject();
                return isDraft(raw);
            },
            isArchived: function isArchived$1() {
                const raw = this.toPlainObject();
                return isArchived(raw);
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw asset data
     * @returns Wrapped asset data
     */
    function wrapAsset(makeRequest, data) {
        const asset = toPlainObject(index$2(data));
        const assetWithMethods = enhanceWithMethods(asset, createAssetApi(makeRequest));
        return freezeSys(assetWithMethods);
    }
    /**
     * @internal
     */
    const wrapAssetCollection = wrapCollection(wrapAsset);
    /**
     * @internal
     */
    const wrapAssetTypeCursorPaginatedCollection = wrapCursorPaginatedCollection(wrapAsset);

    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw asset key data
     * @returns Wrapped asset key data
     */
    function wrapAssetKey(_makeRequest, data) {
        const assetKey = toPlainObject(index$2(data));
        return assetKey;
    }

    /**
     * @internal
     */
    function createLocaleApi(makeRequest) {
        const getParams = (locale) => ({
            spaceId: locale.sys.space.sys.id,
            environmentId: locale.sys.environment.sys.id,
            localeId: locale.sys.id,
        });
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Locale',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapLocale(makeRequest, data));
            },
            delete: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Locale',
                    action: 'delete',
                    params: getParams(raw),
                }).then(() => {
                    // noop
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw locale data
     * @returns Wrapped locale data
     */
    function wrapLocale(makeRequest, data) {
        delete data.internal_code;
        const locale = toPlainObject(index$2(data));
        const localeWithMethods = enhanceWithMethods(locale, createLocaleApi(makeRequest));
        return freezeSys(localeWithMethods);
    }
    /**
     * @internal
     */
    const wrapLocaleCollection = wrapCollection(wrapLocale);

    /**
     * @internal
     */
    function createUploadApi(makeRequest) {
        return {
            delete: async function del() {
                const raw = this.toPlainObject();
                await makeRequest({
                    entityType: 'Upload',
                    action: 'delete',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        uploadId: raw.sys.id,
                    },
                });
            },
        };
    }
    /**
     * @internal
     * @param {function} makeRequest - function to make requests via an adapter
     * @param {object} data - Raw upload data
     * @returns {Upload} Wrapped upload data
     */
    function wrapUpload(makeRequest, data) {
        const upload = toPlainObject(index$2(data));
        const uploadWithMethods = enhanceWithMethods(upload, createUploadApi(makeRequest));
        return freezeSys(uploadWithMethods);
    }

    /**
     * @internal
     */
    function createExtensionApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            environmentId: data.sys.environment.sys.id,
            extensionId: data.sys.id,
        });
        return {
            update: function update() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Extension',
                    action: 'update',
                    params: getParams(data),
                    payload: data,
                }).then((response) => wrapExtension(makeRequest, response));
            },
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Extension',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw UI Extension data
     * @returns Wrapped UI Extension data
     */
    function wrapExtension(makeRequest, data) {
        const extension = toPlainObject(index$2(data));
        const extensionWithMethods = enhanceWithMethods(extension, createExtensionApi(makeRequest));
        return freezeSys(extensionWithMethods);
    }
    /**
     * @internal
     */
    const wrapExtensionCollection = wrapCollection(wrapExtension);

    /**
     * @internal
     */
    function createAppInstallationApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            environmentId: data.sys.environment.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
        });
        return {
            update: function update() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppInstallation',
                    action: 'upsert',
                    params: getParams(data),
                    headers: {},
                    payload: data,
                }).then((data) => wrapAppInstallation(makeRequest, data));
            },
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppInstallation',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Installation data
     * @returns Wrapped App installation data
     */
    function wrapAppInstallation(makeRequest, data) {
        const appInstallation = toPlainObject(index$2(data));
        const appInstallationWithMethods = enhanceWithMethods(appInstallation, createAppInstallationApi(makeRequest));
        return freezeSys(appInstallationWithMethods);
    }
    /**
     * @internal
     */
    const wrapAppInstallationCollection = wrapCollection(wrapAppInstallation);

    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppSignedRequest data
     * @returns Wrapped AppSignedRequest data
     */
    function wrapAppSignedRequest(_makeRequest, data) {
        const signedRequest = toPlainObject(index$2(data));
        return signedRequest;
    }

    /**
     * @internal
     */
    function createAppActionCallApi(makeRequest, retryOptions) {
        return {
            createWithResponse: function (params, payload) {
                return makeRequest({
                    entityType: 'AppActionCall',
                    action: 'createWithResponse',
                    params: { ...params, ...retryOptions },
                    payload: payload,
                }).then((data) => wrapAppActionCallResponse(makeRequest, data));
            },
            getCallDetails: function getCallDetails(params) {
                return makeRequest({
                    entityType: 'AppActionCall',
                    action: 'getCallDetails',
                    params,
                }).then((data) => wrapAppActionCallResponse(makeRequest, data));
            },
            get: function get(params) {
                return makeRequest({
                    entityType: 'AppActionCall',
                    action: 'get',
                    params,
                }).then((data) => wrapAppActionCall(makeRequest, data));
            },
            createWithResult: function (params, payload) {
                return makeRequest({
                    entityType: 'AppActionCall',
                    action: 'createWithResult',
                    params: { ...params, ...retryOptions },
                    payload: payload,
                }).then((data) => wrapAppActionCall(makeRequest, data));
            },
        };
    }
    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppActionCall data
     * @returns Wrapped AppActionCall data
     */
    function wrapAppActionCall(makeRequest, data) {
        const signedRequest = toPlainObject(index$2(data));
        const signedRequestWithMethods = enhanceWithMethods(signedRequest, createAppActionCallApi(makeRequest));
        return signedRequestWithMethods;
    }
    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppActionCall data
     * @returns Wrapped AppActionCall data
     */
    function wrapAppActionCallResponse(makeRequest, data, retryOptions) {
        const appActionCallResponse = toPlainObject(index$2(data));
        const appActionCallResponseWithMethods = enhanceWithMethods(appActionCallResponse, createAppActionCallApi(makeRequest, retryOptions));
        return appActionCallResponseWithMethods;
    }

    /* eslint-disable @typescript-eslint/no-explicit-any */
    /** Represents the state of the BulkAction */
    var BulkActionStatus;
    (function (BulkActionStatus) {
        /** BulkAction is pending execution */
        BulkActionStatus["created"] = "created";
        /** BulkAction has been started and pending completion */
        BulkActionStatus["inProgress"] = "inProgress";
        /** BulkAction was completed successfully (terminal state) */
        BulkActionStatus["succeeded"] = "succeeded";
        /** BulkAction failed to complete (terminal state) */
        BulkActionStatus["failed"] = "failed";
    })(BulkActionStatus || (BulkActionStatus = {}));
    Object.values(BulkActionStatus);
    /**
     * @internal
     */
    function createBulkActionApi(makeRequest) {
        const getParams = (self) => {
            const bulkAction = self.toPlainObject();
            return {
                spaceId: bulkAction.sys.space.sys.id,
                environmentId: bulkAction.sys.environment.sys.id,
                bulkActionId: bulkAction.sys.id,
            };
        };
        return {
            async get() {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'BulkAction',
                    action: 'get',
                    params,
                }).then((bulkAction) => wrapBulkAction(makeRequest, bulkAction));
            },
            async waitProcessing(options) {
                return pollAsyncActionStatus(async () => this.get(), options);
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw BulkAction data
     * @returns Wrapped BulkAction data
     */
    function wrapBulkAction(makeRequest, data) {
        const bulkAction = toPlainObject(index$2(data));
        const bulkActionWithApiMethods = enhanceWithMethods(bulkAction, createBulkActionApi(makeRequest));
        return freezeSys(bulkActionWithApiMethods);
    }

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw app access token data
     * @returns {AppAccessToken} Wrapped AppAccessToken data
     */
    function wrapAppAccessToken(_makeRequest, data) {
        const appAccessToken = toPlainObject(index$2(data));
        return freezeSys(appAccessToken);
    }

    /**
     * @internal
     */
    function createResourceTypeApi(makeRequest) {
        return {
            /**
             * Sends an update to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getResourceType())
             * .then((resourceType) => {
             *    resourceType.name = '<new_name>'
             *    return resourceType.upsert()
             * })
             * .catch(console.error)
             * ```
             */
            upsert: function upsert() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceType',
                    action: 'upsert',
                    params: getParams$1(data),
                    headers: {},
                    payload: getUpsertParams$1(data),
                }).then((data) => wrapResourceType(makeRequest, data));
            },
            /**
             * Deletes this object on the server.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getResourceType())
             * .then((resourceType) => resourceType.delete())
             * .catch(console.error)
             * ```
             */
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceType',
                    action: 'delete',
                    params: getParams$1(data),
                });
            },
        };
    }
    const getParams$1 = (data) => ({
        organizationId: data.sys.organization.sys.id,
        appDefinitionId: data.sys.appDefinition.sys.id,
        resourceTypeId: data.sys.id,
    });
    const getUpsertParams$1 = (data) => ({
        name: data.name,
        defaultFieldMapping: data.defaultFieldMapping,
    });
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw Resource Type data
     * @returns Wrapped Resource Type data
     */
    function wrapResourceType(makeRequest, data) {
        const resourceType = toPlainObject(index$2(data));
        const ResourceTypeWithMethods = enhanceWithMethods(resourceType, createResourceTypeApi(makeRequest));
        return freezeSys(ResourceTypeWithMethods);
    }
    function wrapResourceTypeforEnvironment(makeRequest, data) {
        const resourceType = toPlainObject(data);
        return freezeSys(resourceType);
    }
    const wrapResourceTypesForEnvironmentCollection = wrapCursorPaginatedCollection(wrapResourceTypeforEnvironment);

    function wrapResource(makeRequest, data) {
        const resource = toPlainObject(data);
        return freezeSys(resource);
    }
    const wrapResourceCollection = wrapCursorPaginatedCollection(wrapResource);

    /**
     * Wraps raw AI Action Invocation data with SDK helper methods.
     *
     * @param makeRequest - Function to make API requests.
     * @param data - Raw AI Action Invocation data.
     * @returns The AI Action Invocation entity.
     */
    function wrapAiActionInvocation(makeRequest, data) {
        const invocation = toPlainObject(index$2(data));
        return freezeSys(invocation);
    }

    function wrapAgentRun(_makeRequest, data) {
        const agentRun = toPlainObject(index$2(data));
        return freezeSys(agentRun);
    }
    function wrapAgentGenerateResponse(_makeRequest, data) {
        const response = toPlainObject(index$2(data));
        return freezeSys(response);
    }
    const wrapAgentRunCollection = wrapCollection(wrapAgentRun);

    function createAgentApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            environmentId: data.sys.environment.sys.id,
            agentId: data.sys.id,
        });
        return {
            generate: function generate(payload) {
                const self = this;
                return makeRequest({
                    entityType: 'Agent',
                    action: 'generate',
                    params: getParams(self),
                    payload,
                }).then((data) => wrapAgentGenerateResponse(makeRequest, data));
            },
        };
    }
    function wrapAgent(makeRequest, data) {
        const agent = toPlainObject(index$2(data));
        const agentWithMethods = enhanceWithMethods(agent, createAgentApi(makeRequest));
        return freezeSys(agentWithMethods);
    }
    const wrapAgentCollection = wrapCollection(wrapAgent);

    function wrapSemanticDuplicates(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }

    function wrapSemanticRecommendations(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }

    function wrapSemanticReferenceSuggestions(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }

    function wrapSemanticSearch(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }

    function wrapContentSemanticsIndex(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }
    function wrapContentSemanticsIndexCollection(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }

    /**
     * Creates API object with methods to access the Environment API
     * @param {ContentfulEnvironmentAPI} makeRequest - function to make requests via an adapter
     * @returns {ContentfulSpaceAPI}
     * @internal
     */
    function createEnvironmentApi(makeRequest) {
        return {
            /**
             * Deletes the environment
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.delete())
             * .then(() => console.log('Environment deleted.'))
             * .catch(console.error)
             * ```
             */
            delete: function deleteEnvironment() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Environment',
                    action: 'delete',
                    params: { spaceId: raw.sys.space.sys.id, environmentId: raw.sys.id },
                }).then(() => {
                    // noop
                });
            },
            /**
             * Updates the environment
             * @returns Promise for the updated environment.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => {
             *   environment.name = 'New name'
             *   return environment.update()
             * })
             * .then((environment) => console.log(`Environment ${environment.sys.id} renamed.`)
             * .catch(console.error)
             * ```
             */
            update: function updateEnvironment() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Environment',
                    action: 'update',
                    params: { spaceId: raw.sys.space.sys.id, environmentId: raw.sys.id },
                    payload: raw,
                }).then((data) => wrapEnvironment(makeRequest, data));
            },
            /**
             * Creates SDK Entry object (locally) from entry data
             * @param entryData - Entry Data
             * @returns Entry
             * @example ```javascript
             * environment.getEntry('entryId').then(entry => {
             *
             *   // Build a plainObject in order to make it usable for React (saving in state or redux)
             *   const plainObject = entry.toPlainObject();
             *
             *   // The entry is being updated in some way as plainObject:
             *   const updatedPlainObject = {
             *     ...plainObject,
             *     fields: {
             *       ...plainObject.fields,
             *       title: {
             *         'en-US': 'updatedTitle'
             *       }
             *     }
             *   };
             *
             *   // Rebuild an sdk object out of the updated plainObject:
             *   const entryWithMethodsAgain = environment.getEntryFromData(updatedPlainObject);
             *
             *   // Update with help of the sdk method:
             *   entryWithMethodsAgain.update();
             *
             * });
             * ```
             **/
            getEntryFromData(entryData) {
                return wrapEntry(makeRequest, entryData);
            },
            /**
             * Creates SDK Asset object (locally) from entry data
             * @param assetData - Asset ID
             * @returns Asset
             * @example ```javascript
             * environment.getAsset('asset_id').then(asset => {
             *
             *   // Build a plainObject in order to make it usable for React (saving in state or redux)
             *   const plainObject = asset.toPlainObject();
             *
             *   // The asset is being updated in some way as plainObject:
             *   const updatedPlainObject = {
             *     ...plainObject,
             *     fields: {
             *       ...plainObject.fields,
             *       title: {
             *         'en-US': 'updatedTitle'
             *       }
             *     }
             *   };
             *
             *   // Rebuild an sdk object out of the updated plainObject:
             *   const assetWithMethodsAgain = environment.getAssetFromData(updatedPlainObject);
             *
             *   // Update with help of the sdk method:
             *   assetWithMethodsAgain.update();
             *
             * });
             * ```
             */
            getAssetFromData(assetData) {
                return wrapAsset(makeRequest, assetData);
            },
            /**
             *
             * @description Get a BulkAction by ID.
             *  See: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/bulk-actions/bulk-action
             * @param bulkActionId - ID of the BulkAction to fetch
             * @returns - Promise with the BulkAction
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getBulkAction('<bulk_action_id>'))
             * .then((bulkAction) => console.log(bulkAction))
             * ```
             */
            getBulkAction(bulkActionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'BulkAction',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        bulkActionId,
                    },
                }).then((data) => wrapBulkAction(makeRequest, data));
            },
            /**
             * @description Creates a BulkAction that will attempt to publish all items contained in the payload.
             * See: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/bulk-actions/publish-bulk-action
             * @param {BulkActionPayload} payload - Object containing the items to be processed in the bulkAction
             * @returns - Promise with the BulkAction
             *
             * @example
             *
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const payload = {
             *  entities: {
             *    sys: { type: 'Array' }
             *    items: [
             *      { sys: { type: 'Link', id: '<entry-id>', linkType: 'Entry', version: 2 } }
             *    ]
             *  }
             * }
             *
             * // Using Thenables
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.createPublishBulkAction(payload))
             * .then((bulkAction) => console.log(bulkAction.waitProcessing()))
             * .catch(console.error)
             *
             * // Using async/await
             * try {
             *  const space = await client.getSpace('<space_id>')
             *  const environment = await space.getEnvironment('<environment_id>')
             *  const bulkActionInProgress = await environment.createPublishBulkAction(payload)
             *
             *  // You can wait for a recently created BulkAction to be processed by using `bulkAction.waitProcessing()`
             *  const bulkActionCompleted = await bulkActionInProgress.waitProcessing()
             *  console.log(bulkActionCompleted)
             * } catch (error) {
             *  console.log(error)
             * }
             * ```
             */
            createPublishBulkAction(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'BulkAction',
                    action: 'publish',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapBulkAction(makeRequest, data));
            },
            /**
             * @description Creates a BulkAction that will attempt to validate all items contained in the payload.
             * See: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/bulk-actions/validate-bulk-action
             * @param {BulkActionPayload} payload - Object containing the items to be processed in the bulkAction
             * @returns - Promise with the BulkAction
             *
             * @example
             *
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const payload = {
             *  action: 'publish',
             *  entities: {
             *    sys: { type: 'Array' }
             *    items: [
             *      { sys: { type: 'Link', id: '<entry-id>', linkType: 'Entry' } }
             *    ]
             *  }
             * }
             *
             * // Using Thenables
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.createValidateBulkAction(payload))
             * .then((bulkAction) => console.log(bulkAction.waitProcessing()))
             * .catch(console.error)
             *
             * // Using async/await
             * try {
             *  const space = await client.getSpace('<space_id>')
             *  const environment = await space.getEnvironment('<environment_id>')
             *  const bulkActionInProgress = await environment.createValidateBulkAction(payload)
             *
             *  // You can wait for a recently created BulkAction to be processed by using `bulkAction.waitProcessing()`
             *  const bulkActionCompleted = await bulkActionInProgress.waitProcessing()
             *  console.log(bulkActionCompleted)
             * } catch (error) {
             *  console.log(error)
             * }
             * ```
             */
            createValidateBulkAction(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'BulkAction',
                    action: 'validate',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapBulkAction(makeRequest, data));
            },
            /**
             * @description Creates a BulkAction that will attempt to unpublish all items contained in the payload.
             * See: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/bulk-actions/unpublish-bulk-action
             * @param {BulkActionPayload} payload - Object containing the items to be processed in the bulkAction
             * @returns - Promise with the BulkAction
             *
             * @example
             *
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const payload = {
             *  entities: {
             *    sys: { type: 'Array' }
             *    items: [
             *      { sys: { type: 'Link', id: 'entry-id', linkType: 'Entry' } }
             *    ]
             *  }
             * }
             *
             * // Using Thenables
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.createUnpublishBulkAction(payload))
             * .then((bulkAction) => console.log(bulkAction.waitProcessing()))
             * .catch(console.error)
             *
             * // Using async/await
             * try {
             *  const space = await clientgetSpace('<space_id>')
             *  const environment = await space.getEnvironment('<environment_id>')
             *  const bulkActionInProgress = await environment.createUnpublishBulkAction(payload)
             *
             *  // You can wait for a recently created BulkAction to be processed by using `bulkAction.waitProcessing()`
             *  const bulkActionCompleted = await bulkActionInProgress.waitProcessing()
             *  console.log(bulkActionCompleted)
             * } catch (error) {
             *  console.log(error)
             * }
             * ```
             */
            createUnpublishBulkAction(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'BulkAction',
                    action: 'unpublish',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapBulkAction(makeRequest, data));
            },
            /**
             * Gets a Content Type
             * @param contentTypeId - Content Type ID
             * @returns Promise for a Content Type
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getContentType('<content_type_id>'))
             * .then((contentType) => console.log(contentType))
             * .catch(console.error)
             * ```
             */
            getContentType(contentTypeId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        contentTypeId,
                    },
                }).then((data) => wrapContentType(makeRequest, data));
            },
            /**
             * Gets a collection of Content Types
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of Content Types
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getContentTypes())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getContentTypes(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapContentTypeCollection(makeRequest, data));
            },
            /**
             * Gets a collection of Content Types with cursor based pagination
             * @param query - Object with cursor pagination parameters. Check the <a href="https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/cursor-pagination">REST API reference</a> for more details.
             * @returns Promise for a collection of Content Types
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getContentTypesWithCursor())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getContentTypesWithCursor(query = {}) {
                const raw = this.toPlainObject();
                const normalizedQueryParams = normalizeCursorPaginationParameters(query);
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: normalizedQueryParams }).params,
                    },
                }).then((data) => wrapContentTypeCursorPaginatedCollection(makeRequest, normalizeCursorPaginationResponse(data)));
            },
            /**
             * Creates a Content Type
             * @param data - Object representation of the Content Type to be created
             * @returns Promise for the newly created Content Type
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createContentType({
             *   name: 'Blog Post',
             *   fields: [
             *     {
             *       id: 'title',
             *       name: 'Title',
             *       required: true,
             *       localized: false,
             *       type: 'Text'
             *     }
             *   ]
             * }))
             * .then((contentType) => console.log(contentType))
             * .catch(console.error)
             * ```
             */
            createContentType(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload: data,
                }).then((response) => wrapContentType(makeRequest, response));
            },
            /**
             * Creates a Content Type with a custom ID
             * @param contentTypeId - Content Type ID
             * @param data - Object representation of the Content Type to be created
             * @returns Promise for the newly created Content Type
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createContentTypeWithId('<content-type-id>', {
             *   name: 'Blog Post',
             *   fields: [
             *     {
             *       id: 'title',
             *       name: 'Title',
             *       required: true,
             *       localized: false,
             *       type: 'Text'
             *     }
             *   ]
             * }))
             * .then((contentType) => console.log(contentType))
             * .catch(console.error)
             * ```
             */
            createContentTypeWithId(contentTypeId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentType',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        contentTypeId,
                    },
                    payload: data,
                }).then((response) => wrapContentType(makeRequest, response));
            },
            /**
             * Gets an EditorInterface for a ContentType
             * @param contentTypeId - Content Type ID
             * @returns Promise for an EditorInterface
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEditorInterfaceForContentType('<content_type_id>'))
             * .then((EditorInterface) => console.log(EditorInterface))
             * .catch(console.error)
             * ```
             */
            getEditorInterfaceForContentType(contentTypeId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EditorInterface',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        contentTypeId,
                    },
                }).then((response) => wrapEditorInterface(makeRequest, response));
            },
            /**
             * Gets all EditorInterfaces
             * @returns Promise for a collection of EditorInterface
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEditorInterfaces())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEditorInterfaces() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EditorInterface',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((response) => wrapEditorInterfaceCollection(makeRequest, response));
            },
            /**
             * Gets an Entry
             * Warning: if you are using the select operator, when saving, any field that was not selected will be removed
             * from your entry in the backend
             * @param id - Entry ID
             * @param query - Object with search parameters. In this method it's only useful for `locale`.
             * @returns Promise for an Entry
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntry('<entry-id>'))
             * .then((entry) => console.log(entry))
             * .catch(console.error)
             * ```
             */
            getEntry(id, query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        entryId: id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapEntry(makeRequest, data));
            },
            /**
             * Deletes an Entry of this environment
             * @param id - Entry ID
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.deleteEntry("4bmLXiuviAZH3jkj5DLRWE"))
             * .then(() => console.log('Entry deleted.'))
             * .catch(console.error)
             * ```
             */
            deleteEntry(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'delete',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        entryId: id,
                    },
                }).then(() => {
                    // noop
                });
            },
            /**
             * Gets a collection of Entries
             * Warning: if you are using the select operator, when saving, any field that was not selected will be removed
             * from your entry in the backend
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of Entries
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntries({'content_type': 'foo'})) // you can add more queries as 'key': 'value'
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEntries(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapEntryCollection(makeRequest, data));
            },
            /**
             * Gets a collection of Entries with cursor based pagination
             * Warning: if you are using the select operator, when saving, any field that was not selected will be removed
             * from your entry in the backend
             * @param query - Object with cursor pagination parameters. Check the <a href="https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/cursor-pagination">REST API reference</a> for more details.
             * @returns Promise for a collection of Entries
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntriesWithCursor({'content_type': 'foo'})) // you can add more queries as 'key': 'value'
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEntriesWithCursor(query = {}) {
                const raw = this.toPlainObject();
                const normalizedQueryParams = normalizeCursorPaginationParameters(query);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: normalizedQueryParams }).params,
                    },
                }).then((data) => wrapEntryTypeCursorPaginatedCollection(makeRequest, normalizeCursorPaginationResponse(data)));
            },
            /**
             * Gets a collection of published Entries
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of published Entries
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getPublishedEntries({'content_type': 'foo'})) // you can add more queries as 'key': 'value'
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getPublishedEntries(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'getPublished',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapEntryCollection(makeRequest, data));
            },
            /**
             * Gets a collection of published Entries with cursor based pagination
             * @param query - Object with cursor pagination parameters. Check the <a href="https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/cursor-pagination">REST API reference</a> for more details.
             * @returns Promise for a collection of published Entries
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getPublishedEntriesWithCursor())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getPublishedEntriesWithCursor(query = {}) {
                const raw = this.toPlainObject();
                const normalizedQueryParams = normalizeCursorPaginationParameters(query);
                return makeRequest({
                    entityType: 'Entry',
                    action: 'getPublished',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: normalizedQueryParams }).params,
                    },
                }).then((data) => wrapEntryTypeCursorPaginatedCollection(makeRequest, normalizeCursorPaginationResponse(data)));
            },
            /**
             * Creates a Entry
             * @param contentTypeId - The Content Type ID of the newly created Entry
             * @param data - Object representation of the Entry to be created
             * @returns Promise for the newly created Entry
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createEntry('<content_type_id>', {
             *   fields: {
             *     title: {
             *       'en-US': 'Entry title'
             *     }
             *   }
             * }))
             * .then((entry) => console.log(entry))
             * .catch(console.error)
             * ```
             */
            createEntry(contentTypeId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        contentTypeId: contentTypeId,
                    },
                    payload: data,
                }).then((response) => wrapEntry(makeRequest, response));
            },
            /**
             * Creates a Entry with a custom ID
             * @param contentTypeId - The Content Type of the newly created Entry
             * @param id - Entry ID
             * @param data - Object representation of the Entry to be created
             * @returns Promise for the newly created Entry
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // Create entry
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createEntryWithId('<content_type_id>', '<entry_id>', {
             *   fields: {
             *     title: {
             *       'en-US': 'Entry title'
             *     }
             *   }
             * }))
             * .then((entry) => console.log(entry))
             * .catch(console.error)
             * ```
             */
            createEntryWithId(contentTypeId, id, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        entryId: id,
                        contentTypeId: contentTypeId,
                    },
                    payload: data,
                }).then((response) => wrapEntry(makeRequest, response));
            },
            /**
             * Get entry references
             * @param entryId - Entry ID
             * @param {Object} options.include - Level of the entry descendants from 1 up to 10 maximum
             * @returns Promise of Entry references
             * @example ```javascript
             * const contentful = require('contentful-management');
             *
             * const client = contentful.createClient({
             *  accessToken: '<contentful_management_api_key>
             * })
             *
             * // Get entry references
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEntryReferences('<entry_id>', {include: number}))
             * .then((entry) => console.log(entry.includes))
             * // or
             * .then((environment) => environment.getEntry('<entry_id>')).then((entry) => entry.references({include: number}))
             * .catch(console.error)
             * ```
             */
            getEntryReferences(entryId, options) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Entry',
                    action: 'references',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        entryId: entryId,
                        include: options?.include,
                    },
                }).then((response) => wrapEntryCollection(makeRequest, response));
            },
            /**
             * Gets an Asset
             * Warning: if you are using the select operator, when saving, any field that was not selected will be removed
             * from your entry in the backend
             * @param id - Asset ID
             * @param query - Object with search parameters. In this method it's only useful for `locale`.
             * @returns Promise for an Asset
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getAsset('<asset_id>'))
             * .then((asset) => console.log(asset))
             * .catch(console.error)
             * ```
             */
            getAsset(id, query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        assetId: id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapAsset(makeRequest, data));
            },
            /**
             * Gets a collection of Assets
             * Warning: if you are using the select operator, when saving, any field that was not selected will be removed
             * from your entry in the backend
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of Assets
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getAssets())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getAssets(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapAssetCollection(makeRequest, data));
            },
            /**
             * Gets a collection of Assets with cursor based pagination
             * Warning: if you are using the select operator, when saving, any field that was not selected will be removed
             * from your entry in the backend
             * @param query - Object with cursor pagination parameters. Check the <a href="https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/cursor-pagination">REST API reference</a> for more details.
             * @returns Promise for a collection of Assets
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getAssetsWithCursor())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getAssetsWithCursor(query = {}) {
                const raw = this.toPlainObject();
                const normalizedQueryParams = normalizeCursorPaginationParameters(query);
                return makeRequest({
                    entityType: 'Asset',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: normalizedQueryParams }).params,
                    },
                }).then((data) => wrapAssetTypeCursorPaginatedCollection(makeRequest, normalizeCursorPaginationResponse(data)));
            },
            /**
             * Gets a collection of published Assets
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of published Assets
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getPublishedAssets())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getPublishedAssets(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'getPublished',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapAssetCollection(makeRequest, data));
            },
            /**
             * Gets a collection of published Assets with cursor based pagination
             * @param query - Object with cursor pagination parameters. Check the <a href="https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/cursor-pagination">REST API reference</a> for more details.
             * @returns Promise for a collection of published Assets
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getPublishedAssetsWithCursor())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getPublishedAssetsWithCursor(query = {}) {
                const raw = this.toPlainObject();
                const normalizedQueryParams = normalizeCursorPaginationParameters(query);
                return makeRequest({
                    entityType: 'Asset',
                    action: 'getPublished',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query: normalizedQueryParams }).params,
                    },
                }).then((data) => wrapAssetTypeCursorPaginatedCollection(makeRequest, normalizeCursorPaginationResponse(data)));
            },
            /**
             * Creates a Asset. After creation, call asset.processForLocale or asset.processForAllLocales to start asset processing.
             * @param data - Object representation of the Asset to be created. Note that the field object should have an upload property on asset creation, which will be removed and replaced with an url property when processing is finished.
             * @returns Promise for the newly created Asset
             * @example ```javascript
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // Create asset
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createAsset({
             *   fields: {
             *     title: {
             *       'en-US': 'Playsam Streamliner'
             *    },
             *    file: {
             *       'en-US': {
             *         contentType: 'image/jpeg',
             *        fileName: 'example.jpeg',
             *        upload: 'https://example.com/example.jpg'
             *      }
             *    }
             *   }
             * }))
             * .then((asset) => asset.processForLocale("en-US")) // OR asset.processForAllLocales()
             * .then((asset) => console.log(asset))
             * .catch(console.error)
             * ```
             */
            createAsset(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload: data,
                }).then((response) => wrapAsset(makeRequest, response));
            },
            /**
             * Creates a Asset with a custom ID. After creation, call asset.processForLocale or asset.processForAllLocales to start asset processing.
             * @param id - Asset ID
             * @param data - Object representation of the Asset to be created. Note that the field object should have an upload property on asset creation, which will be removed and replaced with an url property when processing is finished.
             * @returns Promise for the newly created Asset
             * @example ```javascript
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // Create asset
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createAssetWithId('<asset_id>', {
             *   title: {
             *     'en-US': 'Playsam Streamliner'
             *   },
             *   file: {
             *     'en-US': {
             *       contentType: 'image/jpeg',
             *       fileName: 'example.jpeg',
             *       upload: 'https://example.com/example.jpg'
             *     }
             *   }
             * }))
             * .then((asset) => asset.process())
             * .then((asset) => console.log(asset))
             * .catch(console.error)
             * ```
             */
            createAssetWithId(id, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        assetId: id,
                    },
                    payload: data,
                }).then((response) => wrapAsset(makeRequest, response));
            },
            /**
             * Creates a Asset based on files. After creation, call asset.processForLocale or asset.processForAllLocales to start asset processing.
             * @param data - Object representation of the Asset to be created. Note that the field object should have an uploadFrom property on asset creation, which will be removed and replaced with an url property when processing is finished.
             * @param data.fields.file.[LOCALE].file - Can be a string, an ArrayBuffer or a Stream.
             * @returns Promise for the newly created Asset
             * @example ```javascript
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createAssetFromFiles({
             *   fields: {
             *     file: {
             *       'en-US': {
             *          contentType: 'image/jpeg',
             *          fileName: 'filename_english.jpg',
             *          file: createReadStream('path/to/filename_english.jpg')
             *       },
             *       'de-DE': {
             *          contentType: 'image/svg+xml',
             *          fileName: 'filename_german.svg',
             *          file: '<svg><path fill="red" d="M50 50h150v50H50z"/></svg>'
             *       }
             *     }
             *   }
             * }))
             * .then((asset) => console.log(asset))
             * .catch(console.error)
             * ```
             */
            createAssetFromFiles(data, options) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Asset',
                    action: 'createFromFiles',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        uploadTimeout: options?.uploadTimeout,
                    },
                    payload: data,
                }).then((response) => wrapAsset(makeRequest, response));
            },
            /**
             * Creates an asset key for signing asset URLs (Embargoed Assets)
             * @param data Object with request payload
             * @param data.expiresAt number a UNIX timestamp in the future (but not more than 48 hours from time of calling)
             * @returns Promise for the newly created AssetKey
             * @example ```javascript
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // Create assetKey
             * now = () => Math.floor(Date.now() / 1000)
             * const withExpiryIn1Hour = () => now() + 1 * 60 * 60
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createAssetKey({ expiresAt: withExpiryIn1Hour() }))
             * .then((policy, secret) => console.log({ policy, secret }))
             * .catch(console.error)
             * ```
             */
            createAssetKey(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AssetKey',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapAssetKey(makeRequest, data));
            },
            /**
             * Gets an Upload
             * @param id - Upload ID
             * @returns Promise for an Upload
             * @example ```javascript
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const uploadStream = createReadStream('path/to/filename_english.jpg')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getUpload('<upload-id>')
             * .then((upload) => console.log(upload))
             * .catch(console.error)
             */
            getUpload(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Upload',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        uploadId: id,
                    },
                }).then((data) => wrapUpload(makeRequest, data));
            },
            /**
             * Creates a Upload.
             * @param data - Object with file information.
             * @param data.file - Actual file content. Can be a string, an ArrayBuffer or a Stream.
             * @returns Upload object containing information about the uploaded file.
             * @example ```javascript
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const uploadStream = createReadStream('path/to/filename_english.jpg')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createUpload({file: uploadStream})
             * .then((upload) => console.log(upload))
             * .catch(console.error)
             * ```
             */
            createUpload: function createUpload(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Upload',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload: data,
                }).then((data) => wrapUpload(makeRequest, data));
            },
            /**
             * Gets a Locale
             * @param localeId - Locale ID
             * @returns Promise for an Locale
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getLocale('<locale_id>'))
             * .then((locale) => console.log(locale))
             * .catch(console.error)
             * ```
             */
            getLocale(localeId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Locale',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        localeId,
                    },
                }).then((data) => wrapLocale(makeRequest, data));
            },
            /**
             * Gets a collection of Locales
             * @returns Promise for a collection of Locales
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getLocales())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getLocales(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Locale',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapLocaleCollection(makeRequest, data));
            },
            /**
             * Creates a Locale
             * @param data - Object representation of the Locale to be created
             * @returns Promise for the newly created Locale
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // Create locale
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createLocale({
             *   name: 'German (Austria)',
             *   code: 'de-AT',
             *   fallbackCode: 'de-DE',
             *   optional: true
             * }))
             * .then((locale) => console.log(locale))
             * .catch(console.error)
             * ```
             */
            createLocale(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Locale',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload: data,
                }).then((response) => wrapLocale(makeRequest, response));
            },
            /**
             * Gets an UI Extension
             * @param id - Extension ID
             * @returns Promise for an UI Extension
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getUiExtension('<extension-id>'))
             * .then((extension) => console.log(extension))
             * .catch(console.error)
             * ```
             */
            getUiExtension(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Extension',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        extensionId: id,
                    },
                }).then((data) => wrapExtension(makeRequest, data));
            },
            /**
             * Gets a collection of UI Extension
             * @returns Promise for a collection of UI Extensions
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getUiExtensions()
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getUiExtensions() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Extension',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((response) => wrapExtensionCollection(makeRequest, response));
            },
            /**
             * Creates a UI Extension
             * @param data - Object representation of the UI Extension to be created
             * @returns Promise for the newly created UI Extension
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createUiExtension({
             *   extension: {
             *     name: 'My awesome extension',
             *     src: 'https://example.com/my',
             *     fieldTypes: [
             *       {
             *         type: 'Symbol'
             *       },
             *       {
             *         type: 'Text'
             *       }
             *     ],
             *     sidebar: false
             *   }
             * }))
             * .then((extension) => console.log(extension))
             * .catch(console.error)
             * ```
             */
            createUiExtension(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Extension',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload: data,
                }).then((response) => wrapExtension(makeRequest, response));
            },
            /**
             * Creates a UI Extension with a custom ID
             * @param id - Extension ID
             * @param data - Object representation of the UI Extension to be created
             * @returns Promise for the newly created UI Extension
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createUiExtensionWithId('<extension_id>', {
             *   extension: {
             *     name: 'My awesome extension',
             *     src: 'https://example.com/my',
             *     fieldTypes: [
             *       {
             *         type: 'Symbol'
             *       },
             *       {
             *         type: 'Text'
             *       }
             *     ],
             *     sidebar: false
             *   }
             * }))
             * .then((extension) => console.log(extension))
             * .catch(console.error)
             * ```
             */
            createUiExtensionWithId(id, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Extension',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        extensionId: id,
                    },
                    payload: data,
                }).then((response) => wrapExtension(makeRequest, response));
            },
            /**
             * Creates an App Installation
             * @param appDefinitionId - AppDefinition ID
             * @param data - AppInstallation data
             * @param options.acceptAllTerms - Flag for accepting Apps' Marketplace EULA, Terms, and Privacy policy (need to pass `{acceptAllTerms: true}` to install a marketplace app)
             * @returns Promise for an App Installation
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *  .then((space) => space.getEnvironment('<environment-id>'))
             *  .then((environment) => environment.createAppInstallation('<app_definition_id>', {
             *    parameters: {
             *      someParameter: someValue
             *    }
             *   })
             *  .then((appInstallation) => console.log(appInstallation))
             *  .catch(console.error)
             *  ```
             */
            createAppInstallation(appDefinitionId, data, { acceptAllTerms } = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppInstallation',
                    action: 'upsert',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appDefinitionId,
                        acceptAllTerms,
                    },
                    payload: data,
                }).then((payload) => wrapAppInstallation(makeRequest, payload));
            },
            /**
             * Gets an App Installation
             * @param id - AppDefinition ID
             * @returns Promise for an App Installation
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *  .then((space) => space.getEnvironment('<environment-id>'))
             *  .then((environment) => environment.getAppInstallation('<app-definition-id>'))
             *  .then((appInstallation) => console.log(appInstallation))
             *  .catch(console.error)
             *  ```
             */
            getAppInstallation(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppInstallation',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appDefinitionId: id,
                    },
                }).then((data) => wrapAppInstallation(makeRequest, data));
            },
            /**
             * Gets a collection of App Installation
             * @returns Promise for a collection of App Installations
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *  .then((space) => space.getEnvironment('<environment-id>'))
             *  .then((environment) => environment.getAppInstallations()
             *  .then((response) => console.log(response.items))
             *  .catch(console.error)
             *  ```
             */
            getAppInstallations() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppInstallation',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((data) => wrapAppInstallationCollection(makeRequest, data));
            },
            /**
             * Creates an app action call
             * @param appDefinitionId - AppDefinition ID
             * @param appActionId - action ID
             * @param data - App Action Call data
             * @returns Promise for an App Action Call
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const data = {
             *   headers: {
             *     'x-my-header': 'some-value'
             *   },
             *   body: {
             *     'some-body-value': true
             *   }
             * }
             *
             * client.getSpace('<space_id>')
             *  .then((space) => space.getEnvironment('<environment-id>'))
             *  .then((environment) => environment.createAppActionCall('<app_definition_id>', '<action_id>', data)
             *  .then((appActionCall) => console.log(appActionCall))
             *  .catch(console.error)
             *  ```
             */
            createAppActionCall(appDefinitionId, appActionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppActionCall',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appDefinitionId,
                        appActionId,
                    },
                    payload: data,
                }).then((payload) => wrapAppActionCall(makeRequest, payload));
            },
            /**
             * Gets the raw response (headers/body) for a completed App Action Call
             * @param appDefinitionId - AppDefinition ID
             * @param appActionId - App Action ID
             * @param callId - App Action Call ID
             * @returns Promise for the raw response object including `response.body` and optional `response.headers`
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client
             *   .getSpace('<space_id>')
             *   .then((space) => space.getEnvironment('<environment_id>'))
             *   .then((environment) => environment.getAppActionCallResponse('<app_definition_id>', '<app_action_id>', '<call_id>'))
             *   .then((raw) => console.log(raw.response.body))
             *   .catch(console.error)
             * ```
             */
            getAppActionCallResponse(appDefinitionId, appActionId, callId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppActionCall',
                    action: 'getResponse',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appDefinitionId,
                        appActionId,
                        callId,
                    },
                });
            },
            /**
             * Creates an app signed request
             * @param appDefinitionId - AppDefinition ID
             * @param data - SignedRequest data
             * @returns Promise for a Signed Request
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const data = {
             *   method: 'POST',
             *   path: '/request_path',
             *   body: '{ "key": "data" }',
             *   headers: {
             *     'x-my-header': 'some-value'
             *   },
             * }
             *
             * client.getSpace('<space_id>')
             *  .then((space) => space.getEnvironment('<environment-id>'))
             *  .then((environment) => environment.createAppSignedRequest('<app_definition_id>', data)
             *  .then((signedRequest) => console.log(signedRequest))
             *  .catch(console.error)
             *  ```
             */
            createAppSignedRequest(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppSignedRequest',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appDefinitionId,
                    },
                    payload: data,
                }).then((payload) => wrapAppSignedRequest(makeRequest, payload));
            },
            /**
             * Creates an app access token
             * @param appDefinitionId - AppDefinition ID
             * @param data - Json Web Token
             * @returns Promise for an app access token
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const { sign } = require('jsonwebtoken')
             *
             * const signOptions = { algorithm: 'RS256', issuer: '<app_definition_id>', expiresIn: '10m' }
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const data = {
             *   jwt: sign({}, '<private_key>', signOptions)
             * }
             *
             * client.getSpace('<space_id>')
             *  .then((space) => space.getEnvironment('<environment-id>'))
             *  .then((environment) => environment.createAppAccessToken('<app_definition_id>', data)
             *  .then((appAccessToken) => console.log(appAccessToken))
             *  .catch(console.error)
             *  ```
             */
            createAppAccessToken(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAccessToken',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appDefinitionId,
                    },
                    payload: data,
                }).then((payload) => wrapAppAccessToken(makeRequest, payload));
            },
            /**
             * Gets a collection of Functions for a given environment
             * @param appInstallationId
             * @param {import('../common-types').AcceptsQueryOptions} query  - optional query parameter for filtering functions by action
             * @returns Promise containing wrapped collection of Functions in an environment
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client
             *    .getSpace('<space-id>')
             *    .then((space) => space.getEnvironment('<environment-id>'))
             *    .then((environment) => environment.getFunctionsForEnvironment('<app-installation-id>',  { 'accepts[all]': '<action>' }))
             *    .then((functions) => console.log(functions.items))
             *    .catch(console.error)
             * ```
             */
            getFunctionsForEnvironment(appInstallationId, query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Function',
                    action: 'getManyForEnvironment',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appInstallationId,
                        query,
                    },
                }).then((data) => wrapFunctionCollection(makeRequest, data));
            },
            /**
             * Gets a collection of FunctionLogs for a given app installation id and FunctionId
             * @param appInstallationId
             * @param functionId
             * @param {import('../common-types').CursorBasedParams} query  - optional query parameter for pagination (limit, nextPage, prevPage)
             * @returns Promise containing wrapped collection of FunctionLogs
             * * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client
             *    .getSpace('<space-id>')
             *    .then((space) => space.getEnvironment('<environment-id>'))
             *    .then((environment) =>
             *       environment.getFunctionLogs(
             *          '<app-installation-id>',
             *          '<function-id>',
             *          {
             *            query: {
             *              // optional limit
             *              limit: 10,
             *              // optional interval query
             *              'sys.createdAt[gte]': start,
             *              'sys.createdAt[lt]': end,
             *              // optional cursor based pagination parameters
             *              pagePrev: '<page_prev>',
             *            },
             *          },
             *       )
             *     )
             *     .then((functionLogs) => console.log(functionLog.items))
             *     .catch(console.error)
             * ```
             */
            getFunctionLogs(appInstallationId, functionId, query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'FunctionLog',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appInstallationId,
                        functionId,
                        query: query ? createRequestConfig({ query }).params : undefined,
                    },
                }).then((data) => wrapFunctionLogCollection(makeRequest, data));
            },
            /**
             * Gets a FunctionLog by appInstallationId, functionId and logId
             * @param appInstallationId
             * @param functionId
             * @param logId
             * @returns Promise containing a wrapped FunctionLog
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client
             *    .getSpace(<space-id>)
             *    .then((space) => space.getEnvironment('<environment-id>'))
             *    .then((environment) =>
             *       environment.getFunctionLog(
             *          '<app-installation-id>',
             *          '<function-id>',
             *          '<log-id>'
             *       )
             *     )
             *     .then((functionLog) => console.log(functionLog))
             *     .catch(console.error)
             * ```
             */
            getFunctionLog(appInstallationId, functionId, logId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'FunctionLog',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        appInstallationId,
                        functionId,
                        logId,
                    },
                }).then((data) => wrapFunctionLog(makeRequest, data));
            },
            /**
             * Gets all snapshots of an entry
             * @func getEntrySnapshots
             * @param entryId - Entry ID
             * @param query - query additional query paramaters
             * @returns Promise for a collection of Entry Snapshots
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getEntrySnapshots('<entry_id>'))
             * .then((snapshots) => console.log(snapshots.items))
             * .catch(console.error)
             * ```
             */
            getEntrySnapshots(entryId, query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Snapshot',
                    action: 'getManyForEntry',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        entryId,
                        query,
                    },
                }).then((data) => wrapSnapshotCollection(makeRequest, data));
            },
            /**
             * Gets all snapshots of a contentType
             * @func getContentTypeSnapshots
             * @param contentTypeId - Content Type ID
             * @param query - query additional query paramaters
             * @returns Promise for a collection of Content Type Snapshots
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getContentTypeSnapshots('<contentTypeId>'))
             * .then((snapshots) => console.log(snapshots.items))
             * .catch(console.error)
             * ```
             */
            getContentTypeSnapshots(contentTypeId, query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Snapshot',
                    action: 'getManyForContentType',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        contentTypeId,
                        query,
                    },
                }).then((data) => wrapSnapshotCollection(makeRequest, data));
            },
            createTag(id, name, visibility) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Tag',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        tagId: id,
                    },
                    payload: {
                        name,
                        sys: { visibility: visibility ?? 'private' },
                    },
                }).then((data) => wrapTag(makeRequest, data));
            },
            getTags(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Tag',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapTagCollection(makeRequest, data));
            },
            getTag(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Tag',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        tagId: id,
                    },
                }).then((data) => wrapTag(makeRequest, data));
            },
            /**
             * Retrieves a Release by ID
             * @param releaseId
             * @returns Promise containing a wrapped Release
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getRelease('<release_id>'))
             * .then((release) => console.log(release))
             * .catch(console.error)
             * ```
             */
            getRelease(releaseId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                    },
                }).then((data) => wrapRelease(makeRequest, data));
            },
            /**
             * Gets a Collection of Releases,
             * @param {ReleaseQueryOptions} query filtering options for the collection result
             * @returns Promise containing a wrapped Release Collection
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getReleases({ 'entities.sys.id[in]': '<asset_id>,<entry_id>' }))
             * .then((releases) => console.log(releases))
             * .catch(console.error)
             * ```
             */
            getReleases(query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'query',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query,
                    },
                }).then((data) => wrapReleaseCollection(makeRequest, data));
            },
            /**
             * Creates a new Release with the entities and title in the payload
             * @param payload Object containing the payload in order to create a Release
             * @returns Promise containing a wrapped Release, that has other helper methods within.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const payload = {
             *   title: 'My Release',
             *   entities: {
             *     sys: { type: 'Array' },
             *     items: [
             *      { sys: { linkType: 'Entry', type: 'Link', id: '<entry_id>' } }
             *     ]
             *   }
             * }
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.createRelease(payload))
             * .then((release) => console.log(release))
             * .catch(console.error)
             * ```
             */
            createRelease(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapRelease(makeRequest, data));
            },
            /**
             * Updates a Release and replaces all the properties.
             * @param {object} options,
             * @param options.releaseId the ID of the release
             * @param options.payload the payload to be updated in the Release
             * @param options.version Release sys.version that to be updated
             * @returns Promise containing a wrapped Release, that has helper methods within.
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             *
             * const payload = {
             *   title: "Updated Release title",
             *   entities: {
             *     sys: { type: 'Array' },
             *     items: [
             *        { sys: { linkType: 'Entry', type: 'Link', id: '<entry_id>' } }
             *     ]
             *   }
             * }
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.updateRelease({ releaseId: '<release_id>', version: 1, payload } ))
             * .then((release) => console.log(release))
             * .catch(console.error)
             * ```
             */
            updateRelease({ releaseId, payload, version, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'update',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                        version,
                    },
                    payload,
                }).then((data) => wrapRelease(makeRequest, data));
            },
            /**
             * Deletes a Release by ID - does not delete any entities.
             * @param releaseId the ID of the release
             *
             * @returns Promise containing a wrapped Release, that has helper methods within.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.deleteRelease('<release_id>')
             * .catch(console.error)
             * ```
             */
            deleteRelease(releaseId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'delete',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                    },
                });
            },
            /**
             * Publishes all Entities contained in a Release.
             * @param options.releaseId the ID of the release
             * @param options.version the version of the release that is to be published
             * @returns Promise containing a wrapped Release, that has helper methods within.
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.publishRelease({ releaseId: '<release_id>', version: 1 }))
             * .catch(console.error)
             * ```
             */
            publishRelease({ releaseId, version }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'publish',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                        version,
                    },
                }).then((data) => wrapReleaseAction(makeRequest, data));
            },
            /**
             * Unpublishes all Entities contained in a Release.
             * @param options.releaseId the ID of the release
             * @param options.version the version of the release that is to be published
             * @returns Promise containing a wrapped Release, that has helper methods within.
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.unpublishRelease({ releaseId: '<release_id>', version: 1 }))
             * .catch(console.error)
             * ```
             */
            unpublishRelease({ releaseId, version }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'unpublish',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                        version,
                    },
                }).then((data) => wrapReleaseAction(makeRequest, data));
            },
            /**
             * Validates all Entities contained in a Release against an action (publish or unpublish)
             * @param options.releaseId the ID of the release
             * @param options.payload (optional) the type of action to be validated against
             *
             * @returns Promise containing a wrapped Release, that has helper methods within.
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.validateRelease({ releaseId: '<release_id>', payload: { action: 'unpublish' } }))
             * .catch(console.error)
             * ```
             */
            validateRelease({ releaseId, payload, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'validate',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                    },
                    payload,
                }).then((data) => wrapReleaseAction(makeRequest, data));
            },
            /**
             * Archives a Release and prevents new operations (publishing, unpublishing adding new entities etc).
             * @param options.releaseId the ID of the release
             * @param options.version the version of the release that is to be archived
             * @returns Promise containing a wrapped Release, that has helper methods within.
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.archiveRelease({ releaseId: '<release_id>', version: 1 }))
             * .catch(console.error)
             * ```
             */
            archiveRelease({ releaseId, version }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'archive',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                        version,
                    },
                }).then((data) => wrapRelease(makeRequest, data));
            },
            /**
             * Unarchives a previously archived Release - this enables the release to be published, unpublished etc.
             * @param options.releaseId the ID of the release
             * @param options.version the version of the release that is to be unarchived
             * @returns Promise containing a wrapped Release, that has helper methods within.
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.unarchiveRelease({ releaseId: '<release_id>', version: 1 }))
             * .catch(console.error)
             * ```
             */
            unarchiveRelease({ releaseId, version }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Release',
                    action: 'unarchive',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                        version,
                    },
                }).then((data) => wrapRelease(makeRequest, data));
            },
            /**
             * Retrieves a ReleaseAction by ID
             * @param params.releaseId The ID of a Release
             * @param params.actionId The ID of a Release Action
             * @returns Promise containing a wrapped ReleaseAction
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getReleaseAction({ releaseId: '<release_id>', actionId: '<action_id>' }))
             * .then((releaseAction) => console.log(releaseAction))
             * .catch(console.error)
             * ```
             */
            getReleaseAction({ actionId, releaseId }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ReleaseAction',
                    action: 'get',
                    params: {
                        actionId,
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        releaseId,
                    },
                }).then((data) => wrapReleaseAction(makeRequest, data));
            },
            /**
             * Gets a Collection of ReleaseActions
             * @param {string} params.releaseId ID of the Release to fetch the actions from
             * @param {ReleaseQueryOptions} params.query filtering options for the collection result
             * @returns Promise containing a wrapped ReleaseAction Collection
             *
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment-id>'))
             * .then((environment) => environment.getReleaseActions({ query: { 'sys.id[in]': '<id_1>,<id_2>', 'sys.release.sys.id[in]': '<id1>,<id2>' } }))
             * .then((releaseActions) => console.log(releaseActions))
             * .catch(console.error)
             * ```
             */
            getReleaseActions({ query }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ReleaseAction',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query,
                    },
                }).then((data) => wrapReleaseActionCollection(makeRequest, data));
            },
            async getUIConfig() {
                const raw = this.toPlainObject();
                const data = await makeRequest({
                    entityType: 'UIConfig',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                });
                return wrapUIConfig(makeRequest, data);
            },
            async getUserUIConfig() {
                const raw = this.toPlainObject();
                const data = await makeRequest({
                    entityType: 'UserUIConfig',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                });
                return wrapUserUIConfig(makeRequest, data);
            },
            /**
             * Gets a collection of all environment template installations in the environment for a given template
             * @param environmentTemplateId - Environment template ID to return installations for
             * @param [options.installationId] - Installation ID to filter for a specific installation
             * @returns Promise for a collection of EnvironmentTemplateInstallations
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getEnvironmentTemplateInstallations('<environment_template_id>'))
             * .then((installations) => console.log(installations.items))
             * .catch(console.error)
             * ```
             */
            async getEnvironmentTemplateInstallations(environmentTemplateId, { installationId, ...query } = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplateInstallation',
                    action: 'getForEnvironment',
                    params: {
                        environmentTemplateId,
                        ...(installationId && { installationId }),
                        query: { ...createRequestConfig({ query }).params },
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((data) => wrapEnvironmentTemplateInstallationCollection(makeRequest, data));
            },
            /**
             * Gets a collection of all resource types based on native external references app installations in the environment
             * @param query - BasicCursorPaginationOptions
             * @returns Promise for a collection of ResourceTypes
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getResourceTypes({limit: 10}))
             * .then((installations) => console.log(installations.items))
             * .catch(console.error)
             * ```
             */
            async getResourceTypes(query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceType',
                    action: 'getForEnvironment',
                    params: {
                        query,
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((data) => wrapResourceTypesForEnvironmentCollection(makeRequest, data));
            },
            /**
             * Gets a collection of all resources for a given resource type based on native external references app installations in the environment
             * @param resourceTypeId - Id of the resourceType to get its resources
             * @param query - Either LookupQuery options with 'sys.urn[in]' param or a Search query with 'query' param, in both cases you can add pagination options
             * @returns Promise for a collection of Resources for a given resourceTypeId
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // Search Query
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * // <search_query> is a string you want to search for in the external resources
             * .then((environment) => environment.getResourcesForResourceType('<resource_type_id>', {query: '<search_query>', limit: 10}))
             * .then((installations) => console.log(installations.items))
             * .catch(console.error)
             *
             * // Lookup query
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => environment.getResourcesForResourceType('<resource_type_id>', {'sys.urn[in]': '<resource_urn1>,<resource_urn2>', limit: 10}))
             * .then((installations) => console.log(installations.items))
             * .catch(console.error)
             * ```
             */
            async getResourcesForResourceType(resourceTypeId, query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Resource',
                    action: 'getMany',
                    params: {
                        query,
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        resourceTypeId,
                    },
                }).then((data) => wrapResourceCollection(makeRequest, data));
            },
            /**
             * Invokes an AI Action.
             * @param aiActionId - The ID of the AI Action to invoke.
             * @param payload - The invocation payload.
             * @returns Promise for an AI Action Invocation.
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.invokeAiAction('<ai_action_id>', {
             *     variables: [  ...  ],
             *     outputFormat: 'RichText'
             *   }))
             *   .then(invocation => console.log(invocation))
             *   .catch(console.error)
             * ```
             */
            invokeAiAction(aiActionId, payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'invoke',
                    params: { spaceId: raw.sys.space.sys.id, environmentId: raw.sys.id, aiActionId },
                    payload,
                }).then((data) => wrapAiActionInvocation(makeRequest, data));
            },
            /**
             * Retrieves an AI Action Invocation.
             * @param params - Object containing the AI Action ID and the Invocation ID.
             * @returns Promise for an AI Action Invocation.
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.getAiActionInvocation({
             *      aiActionId: '<ai_action_id>',
             *      invocationId: '<invocation_id>'
             *   }))
             *   .then(invocation => console.log(invocation))
             *   .catch(console.error)
             * ```
             */
            getAiActionInvocation({ aiActionId, invocationId, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiActionInvocation',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        aiActionId,
                        invocationId,
                    },
                }).then((data) => wrapAiActionInvocation(makeRequest, data));
            },
            /**
             * Retrieves Semantic Duplicates for the given entity ID
             * @param payload - Object containing the entityId and optional filters
             * @returns Promise for Semantic Duplicates
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.getSemanticDuplicates({
             *      entityId: '<entity_id>',
             *      filters: {
             *        contentTypeIds: ['<content_type_id1>', '<content_type_id2>'],
             *      }
             *    })
             */
            getSemanticDuplicates(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SemanticDuplicates',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapSemanticDuplicates(makeRequest, data));
            },
            /**
             * Retrieves Semantic Recommendations for the given entity IDs
             * @param payload - Object containing the entityIds and optional filters
             * @returns Promise for Semantic Recommendations
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.getSemanticRecommendations({
             *      entityIds: ['<entity_id>'],
             *      filters: {
             *        contentTypeIds: ['<content_type_id1>', '<content_type_id2>'],
             *      }
             *    })
             */
            getSemanticRecommendations(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SemanticRecommendations',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapSemanticRecommendations(makeRequest, data));
            },
            /**
             * Retrieves Semantic Reference Suggestions for the given entity ID and its reference field ID
             * @param payload - Object containing the entityId and referenceFieldId
             * @returns Promise for Semantic Reference Suggestions
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.getSemanticReferenceSuggestions({
             *      entityId: '<entity_id>',
             *      referenceFieldId: '<reference_field_id>',
             *    })
             */
            getSemanticReferenceSuggestions(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SemanticReferenceSuggestions',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapSemanticReferenceSuggestions(makeRequest, data));
            },
            /**
             * Retrieves Semantic Search results for the given query
             * @param payload - Object containing the search query and optional filters
             * @returns Promise for Semantic Search results
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.getSemanticSearch({
             *      query: '<search_query>',
             *      filters: {
             *        contentTypeIds: ['<content_type_id1>', '<content_type_id2>'],
             *      }
             *    })
             */
            getSemanticSearch(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SemanticSearch',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                    payload,
                }).then((data) => wrapSemanticSearch(makeRequest, data));
            },
            /**
             * Gets all content semantics indexes for the environment
             * @return Promise for a collection of ContentSemanticsIndex
             * @example ```javascript
             * client.getSpace('<space_id>')
             *   .then(space => space.getEnvironment('<environment_id>'))
             *   .then(environment => environment.getContentSemanticsIndexes())
             */
            getContentSemanticsIndexes() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentSemanticsIndex',
                    action: 'getManyForEnvironment',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((data) => wrapContentSemanticsIndexCollection(makeRequest, data));
            },
            /**
             * Gets an AI Agent
             * @param agentId - AI Agent ID
             * @returns Promise for an AI Agent
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.getEnvironment('<environment_id>'))
             *   .then((environment) => environment.getAgent('<agent_id>'))
             *   .then((agent) => console.log(agent))
             *   .catch(console.error)
             * ```
             */
            getAgent(agentId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Agent',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        agentId,
                    },
                }).then((data) => wrapAgent(makeRequest, data));
            },
            /**
             * Gets a collection of AI Agents
             * @returns Promise for a collection of AI Agents
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.getEnvironment('<environment_id>'))
             *   .then((environment) => environment.getAgents())
             *   .then((response) => console.log(response.items))
             *   .catch(console.error)
             * ```
             */
            getAgents() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Agent',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                    },
                }).then((data) => wrapAgentCollection(makeRequest, data));
            },
            /**
             * Generates content using an AI Agent
             * @param agentId - AI Agent ID
             * @param payload - Generation payload
             * @returns Promise for a simplified response containing `sys.id`, `sys.type`, and `sys.status`.
             *         Use `getAgentRun()` with the returned `sys.id` to poll for full results.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * async function generateContent() {
             *   const client = contentful.createClient({
             *     accessToken: '<content_management_api_key>'
             *   })
             *
             *   const space = await client.getSpace('<space_id>')
             *   const environment = await space.getEnvironment('<environment_id>')
             *
             *   // Start generation (returns 202 Accepted)
             *   const response = await environment.generateWithAgent('<agent_id>', {
             *     messages: [
             *       {
             *         parts: [{ type: 'text', text: 'Write a short poem about Contentful' }],
             *         role: 'user'
             *       }
             *     ]
             *   })
             *
             *   // Poll for full results
             *   let run = await environment.getAgentRun(response.sys.id)
             *   while (run.sys.status === 'IN_PROGRESS') {
             *     await new Promise((resolve) => setTimeout(resolve, 1000))
             *     run = await environment.getAgentRun(response.sys.id)
             *   }
             *
             *   console.log(run)
             * }
             * ```
             */
            generateWithAgent(agentId, payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Agent',
                    action: 'generate',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        agentId,
                    },
                    payload,
                }).then((data) => wrapAgentGenerateResponse(makeRequest, data));
            },
            /**
             * Gets an AI Agent Run
             * @param runId - AI Agent Run ID
             * @returns Promise for an AI Agent Run
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.getEnvironment('<environment_id>'))
             *   .then((environment) => environment.getAgentRun('<run_id>'))
             *   .then((run) => console.log(run))
             *   .catch(console.error)
             * ```
             */
            getAgentRun(runId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AgentRun',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        runId,
                    },
                }).then((data) => wrapAgentRun(makeRequest, data));
            },
            /**
             * Gets a collection of AI Agent Runs with optional filtering
             * @param query - Object with search parameters (agentIn, statusIn)
             * @returns Promise for a collection of AI Agent Runs
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.getEnvironment('<environment_id>'))
             *   .then((environment) => environment.getAgentRuns({
             *     agentIn: ['agent1', 'agent2'],
             *     statusIn: ['COMPLETED', 'IN_PROGRESS']
             *   }))
             *   .then((response) => console.log(response.items))
             *   .catch(console.error)
             * ```
             */
            getAgentRuns(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AgentRun',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.space.sys.id,
                        environmentId: raw.sys.id,
                        query,
                    },
                }).then((data) => wrapAgentRunCollection(makeRequest, data));
            },
        };
    }

    /**
     * This method creates the API for the given environment with all the methods for
     * reading and creating other entities. It also passes down a clone of the
     * http client with a environment id, so the base path for requests now has the
     * environment id already set.
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - API response for a Environment
     * @returns
     */
    function wrapEnvironment(makeRequest, data) {
        // do not pollute generated typings
        const environment = toPlainObject(index$2(data));
        const environmentApi = createEnvironmentApi(makeRequest);
        const enhancedEnvironment = enhanceWithMethods(environment, environmentApi);
        return freezeSys(enhancedEnvironment);
    }
    /**
     * This method wraps each environment in a collection with the environment API. See wrapEnvironment
     * above for more details.
     * @internal
     */
    const wrapEnvironmentCollection = wrapCollection(wrapEnvironment);

    /**
     * @internal
     */
    function createWebhookApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            webhookDefinitionId: data.sys.id,
        });
        return {
            update: function update() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'update',
                    params: getParams(data),
                    payload: data,
                }).then((data) => wrapWebhook(makeRequest, data));
            },
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'delete',
                    params: getParams(data),
                });
            },
            getCalls: function getCalls() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'getManyCallDetails',
                    params: getParams(data),
                });
            },
            getCall: function getCall(id) {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'getCallDetails',
                    params: { ...getParams(data), callId: id },
                });
            },
            getHealth: function getHealth() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'getHealthStatus',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw webhook data
     * @returns Wrapped webhook data
     */
    function wrapWebhook(makeRequest, data) {
        const webhook = toPlainObject(index$2(data));
        const webhookWithMethods = enhanceWithMethods(webhook, createWebhookApi(makeRequest));
        return freezeSys(webhookWithMethods);
    }
    /**
     * @internal
     */
    const wrapWebhookCollection = wrapCollection(wrapWebhook);

    /**
     * @internal
     */
    function createRoleApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            roleId: data.sys.id,
        });
        return {
            update: function update() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'update',
                    params: getParams(data),
                    payload: data,
                }).then((data) => wrapRole(makeRequest, data));
            },
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw role data
     * @returns Wrapped role data
     */
    function wrapRole(makeRequest, data) {
        const role = toPlainObject(index$2(data));
        const roleWithMethods = enhanceWithMethods(role, createRoleApi(makeRequest));
        return freezeSys(roleWithMethods);
    }
    /**
     * @internal
     */
    const wrapRoleCollection = wrapCollection(wrapRole);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw data
     * @returns Normalized user
     */
    function wrapUser(_makeRequest, data) {
        const user = toPlainObject(index$2(data));
        const userWithMethods = enhanceWithMethods(user, {});
        return freezeSys(userWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw data collection
     * @returns Normalized user collection
     */
    const wrapUserCollection = wrapCollection(wrapUser);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw space add-on data
     * @returns Wrapped space add-on data
     */
    function wrapSpaceAddOn(makeRequest, data) {
        const spaceAddOn = toPlainObject(index$2(data));
        const spaceAddOnWithMethods = enhanceWithMethods(spaceAddOn, {});
        return freezeSys(spaceAddOnWithMethods);
    }
    /**
     * @internal
     */
    const wrapSpaceAddOnCollection = wrapCollection(wrapSpaceAddOn);
    /**
     * @internal
     */
    function wrapSpaceAddOnOrganization(makeRequest, data) {
        const orgAddOn = toPlainObject(index$2(data));
        const orgAddOnWithMethods = enhanceWithMethods(orgAddOn, {});
        return freezeSys(orgAddOnWithMethods);
    }
    /**
     * @internal
     */
    const wrapSpaceAddOnOrganizationCollection = wrapCollection(wrapSpaceAddOnOrganization);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw space member data
     * @returns Wrapped space member data
     */
    function wrapSpaceMember(_makeRequest, data) {
        const spaceMember = toPlainObject(index$2(data));
        return freezeSys(spaceMember);
    }
    /**
     * @internal
     */
    const wrapSpaceMemberCollection = wrapCollection(wrapSpaceMember);

    /**
     * @internal
     */
    function createSpaceMembershipApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            spaceMembershipId: data.sys.id,
        });
        return {
            update: function update() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'update',
                    params: getParams(data),
                    payload: data,
                }).then((data) => wrapSpaceMembership(makeRequest, data));
            },
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw space membership data
     * @returns Wrapped space membership data
     */
    function wrapSpaceMembership(makeRequest, data) {
        const spaceMembership = toPlainObject(index$2(data));
        const spaceMembershipWithMethods = enhanceWithMethods(spaceMembership, createSpaceMembershipApi(makeRequest));
        return freezeSys(spaceMembershipWithMethods);
    }
    /**
     * @internal
     */
    const wrapSpaceMembershipCollection = wrapCollection(wrapSpaceMembership);

    /**
     * @internal
     */
    function createTeamSpaceMembershipApi(makeRequest) {
        const getParams = (data) => ({
            teamSpaceMembershipId: data.sys.id,
            spaceId: data.sys.space.sys.id,
        });
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapTeamSpaceMembership(makeRequest, data));
            },
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw space membership data
     * @returns Wrapped team space membership data
     */
    function wrapTeamSpaceMembership(makeRequest, data) {
        const teamSpaceMembership = toPlainObject(index$2(data));
        const teamSpaceMembershipWithMethods = enhanceWithMethods(teamSpaceMembership, createTeamSpaceMembershipApi(makeRequest));
        return freezeSys(teamSpaceMembershipWithMethods);
    }
    /**
     * @internal
     */
    const wrapTeamSpaceMembershipCollection = wrapCollection(wrapTeamSpaceMembership);

    /**
     * @internal
     */
    function createTeamApi(makeRequest) {
        const getParams = (data) => ({
            teamId: data.sys.id,
            organizationId: data.sys.organization.sys.id,
        });
        return {
            update: function update() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Team',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapTeam(makeRequest, data));
            },
            delete: function del() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Team',
                    action: 'delete',
                    params: getParams(raw),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw team data
     * @returns Wrapped team data
     */
    function wrapTeam(makeRequest, data) {
        const team = toPlainObject(index$2(data));
        const teamWithMethods = enhanceWithMethods(team, createTeamApi(makeRequest));
        return freezeSys(teamWithMethods);
    }
    /**
     * @internal
     */
    const wrapTeamCollection = wrapCollection(wrapTeam);

    /**
     * @internal
     */
    function createApiKeyApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space?.sys.id ?? '',
            apiKeyId: data.sys.id,
        });
        return {
            update: function update() {
                const self = this;
                return makeRequest({
                    entityType: 'ApiKey',
                    action: 'update',
                    params: getParams(self),
                    payload: self,
                    headers: {},
                }).then((data) => wrapApiKey(makeRequest, data));
            },
            delete: function del() {
                const self = this;
                return makeRequest({
                    entityType: 'ApiKey',
                    action: 'delete',
                    params: getParams(self),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw api key data
     */
    function wrapApiKey(makeRequest, data) {
        const apiKey = toPlainObject(index$2(data));
        const apiKeyWithMethods = enhanceWithMethods(apiKey, createApiKeyApi(makeRequest));
        return freezeSys(apiKeyWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw api key collection data
     * @returns Wrapped api key collection data
     */
    const wrapApiKeyCollection = wrapCollection(wrapApiKey);

    /**
     * @internal
     */
    function createEnvironmentAliasApi(makeRequest) {
        const getParams = (alias) => ({
            spaceId: alias.sys.space.sys.id,
            environmentAliasId: alias.sys.id,
        });
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentAlias',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapEnvironmentAlias(makeRequest, data));
            },
            delete: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentAlias',
                    action: 'delete',
                    params: getParams(raw),
                }).then(() => {
                    // noop
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw environment alias data
     * @returns Wrapped environment alias data
     */
    function wrapEnvironmentAlias(makeRequest, data) {
        const alias = toPlainObject(index$2(data));
        const enhancedAlias = enhanceWithMethods(alias, createEnvironmentAliasApi(makeRequest));
        return freezeSys(enhancedAlias);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw environment alias collection data
     * @returns Wrapped environment alias collection data
     */
    const wrapEnvironmentAliasCollection = wrapCollection(wrapEnvironmentAlias);

    /**
     * @internal
     */
    function createPreviewApiKeyApi() {
        return {};
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw api key data
     * @returns Wrapped preview api key data
     */
    function wrapPreviewApiKey(_makeRequest, data) {
        const previewApiKey = toPlainObject(index$2(data));
        const previewApiKeyWithMethods = enhanceWithMethods(previewApiKey, createPreviewApiKeyApi());
        return freezeSys(previewApiKeyWithMethods);
    }
    /**
     * @internal
     */
    const wrapPreviewApiKeyCollection = wrapCollection(wrapPreviewApiKey);

    /**
     * Represents that state of the scheduled action
     */
    exports.ScheduledActionStatus = void 0;
    (function (ScheduledActionStatus) {
        /** action is pending execution */
        ScheduledActionStatus["scheduled"] = "scheduled";
        /** action has been started and pending completion */
        ScheduledActionStatus["inProgress"] = "inProgress";
        /** action was completed successfully (terminal state) */
        ScheduledActionStatus["succeeded"] = "succeeded";
        /** action failed to complete (terminal state) */
        ScheduledActionStatus["failed"] = "failed";
        /** action was canceled by a user (terminal state) */
        ScheduledActionStatus["canceled"] = "canceled";
    })(exports.ScheduledActionStatus || (exports.ScheduledActionStatus = {}));
    function getInstanceMethods(makeRequest) {
        const getParams = (self) => {
            const scheduledAction = self.toPlainObject();
            return {
                spaceId: scheduledAction.sys.space.sys.id,
                environmentId: scheduledAction.environment?.sys.id,
                scheduledActionId: scheduledAction.sys.id,
                version: scheduledAction.sys.version,
            };
        };
        return {
            /**
             * Cancels the current Scheduled Action schedule.
             *
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  client.getSpace('<space_id>')
             *    .then((space) => {
             *      return space.createScheduledAction({
             *        entity: {
             *          sys: {
             *            type: 'Link',
             *            linkType: 'Entry',
             *            id: '<entry_id>'
             *          }
             *        },
             *        environment: {
             *          sys: {
             *            type: 'Link',
             *            linkType: 'Environment',
             *            id: '<environment_id>'
             *          }
             *        },
             *        action: 'publish',
             *        scheduledFor: {
             *          datetime: <ISO_date_string>,
             *          timezone: 'Europe/Berlin'
             *        }
             *      })
             *    .then((scheduledAction) => scheduledAction.delete())
             *    .then((deletedScheduledAction) => console.log(deletedScheduledAction))
             *    .catch(console.error);
             * ```
             */
            async delete() {
                const params = getParams(this);
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'delete',
                    params,
                }).then((data) => wrapScheduledAction(makeRequest, data));
            },
            /**
             * Update the current scheduled action. Currently, only changes made to the `scheduledFor` property will be saved.
             *
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  client.getSpace('<space_id>')
             *    .then((space) => {
             *      return space.createScheduledAction({
             *        entity: {
             *          sys: {
             *            type: 'Link',
             *            linkType: 'Entry',
             *            id: '<entry_id>'
             *          }
             *        },
             *        environment: {
             *          sys: {
             *            type: 'Link',
             *            linkType: 'Environment',
             *            id: '<environment_id>'
             *          }
             *        },
             *        action: 'publish',
             *        scheduledFor: {
             *          datetime: <ISO_date_string>,
             *          timezone: 'Europe/Berlin'
             *        }
             *      })
             *    .then((scheduledAction) => {
             *      scheduledAction.scheduledFor.timezone = 'Europe/Paris';
             *      return scheduledAction.update();
             *    })
             *    .then((scheduledAction) => console.log(scheduledAction))
             *    .catch(console.error);
             * ```
             */
            async update() {
                const params = getParams(this);
                // eslint-disable-next-line @typescript-eslint/no-unused-vars
                const { sys, ...payload } = this.toPlainObject();
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'update',
                    params,
                    payload,
                }).then((data) => wrapScheduledAction(makeRequest, data));
            },
        };
    }
    /**
     * @internal
     */
    function wrapScheduledAction(makeRequest, data) {
        const scheduledAction = toPlainObject(index$2(data));
        const scheduledActionWithMethods = enhanceWithMethods(scheduledAction, getInstanceMethods(makeRequest));
        return freezeSys(scheduledActionWithMethods);
    }
    /**
     * @internal
     */
    const wrapScheduledActionCollection = wrapCollection(wrapScheduledAction);

    function createAiActionApi(makeRequest) {
        const getParams = (data) => ({
            spaceId: data.sys.space.sys.id,
            aiActionId: data.sys.id,
        });
        return {
            update: function update() {
                const self = this;
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'update',
                    params: getParams(self),
                    payload: self,
                }).then((data) => wrapAiAction(makeRequest, data));
            },
            delete: function del() {
                const self = this;
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'delete',
                    params: getParams(self),
                });
            },
            publish: function publish() {
                const self = this;
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'publish',
                    params: {
                        aiActionId: self.sys.id,
                        spaceId: self.sys.space.sys.id,
                        version: self.sys.version,
                    },
                }).then((data) => wrapAiAction(makeRequest, data));
            },
            unpublish: function unpublish() {
                const self = this;
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'unpublish',
                    params: getParams(self),
                }).then((data) => wrapAiAction(makeRequest, data));
            },
            invoke: function invoke(environmentId, payload) {
                const self = this;
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'invoke',
                    params: {
                        spaceId: self.sys.space.sys.id,
                        environmentId,
                        aiActionId: self.sys.id,
                    },
                    payload,
                }).then((data) => wrapAiActionInvocation(makeRequest, data));
            },
        };
    }
    function wrapAiAction(makeRequest, data) {
        const aiAction = toPlainObject(index$2(data));
        const aiActionWithMethods = enhanceWithMethods(aiAction, createAiActionApi(makeRequest));
        return freezeSys(aiActionWithMethods);
    }
    const wrapAiActionCollection = wrapCollection(wrapAiAction);

    /**
     * Contentful Space API. Contains methods to access any operations at a space
     * level, such as creating and reading entities contained in a space.
     */
    /**
     * Creates API object with methods to access the Space API
     * @param {MakeRequest} makeRequest - function to make requests via an adapter
     * @returns {ContentfulSpaceAPI}
     * @internal
     */
    function createSpaceApi(makeRequest) {
        return {
            /**
             * Deletes the space
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.delete())
             *   .then(() => console.log('Space deleted.'))
             *   .catch(console.error)
             * ```
             */
            delete: function deleteSpace() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Space',
                    action: 'delete',
                    params: { spaceId: raw.sys.id },
                });
            },
            /**
             * Updates the space
             * @returns Promise for the updated space.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => {
             *   space.name = 'New name'
             *   return space.update()
             * })
             * .then((space) => console.log(`Space ${space.sys.id} renamed.`)
             * .catch(console.error)
             * ```
             */
            update: function updateSpace() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Space',
                    action: 'update',
                    params: { spaceId: raw.sys.id },
                    payload: raw,
                    headers: {},
                }).then((data) => wrapSpace(makeRequest, data));
            },
            /**
             * Unarchives the space
             * @returns Promise for the unarchived space.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => {
             *   return space.unarchive({productId: 'id'})
             * })
             * .then((space) => console.log(`Space ${space.sys.id} unarchived.`)
             * .catch(console.error)
             * ```
             */
            unarchive: function unarchiveSpace(productId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Space',
                    action: 'unarchive',
                    params: { spaceId: raw.sys.id },
                    payload: { productId },
                    headers: {},
                }).then((data) => wrapSpace(makeRequest, data));
            },
            /**
             * Gets an environment
             * @param id - Environment ID
             * @returns Promise for an Environment
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironment('<environment_id>'))
             * .then((environment) => console.log(environment))
             * .catch(console.error)
             * ```
             */
            getEnvironment(environmentId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Environment',
                    action: 'get',
                    params: { spaceId: raw.sys.id, environmentId },
                }).then((data) => wrapEnvironment(makeRequest, data));
            },
            /**
             * Gets a collection of Environments
             * @returns Promise for a collection of Environment
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironments())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEnvironments(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Environment',
                    action: 'getMany',
                    params: { spaceId: raw.sys.id, query },
                }).then((data) => wrapEnvironmentCollection(makeRequest, data));
            },
            /**
             * Creates an environment
             * @param data - Object representation of the Environment to be created
             * @returns Promise for the newly created Environment
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createEnvironment({ name: 'Staging' }))
             * .then((environment) => console.log(environment))
             * .catch(console.error)
             * ```
             */
            createEnvironment(data = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Environment',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.id,
                    },
                    payload: data,
                }).then((response) => wrapEnvironment(makeRequest, response));
            },
            /**
             * Creates an Environment with a custom ID
             * @param id - Environment ID
             * @param data - Object representation of the Environment to be created
             * @param sourceEnvironmentId - ID of the source environment that will be copied to create the new environment. Default is "master"
             * @returns Promise for the newly created Environment
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createEnvironmentWithId('<environment-id>', { name: 'Staging'}, 'master'))
             * .then((environment) => console.log(environment))
             * .catch(console.error)
             * ```
             */
            createEnvironmentWithId(id, data, sourceEnvironmentId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Environment',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.id,
                        environmentId: id,
                        sourceEnvironmentId,
                    },
                    payload: data,
                }).then((response) => wrapEnvironment(makeRequest, response));
            },
            /**
             * Gets a Webhook
             * @param id - Webhook ID
             * @returns Promise for a Webhook
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getWebhook('<webhook_id>'))
             * .then((webhook) => console.log(webhook))
             * .catch(console.error)
             * ```
             */
            getWebhook(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'get',
                    params: { spaceId: raw.sys.id, webhookDefinitionId: id },
                }).then((data) => wrapWebhook(makeRequest, data));
            },
            /**
             * Gets a collection of Webhooks
             * @returns Promise for a collection of Webhooks
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getWebhooks())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getWebhooks() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'getMany',
                    params: { spaceId: raw.sys.id },
                }).then((data) => wrapWebhookCollection(makeRequest, data));
            },
            /**
             * Fetch a webhook signing secret
             * @returns Promise for the redacted webhook signing secret in this space
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.getWebhookSigningSecret())
             *   .then((response) => console.log(response.redactedValue))
             *   .catch(console.error)
             * ```
             */
            getWebhookSigningSecret: function getSigningSecret() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'getSigningSecret',
                    params: { spaceId: raw.sys.id },
                });
            },
            /**
             * Fetch a webhook retry policy
             * @returns Promise for the redacted webhook retry policy in this space
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.getRetryPolicy())
             *   .then((response) => console.log(response.redactedValue))
             *   .catch(console.error)
             * ```
             */
            getWebhookRetryPolicy: function getWebhookRetryPolicy() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'getRetryPolicy',
                    params: { spaceId: raw.sys.id },
                });
            },
            /**
             * Creates a Webhook
             * @param data - Object representation of the Webhook to be created
             * @returns Promise for the newly created Webhook
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createWebhook({
             *   'name': 'My webhook',
             *   'url': 'https://www.example.com/test',
             *   'topics': [
             *     'Entry.create',
             *     'ContentType.create',
             *     '*.publish',
             *     'Asset.*'
             *   ]
             * }))
             * .then((webhook) => console.log(webhook))
             * .catch(console.error)
             * ```
             */
            createWebhook(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'create',
                    params: { spaceId: raw.sys.id },
                    payload: data,
                }).then((data) => wrapWebhook(makeRequest, data));
            },
            /**
             * Creates a Webhook with a custom ID
             * @param id - Webhook ID
             * @param  data - Object representation of the Webhook to be created
             * @returns Promise for the newly created Webhook
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createWebhookWithId('<webhook_id>', {
             *   'name': 'My webhook',
             *   'url': 'https://www.example.com/test',
             *   'topics': [
             *     'Entry.create',
             *     'ContentType.create',
             *     '*.publish',
             *     'Asset.*'
             *   ]
             * }))
             * .then((webhook) => console.log(webhook))
             * .catch(console.error)
             * ```
             */
            createWebhookWithId(id, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'createWithId',
                    params: { spaceId: raw.sys.id, webhookDefinitionId: id },
                    payload: data,
                }).then((data) => wrapWebhook(makeRequest, data));
            },
            /**
             * Create or update the webhook signing secret for this space
             * @param data 64 character string that will be used to sign the webhook calls
             * @returns Promise for the redacted webhook signing secret that was created or updated
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const crypto = require('crypto')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const signingSecret = client.getSpace('<space_id>')
             *   .then((space) => space.upsertWebhookSigningSecret({
             *     value: crypto.randomBytes(32).toString('hex')
             *   }))
             *   .then((response) => console.log(response.redactedValue))
             *   .catch(console.error)
             * ```
             */
            upsertWebhookSigningSecret: function getSigningSecret(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'upsertSigningSecret',
                    params: { spaceId: raw.sys.id },
                    payload: data,
                });
            },
            /**
             * Create or update the webhook retry policy for this space
             * @param data the maxRetries with integer value >= 2 and <= 99 value to set in the Retry Policy
             * @returns Promise for the redacted webhook retry policy that was created or updated
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * const retryPolicy = client.getSpace('<space_id>')
             *   .then((space) => space.upsertWebhookRetryPolicy({
             *     maxRetries: 15
             *   }))
             *   .then((response) => console.log(response.redactedValue))
             *   .catch(console.error)
             * ```
             */
            upsertWebhookRetryPolicy: function upsertWebhookRetryPolicy(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'upsertRetryPolicy',
                    params: { spaceId: raw.sys.id },
                    payload: data,
                });
            },
            /**
             * Delete the webhook signing secret for this space
             * @returns Promise<void>
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.deleteWebhookSigningSecret())
             *   .then(() => console.log("success"))
             *   .catch(console.error)
             * ```
             */
            deleteWebhookSigningSecret: function getSigningSecret() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'deleteSigningSecret',
                    params: { spaceId: raw.sys.id },
                });
            },
            /**
             * Delete the webhook retry policy for this space
             * @returns Promise<void>
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             *   .then((space) => space.deleteWebhookRetryPolicy())
             *   .then(() => console.log("success"))
             *   .catch(console.error)
             * ```
             */
            deleteWebhookRetryPolicy: function deleteRetryPolicy() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Webhook',
                    action: 'deleteRetryPolicy',
                    params: { spaceId: raw.sys.id },
                });
            },
            /**
             * Gets a Role
             * @param id - Role ID
             * @returns Promise for a Role
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createRole({
             *   fields: {
             *     title: {
             *       'en-US': 'Role title'
             *     }
             *   }
             * }))
             * .then((role) => console.log(role))
             * .catch(console.error)
             * ```
             */
            getRole(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'get',
                    params: { spaceId: raw.sys.id, roleId: id },
                }).then((data) => wrapRole(makeRequest, data));
            },
            /**
             * Gets a collection of Roles
             * @returns Promise for a collection of Roles
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getRoles())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getRoles(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'getMany',
                    params: { spaceId: raw.sys.id, query: createRequestConfig({ query }).params },
                }).then((data) => wrapRoleCollection(makeRequest, data));
            },
            /**
             * Creates a Role
             * @param data - Object representation of the Role to be created
             * @returns  Promise for the newly created Role
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * client.getSpace('<space_id>')
             * .then((space) => space.createRole({
             *   name: 'My Role',
             *   description: 'foobar role',
             *   permissions: {
             *     ContentDelivery: 'all',
             *     ContentModel: ['read'],
             *     Settings: []
             *   },
             *   policies: [
             *     {
             *       effect: 'allow',
             *       actions: 'all',
             *       constraint: {
             *         and: [
             *           {
             *             equals: [
             *               { doc: 'sys.type' },
             *               'Entry'
             *             ]
             *           },
             *           {
             *             equals: [
             *               { doc: 'sys.type' },
             *               'Asset'
             *             ]
             *           }
             *         ]
             *       }
             *     }
             *   ]
             * }))
             * .then((role) => console.log(role))
             * .catch(console.error)
             * ```
             */
            createRole(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'create',
                    params: { spaceId: raw.sys.id },
                    payload: data,
                }).then((data) => wrapRole(makeRequest, data));
            },
            /**
             * Creates a Role with a custom ID
             * @param id - Role ID
             * @param data - Object representation of the Role to be created
             * @returns Promise for the newly created Role
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * client.getSpace('<space_id>')
             * .then((space) => space.createRoleWithId('<role-id>', {
             *   name: 'My Role',
             *   description: 'foobar role',
             *   permissions: {
             *     ContentDelivery: 'all',
             *     ContentModel: ['read'],
             *     Settings: []
             *   },
             *   policies: [
             *     {
             *       effect: 'allow',
             *       actions: 'all',
             *       constraint: {
             *         and: [
             *           {
             *             equals: [
             *               { doc: 'sys.type' },
             *               'Entry'
             *             ]
             *           },
             *           {
             *             equals: [
             *               { doc: 'sys.type' },
             *               'Asset'
             *             ]
             *           }
             *         ]
             *       }
             *     }
             *   ]
             * }))
             * .then((role) => console.log(role))
             * .catch(console.error)
             * ```
             */
            createRoleWithId(id, roleData) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'createWithId',
                    params: { spaceId: raw.sys.id, roleId: id },
                    payload: roleData,
                }).then((data) => wrapRole(makeRequest, data));
            },
            /**
             * Gets a User
             * @param userId - User ID
             * @returns Promise for a User
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceUser('id'))
             * .then((user) => console.log(user))
             * .catch(console.error)
             * ```
             */
            getSpaceUser(userId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'User',
                    action: 'getForSpace',
                    params: {
                        spaceId: raw.sys.id,
                        userId,
                    },
                }).then((data) => wrapUser(makeRequest, data));
            },
            /**
             * Gets a collection of Users in a space
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise a collection of Users in a space
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceUsers(query))
             * .then((data) => console.log(data))
             * .catch(console.error)
             * ```
             */
            getSpaceUsers(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'User',
                    action: 'getManyForSpace',
                    params: {
                        spaceId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapUserCollection(makeRequest, data));
            },
            /**
             * Gets a collection of teams for a space
             * @param query
             * @returns Promise for a collection of teams for a space
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getTeams())
             * .then((teamsCollection) => console.log(teamsCollection))
             * .catch(console.error)
             * ```
             */
            getTeams(query = { limit: 100 }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Team',
                    action: 'getManyForSpace',
                    params: {
                        spaceId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapTeamCollection(makeRequest, data));
            },
            /**
             * Gets a Space Member
             * @param id Get Space Member by user_id
             * @returns Promise for a Space Member
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceMember(id))
             * .then((spaceMember) => console.log(spaceMember))
             * .catch(console.error)
             * ```
             */
            getSpaceMember(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMember',
                    action: 'get',
                    params: { spaceId: raw.sys.id, spaceMemberId: id },
                }).then((data) => wrapSpaceMember(makeRequest, data));
            },
            /**
             * Gets a collection of Space Members
             * @param query
             * @returns Promise for a collection of Space Members
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceMembers({'limit': 100}))
             * .then((spaceMemberCollection) => console.log(spaceMemberCollection))
             * .catch(console.error)
             * ```
             */
            getSpaceMembers(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMember',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapSpaceMemberCollection(makeRequest, data));
            },
            /**
             * Gets a Space Membership
             * Warning: the user attribute in the space membership root is deprecated. The attribute has been moved inside the sys  object (i.e. sys.user).
             * @param id - Space Membership ID
             * @returns Promise for a Space Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceMembership('id'))
             * .then((spaceMembership) => console.log(spaceMembership))
             * .catch(console.error)
             * ```
             */
            getSpaceMembership(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'get',
                    params: { spaceId: raw.sys.id, spaceMembershipId: id },
                }).then((data) => wrapSpaceMembership(makeRequest, data));
            },
            /**
             * Gets a collection of Space Memberships
             * Warning: the user attribute in the space membership root is deprecated. The attribute has been moved inside the sys  object (i.e. sys.user).
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of Space Memberships
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceMemberships({'limit': 100})) // you can add more queries as 'key': 'value'
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getSpaceMemberships(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapSpaceMembershipCollection(makeRequest, data));
            },
            /**
             * Creates a Space Membership
             * Warning: the user attribute in the space membership root is deprecated. The attribute has been moved inside the sys  object (i.e. sys.user).
             * @param  data - Object representation of the Space Membership to be created
             * @returns Promise for the newly created Space Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createSpaceMembership({
             *   admin: false,
             *   roles: [
             *     {
             *       type: 'Link',
             *       linkType: 'Role',
             *       id: '<role_id>'
             *     }
             *   ],
             *   email: 'foo@example.com'
             * }))
             * .then((spaceMembership) => console.log(spaceMembership))
             * .catch(console.error)
             * ```
             */
            createSpaceMembership(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.id,
                    },
                    payload: data,
                }).then((response) => wrapSpaceMembership(makeRequest, response));
            },
            /**
             * Creates a Space Membership with a custom ID
             * Warning: the user attribute in the space membership root is deprecated. The attribute has been moved inside the sys  object (i.e. sys.user).
             * @param id - Space Membership ID
             * @param data - Object representation of the Space Membership to be created
             * @returns Promise for the newly created Space Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createSpaceMembershipWithId('<space-membership-id>', {
             *   admin: false,
             *   roles: [
             *     {
             *       type: 'Link',
             *       linkType: 'Role',
             *       id: '<role_id>'
             *     }
             *   ],
             *   email: 'foo@example.com'
             * }))
             * .then((spaceMembership) => console.log(spaceMembership))
             * .catch(console.error)
             * ```
             */
            createSpaceMembershipWithId(id, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'createWithId',
                    params: {
                        spaceId: raw.sys.id,
                        spaceMembershipId: id,
                    },
                    payload: data,
                }).then((response) => wrapSpaceMembership(makeRequest, response));
            },
            /**
             * Gets a Team Space Membership
             * @param id - Team Space Membership ID
             * @returns Promise for a Team Space Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getTeamSpaceMembership('team_space_membership_id'))
             * .then((teamSpaceMembership) => console.log(teamSpaceMembership))
             * .catch(console.error)
             * ```
             */
            getTeamSpaceMembership(teamSpaceMembershipId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.id,
                        teamSpaceMembershipId,
                    },
                }).then((data) => wrapTeamSpaceMembership(makeRequest, data));
            },
            /**
             * Gets a collection of Team Space Memberships
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of Team Space Memberships
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getTeamSpaceMemberships())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getTeamSpaceMemberships(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapTeamSpaceMembershipCollection(makeRequest, data));
            },
            /**
           * Creates a Team Space Membership
           * @param id - Team ID
           * @param data - Object representation of the Team Space Membership to be created
           * @returns Promise for the newly created Team Space Membership
           * @example ```javascript
           * const contentful = require('contentful-management')
           *
           * const client = contentful.createClient({
           *   accessToken: '<content_management_api_key>'
           * })
           *
           * client.getSpace('<space_id>')
           * .then((space) => space.createTeamSpaceMembership('team_id', {
           *   admin: false,
           *   roles: [
           *    {
                  sys: {
           *       type: 'Link',
           *       linkType: 'Role',
           *       id: '<role_id>'
           *      }
           *    }
           *   ],
           * }))
           * .then((teamSpaceMembership) => console.log(teamSpaceMembership))
           * .catch(console.error)
           * ```
           */
            createTeamSpaceMembership(teamId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'create',
                    params: {
                        spaceId: raw.sys.id,
                        teamId,
                    },
                    payload: data,
                }).then((response) => wrapTeamSpaceMembership(makeRequest, response));
            },
            /**
             * Gets a Api Key
             * @param id - API Key ID
             * @returns  Promise for a Api Key
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getApiKey('<apikey-id>'))
             * .then((apikey) => console.log(apikey))
             * .catch(console.error)
             * ```
             */
            getApiKey(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ApiKey',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.id,
                        apiKeyId: id,
                    },
                }).then((data) => wrapApiKey(makeRequest, data));
            },
            /**
             * Gets a collection of Api Keys
             * @returns Promise for a collection of Api Keys
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getApiKeys())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getApiKeys() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ApiKey',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                    },
                }).then((data) => wrapApiKeyCollection(makeRequest, data));
            },
            /**
             * Gets a collection of preview Api Keys
             * @returns Promise for a collection of Preview Api Keys
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getPreviewApiKeys())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getPreviewApiKeys() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'PreviewApiKey',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                    },
                }).then((data) => wrapPreviewApiKeyCollection(makeRequest, data));
            },
            /**
             * Gets a preview Api Key
             * @param id - Preview API Key ID
             * @returns  Promise for a Preview Api Key
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getPreviewApiKey('<preview-apikey-id>'))
             * .then((previewApikey) => console.log(previewApikey))
             * .catch(console.error)
             * ```
             */
            getPreviewApiKey(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'PreviewApiKey',
                    action: 'get',
                    params: {
                        spaceId: raw.sys.id,
                        previewApiKeyId: id,
                    },
                }).then((data) => wrapPreviewApiKey(makeRequest, data));
            },
            /**
             * Creates a Api Key
             * @param payload - Object representation of the Api Key to be created
             * @returns Promise for the newly created Api Key
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createApiKey({
             *   name: 'API Key name',
             *   environments:[
             *    {
             *     sys: {
             *      type: 'Link'
             *      linkType: 'Environment',
             *      id:'<environment_id>'
             *     }
             *    }
             *   ]
             *   }
             * }))
             * .then((apiKey) => console.log(apiKey))
             * .catch(console.error)
             * ```
             */
            createApiKey: function createApiKey(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ApiKey',
                    action: 'create',
                    params: { spaceId: raw.sys.id },
                    payload,
                }).then((data) => wrapApiKey(makeRequest, data));
            },
            /**
             * Creates a Api Key with a custom ID
             * @param id - Api Key ID
             * @param payload - Object representation of the Api Key to be created
             * @returns Promise for the newly created Api Key
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createApiKeyWithId('<api-key-id>', {
             *   name: 'API Key name'
             *   environments:[
             *    {
             *     sys: {
             *      type: 'Link'
             *      linkType: 'Environment',
             *      id:'<environment_id>'
             *     }
             *    }
             *   ]
             *   }
             * }))
             * .then((apiKey) => console.log(apiKey))
             * .catch(console.error)
             * ```
             */
            createApiKeyWithId(id, payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ApiKey',
                    action: 'createWithId',
                    params: { spaceId: raw.sys.id, apiKeyId: id },
                    payload,
                }).then((data) => wrapApiKey(makeRequest, data));
            },
            /**
             * Creates an EnvironmentAlias with a custom ID
             * @param environmentAliasId - EnvironmentAlias ID
             * @param data - Object representation of the EnvironmentAlias to be created
             * @returns Promise for the newly created EnvironmentAlias
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.createEnvironmentAliasWithId('<environment-alias-id>', {
             *   environment: {
             *     sys: { type: 'Link', linkType: 'Environment', id: 'targetEnvironment' }
             *   }
             * }))
             * .then((environmentAlias) => console.log(environmentAlias))
             * .catch(console.error)
             * ```
             */
            createEnvironmentAliasWithId(environmentAliasId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentAlias',
                    action: 'createWithId',
                    params: { spaceId: raw.sys.id, environmentAliasId },
                    payload: data,
                }).then((response) => wrapEnvironmentAlias(makeRequest, response));
            },
            /**
             * Gets an Environment Alias
             * @param Environment Alias ID
             * @returns Promise for an Environment Alias
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironmentAlias('<alias-id>'))
             * .then((alias) => console.log(alias))
             * .catch(console.error)
             * ```
             */
            getEnvironmentAlias(environmentAliasId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentAlias',
                    action: 'get',
                    params: { spaceId: raw.sys.id, environmentAliasId },
                }).then((data) => wrapEnvironmentAlias(makeRequest, data));
            },
            /**
             * Gets a collection of Environment Aliases
             * @returns Promise for a collection of Environment Aliases
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEnvironmentAliases()
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEnvironmentAliases() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentAlias',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                    },
                }).then((data) => wrapEnvironmentAliasCollection(makeRequest, data));
            },
            /**
             * Query for scheduled actions in space.
             * @param query - Object with search parameters. The enviroment id field is mandatory. Check the <a href="https://www.contentful.com/developers/docs/references/content-management-api/#/reference/scheduled-actions/scheduled-actions-collection">REST API reference</a> for more details.
             * @returns Promise for the scheduled actions query
             *
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  client.getSpace('<space_id>')
             *    .then((space) => space.getScheduledActions({
             *      'environment.sys.id': '<environment_id>',
             *      'sys.status': 'scheduled'
             *    }))
             *    .then((scheduledActionCollection) => console.log(scheduledActionCollection.items))
             *    .catch(console.error)
             * ```
             */
            getScheduledActions(query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'getMany',
                    params: { spaceId: raw.sys.id, query },
                }).then((response) => wrapScheduledActionCollection(makeRequest, response));
            },
            /**
             * Get a Scheduled Action in the current space by environment and ID.
             *
             * @throws if the Scheduled Action cannot be found or the user doesn't have permission to read schedules from the entity of the scheduled action itself.
             * @returns Promise with the Scheduled Action
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  client.getSpace('<space_id>')
             *    .then((space) => space.getScheduledAction({
             *      scheduledActionId: '<scheduled-action-id>',
             *      environmentId: '<environmentId>'
             *    }))
             *    .then((scheduledAction) => console.log(scheduledAction))
             *    .catch(console.error)
             * ```
             */
            getScheduledAction({ scheduledActionId, environmentId, }) {
                const space = this.toPlainObject();
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'get',
                    params: {
                        spaceId: space.sys.id,
                        environmentId,
                        scheduledActionId,
                    },
                }).then((scheduledAction) => wrapScheduledAction(makeRequest, scheduledAction));
            },
            /**
             * Creates a scheduled action
             * @param data - Object representation of the scheduled action to be created
             * @returns Promise for the newly created scheduled actions
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  client.getSpace('<space_id>')
             *    .then((space) => space.createScheduledAction({
             *      entity: {
             *        sys: {
             *          type: 'Link',
             *          linkType: 'Entry',
             *          id: '<entry_id>'
             *        }
             *      },
             *      environment: {
             *        sys: {
             *          type: 'Link',
             *          linkType: 'Environment',
             *          id: '<environment_id>'
             *        }
             *      },
             *      action: 'publish',
             *      scheduledFor: {
             *        datetime: <ISO_date_string>,
             *        timezone: 'Europe/Berlin'
             *      }
             *    }))
             *    .then((scheduledAction) => console.log(scheduledAction))
             *    .catch(console.error)
             * ```
             */
            createScheduledAction(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'create',
                    params: { spaceId: raw.sys.id },
                    payload: data,
                }).then((response) => wrapScheduledAction(makeRequest, response));
            },
            /**
             * Update a scheduled action
             * @param {object} options
             * @param options.scheduledActionId the id of the scheduled action to update
             * @param options.version the sys.version of the scheduled action to be updated
             * @param payload the scheduled actions object with updates, omitting sys object
             * @returns Promise containing a wrapped scheduled action with helper methods
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  client.getSpace('<space_id>')
             *    .then((space) => {
             *      return space.createScheduledAction({
             *        entity: {
             *          sys: {
             *            type: 'Link',
             *            linkType: 'Entry',
             *            id: '<entry_id>'
             *          }
             *        },
             *        environment: {
             *          sys: {
             *            type: 'Link',
             *            linkType: 'Environment',
             *            id: '<environment_id>'
             *          }
             *        },
             *        action: 'publish',
             *        scheduledFor: {
             *          datetime: <ISO_date_string>,
             *          timezone: 'Europe/Berlin'
             *        }
             *      })
             *      .then((scheduledAction) => {
             *        const { _sys, ...payload } = scheduledAction;
             *        return space.updateScheduledAction({
             *          ...payload,
             *          scheduledFor: {
             *            ...payload.scheduledFor,
             *            timezone: 'Europe/Paris'
             *          }
             *        })
             *      })
             *    .then((scheduledAction) => console.log(scheduledAction))
             *    .catch(console.error);
             * ```
             */
            updateScheduledAction({ scheduledActionId, payload, version, }) {
                const spaceProps = this.toPlainObject();
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'update',
                    params: {
                        spaceId: spaceProps.sys.id,
                        version,
                        scheduledActionId,
                    },
                    payload,
                }).then((response) => wrapScheduledAction(makeRequest, response));
            },
            /**
             * Cancels a Scheduled Action.
             * Only cancels actions that have not yet executed.
             *
             * @param {object} options
             * @param options.scheduledActionId the id of the scheduled action to be canceled
             * @param options.environmentId the environment ID of the scheduled action to be canceled
             * @throws if the Scheduled Action cannot be found or the user doesn't have permissions in the entity in the action.
             * @returns Promise containing a wrapped Scheduled Action with helper methods
             * @example ```javascript
             *  const contentful = require('contentful-management');
             *
             *  const client = contentful.createClient({
             *    accessToken: '<content_management_api_key>'
             *  })
             *
             *  // Given that an Scheduled Action is scheduled
             *  client.getSpace('<space_id>')
             *    .then((space) => space.deleteScheduledAction({
             *        environmentId: '<environment-id>',
             *        scheduledActionId: '<scheduled-action-id>'
             *     }))
             *     // The scheduled Action sys.status is now 'canceled'
             *    .then((scheduledAction) => console.log(scheduledAction))
             *    .catch(console.error);
             * ```
             */
            deleteScheduledAction({ scheduledActionId, environmentId, }) {
                const spaceProps = this.toPlainObject();
                return makeRequest({
                    entityType: 'ScheduledAction',
                    action: 'delete',
                    params: {
                        spaceId: spaceProps.sys.id,
                        environmentId,
                        scheduledActionId,
                    },
                }).then((response) => wrapScheduledAction(makeRequest, response));
            },
            /**
             * Gets a single AI Action.
             * @param aiActionId - AI Action ID
             * @returns Promise for an AI Action
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.getAiAction('<ai_action_id>'))
             *   .then((aiAction) => console.log(aiAction))
             *   .catch(console.error)
             * ```
             */
            getAiAction(aiActionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'get',
                    params: { spaceId: raw.sys.id, aiActionId },
                }).then((data) => wrapAiAction(makeRequest, data));
            },
            /**
             * Gets a collection of AI Actions.
             * @param query - Object with search parameters.
             * @returns Promise for a collection of AI Actions
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.getAiActions({ limit: 10 }))
             *   .then((response) => console.log(response.items))
             *   .catch(console.error)
             * ```
             */
            getAiActions(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'getMany',
                    params: { spaceId: raw.sys.id, query },
                }).then((data) => wrapAiActionCollection(makeRequest, data));
            },
            /**
             * Creates an AI Action.
             * @param data - Object representation of the AI Action to be created
             * @returns Promise for the newly created AI Action
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.createAiAction({
             *     name: 'My AI Action',
             *     description: 'Description here',
             *     configuration: { modelType: 'model-x', modelTemperature: 0.7 },
             *     instruction: { template: 'Do something: {{var.input}}', variables: [], conditions: [] },
             *     testCases: []
             *   }))
             *   .then((aiAction) => console.log(aiAction))
             *   .catch(console.error)
             * ```
             */
            createAiAction(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'create',
                    params: { spaceId: raw.sys.id },
                    payload: data,
                }).then((response) => wrapAiAction(makeRequest, response));
            },
            /**
             * Updates an AI Action.
             * @param aiActionId - AI Action ID
             * @param data - Object representation of the AI Action update
             * @returns Promise for the updated AI Action
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.updateAiAction('<ai_action_id>', { name: 'New Name', ... }))
             *   .then((aiAction) => console.log(aiAction))
             *   .catch(console.error)
             * ```
             */
            updateAiAction(aiActionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'update',
                    params: { spaceId: raw.sys.id, aiActionId },
                    payload: data,
                    headers: { 'X-Contentful-Version': data.sys.version ?? 0 },
                }).then((response) => wrapAiAction(makeRequest, response));
            },
            /**
             * Publishes an AI Action.
             * @param aiActionId - AI Action ID
             * @param data - Object representation of the AI Action to be published
             * @returns Promise for the published AI Action
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.publishAiAction('<ai_action_id>', { ... }))
             *   .then((aiAction) => console.log(aiAction))
             *   .catch(console.error)
             * ```
             */
            publishAiAction(aiActionId, { version }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'publish',
                    params: { spaceId: raw.sys.id, aiActionId, version },
                }).then((response) => wrapAiAction(makeRequest, response));
            },
            /**
             * Unpublishes an AI Action.
             * @param aiActionId - AI Action ID
             * @returns Promise for the unpublished AI Action
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.unpublishAiAction('<ai_action_id>'))
             *   .then((aiAction) => console.log(aiAction))
             *   .catch(console.error)
             * ```
             */
            unpublishAiAction(aiActionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'unpublish',
                    params: { spaceId: raw.sys.id, aiActionId },
                }).then((response) => wrapAiAction(makeRequest, response));
            },
            /**
             * Deletes an AI Action.
             * @param aiActionId - AI Action ID
             * @returns Promise for deletion (void)
             * @example
             * ```javascript
             * client.getSpace('<space_id>')
             *   .then((space) => space.deleteAiAction('<ai_action_id>'))
             *   .then(() => console.log('AI Action deleted'))
             *   .catch(console.error)
             * ```
             */
            deleteAiAction(aiActionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AiAction',
                    action: 'delete',
                    params: { spaceId: raw.sys.id, aiActionId },
                });
            },
            /**
             * Gets a collection of Space Add-ons
             * @param query - Object with search parameters (skip, limit)
             * @returns Promise for a collection of Space Add-ons
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getSpaceAddOns())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getSpaceAddOns(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceAddOn',
                    action: 'getMany',
                    params: { spaceId: raw.sys.id, query: createRequestConfig({ query }).params },
                }).then((data) => wrapSpaceAddOnCollection(makeRequest, data));
            },
            /**
             * Gets a collection of Eligible Licenses for the space
             * @param query - Object with search parameters. The API supports pagination with skip and limit parameters.
             * @returns Promise for a collection of Eligible Licenses that can be assigned to this space
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.getEligibleLicenses({ limit: 10, skip: 0 }))
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEligibleLicenses(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EligibleLicense',
                    action: 'getMany',
                    params: {
                        spaceId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapEligibleLicenseCollection(makeRequest, data));
            },
            /**
             * Updates Space Add-on allocations
             * @param allocations - Array of add-on allocation updates
             * @returns Promise for the updated collection of Space Add-ons
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => space.updateSpaceAddOnAllocations([
             *   { add_on: 'contentTypes', allocation: 10 },
             *   { add_on: 'records', allocation: 1000 }
             * ]))
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            updateSpaceAddOnAllocations(allocations) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceAddOn',
                    action: 'updateAllocations',
                    params: { spaceId: raw.sys.id },
                    payload: allocations,
                }).then((data) => wrapSpaceAddOnCollection(makeRequest, data));
            },
        };
    }

    /**
     * This method creates the API for the given space with all the methods for
     * reading and creating other entities. It also passes down a clone of the
     * http client with a space id, so the base path for requests now has the
     * space id already set.
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - API response for a Space
     * @returns {Space}
     */
    function wrapSpace(makeRequest, data) {
        const space = toPlainObject(index$2(data));
        const spaceApi = createSpaceApi(makeRequest);
        const enhancedSpace = enhanceWithMethods(space, spaceApi);
        return freezeSys(enhancedSpace);
    }
    /**
     * This method wraps each space in a collection with the space API. See wrapSpace
     * above for more details.
     * @internal
     */
    const wrapSpaceCollection = wrapCollection(wrapSpace);
    const wrapSpaceCursorPaginatedCollection = wrapCursorPaginatedCollection(wrapSpace);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw  personal access token data
     * @returns Wrapped personal access token
     */
    function wrapPersonalAccessToken(makeRequest, data) {
        const personalAccessToken = toPlainObject(index$2(data));
        const personalAccessTokenWithMethods = enhanceWithMethods(personalAccessToken, {
            revoke: function () {
                return makeRequest({
                    entityType: 'PersonalAccessToken',
                    action: 'revoke',
                    params: { tokenId: data.sys.id },
                }).then((data) => wrapPersonalAccessToken(makeRequest, data));
            },
        });
        return freezeSys(personalAccessTokenWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw personal access collection data
     * @returns Wrapped personal access token collection data
     */
    const wrapPersonalAccessTokenCollection = wrapCollection(wrapPersonalAccessToken);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw  access token data
     * @returns Wrapped access token
     */
    function wrapAccessToken(makeRequest, data) {
        const AccessToken = toPlainObject(index$2(data));
        const accessTokenWithMethods = enhanceWithMethods(AccessToken, {
            revoke: function () {
                return makeRequest({
                    entityType: 'AccessToken',
                    action: 'revoke',
                    params: { tokenId: data.sys.id },
                }).then((data) => wrapAccessToken(makeRequest, data));
            },
        });
        return freezeSys(accessTokenWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw access collection data
     * @returns Wrapped access token collection data
     */
    const wrapAccessTokenCollection = wrapCollection(wrapAccessToken);

    /**
     * @internal
     */
    function createAppBundleApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
            appBundleId: data.sys.id,
        });
        return {
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppBundle',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Bundle data
     * @returns Wrapped App Bundle data
     */
    function wrapAppBundle(makeRequest, data) {
        const appBundle = toPlainObject(index$2(data));
        const appBundleWithMethods = enhanceWithMethods(appBundle, createAppBundleApi(makeRequest));
        return freezeSys(appBundleWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Bundle collection data
     * @returns Wrapped App Bundle collection data
     */
    const wrapAppBundleCollection = wrapCollection(wrapAppBundle);

    /**
     * @internal
     */
    function createResourceProviderApi(makeRequest) {
        return {
            /**
             * Sends an update to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getResourceProvider())
             * .then((resourceProvider) => {
             *    resourceProvider.function.sys.id = '<new_contentful_function_id>'
             *    return resourceProvider.upsert()
             * })
             * .catch(console.error)
             * ```
             */
            upsert: function upsert() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceProvider',
                    action: 'upsert',
                    params: getParams(data),
                    headers: {},
                    payload: getUpsertParams(data),
                }).then((data) => wrapResourceProvider(makeRequest, data));
            },
            /**
             * Deletes this object on the server.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getResourceProvider())
             * .then((resourceProvider) => resourceProvider.delete())
             * .catch(console.error)
             * ```
             */
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceProvider',
                    action: 'delete',
                    params: getParams(data),
                });
            },
            getResourceType: function getResourceType(id) {
                return makeRequest({
                    entityType: 'ResourceType',
                    action: 'get',
                    params: {
                        organizationId: this.sys.organization.sys.id,
                        appDefinitionId: this.sys.appDefinition.sys.id,
                        resourceTypeId: id,
                    },
                }).then((data) => wrapResourceType(makeRequest, data));
            },
            upsertResourceType: function upsertResourceType(id, data) {
                return makeRequest({
                    entityType: 'ResourceType',
                    action: 'upsert',
                    params: {
                        organizationId: this.sys.organization.sys.id,
                        appDefinitionId: this.sys.appDefinition.sys.id,
                        resourceTypeId: id,
                    },
                    headers: {},
                    payload: data,
                }).then((data) => wrapResourceType(makeRequest, data));
            },
            getResourceTypes: function getResourceTypes() {
                return makeRequest({
                    entityType: 'ResourceType',
                    action: 'getMany',
                    params: {
                        organizationId: this.sys.organization.sys.id,
                        appDefinitionId: this.sys.appDefinition.sys.id,
                    },
                }).then((data) => {
                    data.items = data.items.map((item) => wrapResourceType(makeRequest, item));
                    return data;
                });
            },
        };
    }
    /**
     * @internal
     * @param data - raw ResourceProvider Object
     * @returns Object containing the http params for the ResourceProvider request: organizationId and appDefinitionId
     */
    const getParams = (data) => ({
        organizationId: data.sys.organization.sys.id,
        appDefinitionId: data.sys.appDefinition.sys.id,
    });
    /**
     * @internal
     * @param data - raw ResourceProvider Object
     * @returns UpsertResourceProviderProps
     */
    const getUpsertParams = (data) => ({
        sys: { id: data.sys.id },
        type: data.type,
        function: data.function,
    });
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw Resource Provider data
     * @returns Wrapped Resource Provider data
     */
    function wrapResourceProvider(makeRequest, data) {
        const resourceProvider = toPlainObject(index$2(data));
        const ResourceProviderWithMethods = enhanceWithMethods(resourceProvider, createResourceProviderApi(makeRequest));
        return freezeSys(ResourceProviderWithMethods);
    }

    /**
     * @internal
     */
    function createAppDefinitionApi(makeRequest) {
        const getParams = (data) => ({
            appDefinitionId: data.sys.id,
            organizationId: data.sys.organization.sys.id,
        });
        return {
            /**
             * Sends an update to the server with any changes made to the object's properties
             * @returns Object returned from the server with updated changes.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => {
             *   appDefinition.name = 'New App Definition name'
             *   return appDefinition.update()
             * })
             * .then((appDefinition) => console.log(`App Definition ${appDefinition.sys.id} updated.`))
             * .catch(console.error)
             * ```
             */
            update: function update() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'update',
                    params: getParams(data),
                    headers: {},
                    payload: data,
                }).then((data) => wrapAppDefinition(makeRequest, data));
            },
            /**
             * Deletes this object on the server.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.delete())
             * .then(() => console.log(`App Definition deleted.`))
             * .catch(console.error)
             * ```
             */
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'delete',
                    params: getParams(data),
                });
            },
            /**
             * Gets an app bundle
             * @param id - AppBundle ID
             * @returns Promise for an AppBundle
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getAppBundle('<app_upload_id>'))
             * .then((appBundle) => console.log(appBundle))
             * .catch(console.error)
             * ```
             */
            getAppBundle(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppBundle',
                    action: 'get',
                    params: {
                        appBundleId: id,
                        appDefinitionId: raw.sys.id,
                        organizationId: raw.sys.organization.sys.id,
                    },
                }).then((data) => wrapAppBundle(makeRequest, data));
            },
            /**
             * Gets a collection of AppBundles
             * @returns Promise for a collection of AppBundles
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getAppBundles())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getAppBundles(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppBundle',
                    action: 'getMany',
                    params: { organizationId: raw.sys.organization.sys.id, appDefinitionId: raw.sys.id, query },
                }).then((data) => wrapAppBundleCollection(makeRequest, data));
            },
            /**
             * Creates an app bundle
             * @param Object representation of the App Bundle to be created
             * @returns Promise for the newly created AppBundle
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.createAppBundle('<app_upload_id>'))
             * .then((appBundle) => console.log(appBundle))
             * .catch(console.error)
             * ```
             */
            createAppBundle(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppBundle',
                    action: 'create',
                    params: {
                        appDefinitionId: raw.sys.id,
                        organizationId: raw.sys.organization.sys.id,
                    },
                    payload: data,
                }).then((data) => wrapAppBundle(makeRequest, data));
            },
            /**
             * Gets a list of App Installations across an org for given organization and App Definition
             * If a spaceId is provided in the query object, it will return the App Installations for that specific space.
             * @returns Promise for the newly created AppBundle
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * client.getAppDefinition('<organization_id>', '<app_definition_id>')
             * .then((appDefinition) => appDefinition.getInstallationsForOrg(
             *   { spaceId: '<space_id>' } // optional
             * ))
             * .then((appInstallationsForOrg) => console.log(appInstallationsForOrg.items))
             * .catch(console.error)
             * ```
             */
            getInstallationsForOrg(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'getInstallationsForOrg',
                    params: {
                        appDefinitionId: raw.sys.id,
                        organizationId: raw.sys.organization.sys.id,
                        query,
                    },
                });
            },
            /**
             * Creates or updates a resource provider
             * @param data representation of the ResourceProvider
             * @returns Promise for the newly created or updated ResourceProvider
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // You need a valid AppDefinition with an activated AppBundle that has a contentful function configured
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.upsertResourceProvider({
             *    sys: {
             *      id: '<resource_provider_id>'
             *    },
             *    type: 'function',
             *    function: {
             *      sys: {
             *        id: '<contentful_function_id>',
             *        type: 'Link'
             *        linkType: 'Function'
             *      }
             *    }
             * }))
             * .then((resourceProvider) => console.log(resourceProvider))
             * .catch(console.error)
             * ```
             */
            upsertResourceProvider(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceProvider',
                    action: 'upsert',
                    params: {
                        appDefinitionId: raw.sys.id,
                        organizationId: raw.sys.organization.sys.id,
                    },
                    payload: data,
                }).then((payload) => wrapResourceProvider(makeRequest, payload));
            },
            /**
             * Gets a Resource Provider
             * @returns Promise for a Resource Provider
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_def_id>'))
             * .then((appDefinition) => appDefinition.getResourceProvider())
             * .then((resourceProvider) => console.log(resourceProvider))
             * .catch(console.error)
             * ```
             */
            getResourceProvider() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ResourceProvider',
                    action: 'get',
                    params: {
                        appDefinitionId: raw.sys.id,
                        organizationId: raw.sys.organization.sys.id,
                    },
                }).then((payload) => wrapResourceProvider(makeRequest, payload));
            },
        };
    }

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Definition data
     * @returns Wrapped App Definition data
     */
    function wrapAppDefinition(makeRequest, data) {
        const appDefinition = toPlainObject(index$2(data));
        const appDefinitionWithMethods = enhanceWithMethods(appDefinition, createAppDefinitionApi(makeRequest));
        return freezeSys(appDefinitionWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Definition collection data
     * @returns Wrapped App Definition collection data
     */
    const wrapAppDefinitionCollection = wrapCollection(wrapAppDefinition);

    /**
     * @internal
     */
    function createOrganizationMembershipApi(makeRequest, organizationId) {
        const getParams = (data) => ({
            organizationMembershipId: data.sys.id,
            organizationId,
        });
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OrganizationMembership',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapOrganizationMembership(makeRequest, data, organizationId));
            },
            delete: function del() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OrganizationMembership',
                    action: 'delete',
                    params: getParams(raw),
                });
            },
        };
    }
    /**
     * @internal
     * @param {function} makeRequest - function to make requests via an adapter
     * @param {Object} data - Raw organization membership data
     * @returns {OrganizationMembership} Wrapped organization membership data
     */
    function wrapOrganizationMembership(makeRequest, data, organizationId) {
        const organizationMembership = toPlainObject(index$2(data));
        const organizationMembershipWithMethods = enhanceWithMethods(organizationMembership, createOrganizationMembershipApi(makeRequest, organizationId));
        return freezeSys(organizationMembershipWithMethods);
    }
    /**
     * @internal
     */
    const wrapOrganizationMembershipCollection = wrapCollection(wrapOrganizationMembership);

    /**
     * @internal
     */
    function createTeamMembershipApi(makeRequest) {
        const getParams = (data) => ({
            teamMembershipId: data.sys.id,
            teamId: data.sys.team.sys.id,
            organizationId: data.sys.organization.sys.id,
        });
        return {
            update: function () {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamMembership',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                }).then((data) => wrapTeamMembership(makeRequest, data));
            },
            delete: function del() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamMembership',
                    action: 'delete',
                    params: getParams(raw),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw team membership data
     * @returns Wrapped team membership data
     */
    function wrapTeamMembership(makeRequest, data) {
        const teamMembership = toPlainObject(index$2(data));
        const teamMembershipWithMethods = enhanceWithMethods(teamMembership, createTeamMembershipApi(makeRequest));
        return freezeSys(teamMembershipWithMethods);
    }
    /**
     * @internal
     */
    const wrapTeamMembershipCollection = wrapCollection(wrapTeamMembership);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw invitation data
     * @returns {OrganizationInvitation} Wrapped Inviation data
     */
    function wrapOrganizationInvitation(_makeRequest, data) {
        const invitation = toPlainObject(index$2(data));
        return freezeSys(invitation);
    }

    /**
     * @internal
     */
    function createAppUploadApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appUploadId: data.sys.id,
        });
        return {
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppUpload',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Upload data
     * @returns Wrapped App Upload data
     */
    function wrapAppUpload(makeRequest, data) {
        const appUpload = toPlainObject(index$2(data));
        const appUploadWithMethods = enhanceWithMethods(appUpload, createAppUploadApi(makeRequest));
        return freezeSys(appUploadWithMethods);
    }

    function createSigningSecretApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
        });
        return {
            delete: function del() {
                const self = this;
                return makeRequest({
                    entityType: 'AppSigningSecret',
                    action: 'delete',
                    params: getParams(self),
                });
            },
        };
    }
    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppSigningSecret data
     * @returns Wrapped AppSigningSecret data
     */
    function wrapAppSigningSecret(makeRequest, data) {
        const signingSecret = toPlainObject(index$2(data));
        return enhanceWithMethods(signingSecret, createSigningSecretApi(makeRequest));
    }

    function createEventSubscriptionApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
        });
        return {
            delete: function del() {
                const self = this;
                return makeRequest({
                    entityType: 'AppEventSubscription',
                    action: 'delete',
                    params: getParams(self),
                });
            },
        };
    }
    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppEventSubscription data
     * @returns Wrapped AppEventSubscription data
     */
    function wrapAppEventSubscription(makeRequest, data) {
        const eventSubscription = toPlainObject(index$2(data));
        return enhanceWithMethods(eventSubscription, createEventSubscriptionApi(makeRequest));
    }

    function createKeyApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
            fingerprint: data.sys.id,
        });
        return {
            delete: function del() {
                const self = this;
                return makeRequest({
                    entityType: 'AppKey',
                    action: 'delete',
                    params: getParams(self),
                });
            },
        };
    }
    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppKey data
     * @returns Wrapped AppKey data
     */
    function wrapAppKey(makeRequest, data) {
        const key = toPlainObject(index$2(data));
        return enhanceWithMethods(key, createKeyApi(makeRequest));
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Key collection data
     * @returns Wrapped App Key collection data
     */
    const wrapAppKeyCollection = wrapCollection(wrapAppKey);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @returns Wrapped App Details data
     */
    function createAppDetailsApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
        });
        return {
            delete: function del() {
                const self = this;
                return makeRequest({
                    entityType: 'AppDetails',
                    action: 'delete',
                    params: getParams(self),
                });
            },
        };
    }
    /**
     * @internal
     * @param http - HTTP client instance
     * @param data - Raw AppDetails data
     * @returns Wrapped AppDetails data
     */
    function wrapAppDetails(makeRequest, data) {
        const appDetails = toPlainObject(index$2(data));
        return enhanceWithMethods(appDetails, createAppDetailsApi(makeRequest));
    }

    /**
     * @internal
     */
    function createAppActionApi(makeRequest) {
        const getParams = (data) => ({
            organizationId: data.sys.organization.sys.id,
            appDefinitionId: data.sys.appDefinition.sys.id,
            appActionId: data.sys.id,
        });
        return {
            delete: function del() {
                const data = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAction',
                    action: 'delete',
                    params: getParams(data),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Bundle data
     * @returns Wrapped App Bundle data
     */
    function wrapAppAction(makeRequest, data) {
        const appAction = toPlainObject(index$2(data));
        const appActionWithMethods = enhanceWithMethods(appAction, createAppActionApi(makeRequest));
        return freezeSys(appActionWithMethods);
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw App Bundle collection data
     * @returns Wrapped App Bundle collection data
     */
    const wrapAppActionCollection = wrapCollection(wrapAppAction);

    /**
     * @internal
     * Wraps the raw available license data
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw available license data
     * @returns Wrapped available license data
     */
    function wrapAvailableLicense(makeRequest, data) {
        return toPlainObject(index$2(data));
    }
    /**
     * @internal
     */
    const wrapAvailableLicenseCollection = wrapCollection(wrapAvailableLicense);

    function wrapContentSemanticsSettings(_makeRequest, data) {
        const result = toPlainObject(index$2(data));
        return freezeSys(result);
    }

    /**
     * Creates API object with methods to access the Organization API
     * @param {MakeRequest} makeRequest - function to make requests via an adapter
     * @returns {ContentfulOrganizationAPI}
     * @internal
     */
    function createOrganizationApi(makeRequest) {
        return {
            /**
             * Gets a collection of spaces in the organization
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise a collection of Spaces in the organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<organization_id>')
             * .then((organization) => organization.getSpaces())
             * .then((spaces) => console.log(spaces))
             * .catch(console.error)
             * ```
             */
            getSpaces(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Space',
                    action: 'getManyForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapSpaceCollection(makeRequest, data));
            },
            /**
             * Gets a User
             * @returns Promise for a User
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<organization_id>')
             * .then((organization) => organization.getUser('id'))
             * .then((user) => console.log(user))
             * .catch(console.error)
             * ```
             */
            getUser(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'User',
                    action: 'getForOrganization',
                    params: { organizationId: raw.sys.id, userId: id },
                }).then((data) => wrapUser(makeRequest, data));
            },
            /**
             * Gets a collection of Users in organization
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise a collection of Users in organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<organization_id>')
             * .then((organization) => organization.getUsers())
             * .then((users) => console.log(users))
             * .catch(console.error)
             * ```
             */
            getUsers(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'User',
                    action: 'getManyForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query: query }).params,
                    },
                }).then((data) => wrapUserCollection(makeRequest, data));
            },
            /**
             * Gets an Organization Membership
             * @param id - Organization Membership ID
             * @returns Promise for an Organization Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organization_id')
             * .then((organization) => organization.getOrganizationMembership('organizationMembership_id'))
             * .then((organizationMembership) => console.log(organizationMembership))
             * .catch(console.error)
             * ```
             */
            getOrganizationMembership(id) {
                const raw = this.toPlainObject();
                const organizationId = raw.sys.id;
                return makeRequest({
                    entityType: 'OrganizationMembership',
                    action: 'get',
                    params: {
                        organizationId,
                        organizationMembershipId: id,
                    },
                }).then((data) => wrapOrganizationMembership(makeRequest, data, organizationId));
            },
            /**
             * Gets a collection of Organization Memberships
             * @param  params - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a collection of Organization Memberships
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organization_id')
             * .then((organization) => organization.getOrganizationMemberships({'limit': 100})) // you can add more queries as 'key': 'value'
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getOrganizationMemberships(params = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OrganizationMembership',
                    action: 'getMany',
                    params: {
                        organizationId: raw.sys.id,
                        ...params,
                    },
                }).then((data) => wrapOrganizationMembershipCollection(makeRequest, data, raw.sys.id));
            },
            /**
             * Creates a Team
             * @param data representation of the Team to be created
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.createTeam({
             *    name: 'new team',
             *    description: 'new team description'
             *  }))
             * .then((team) => console.log(team))
             * .catch(console.error)
             * ```
             */
            createTeam(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Team',
                    action: 'create',
                    params: { organizationId: raw.sys.id },
                    payload: data,
                }).then((data) => wrapTeam(makeRequest, data));
            },
            /**
             * Gets an Team
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('orgId')
             * .then((organization) => organization.getTeam('teamId'))
             * .then((team) => console.log(team))
             * .catch(console.error)
             * ```
             */
            getTeam(teamId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Team',
                    action: 'get',
                    params: { organizationId: raw.sys.id, teamId },
                }).then((data) => wrapTeam(makeRequest, data));
            },
            /**
             * Gets all Teams in an organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('orgId')
             * .then((organization) => organization.getTeams())
             * .then((teams) => console.log(teams))
             * .catch(console.error)
             * ```
             */
            getTeams(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Team',
                    action: 'getMany',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapTeamCollection(makeRequest, data));
            },
            /**
             * Creates a Team membership
             * @param teamId - Id of the team the membership will be created in
             * @param data - Object representation of the Team Membership to be created
             * @returns Promise for the newly created TeamMembership
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organizationId')
             * .then((org) => org.createTeamMembership('teamId', {
             *    admin: true,
             *    organizationMembershipId: 'organizationMembershipId'
             *  }))
             * .then((teamMembership) => console.log(teamMembership))
             * .catch(console.error)
             * ```
             */
            createTeamMembership(teamId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamMembership',
                    action: 'create',
                    params: { organizationId: raw.sys.id, teamId },
                    payload: data,
                }).then((data) => wrapTeamMembership(makeRequest, data));
            },
            /**
             * Gets an Team Membership from the team with given teamId
             * @returns Promise for an Team Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organizationId')
             * .then((organization) => organization.getTeamMembership('teamId', 'teamMembership_id'))
             * .then((teamMembership) => console.log(teamMembership))
             * .catch(console.error)
             * ```
             */
            getTeamMembership(teamId, teamMembershipId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamMembership',
                    action: 'get',
                    params: { organizationId: raw.sys.id, teamId, teamMembershipId },
                }).then((data) => wrapTeamMembership(makeRequest, data));
            },
            /**
             * Get all Team Memberships. If teamID is provided in the optional config object, it will return all Team Memberships in that team. By default, returns all team memberships for the organization.
             * @returns Promise for a Team Membership Collection
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organizationId')
             * .then((organization) => organization.getTeamMemberships('teamId'))
             * .then((teamMemberships) => console.log(teamMemberships))
             * .catch(console.error)
             * ```
             */
            getTeamMemberships(opts = {}) {
                const { teamId, query = {} } = opts;
                const raw = this.toPlainObject();
                if (teamId) {
                    return makeRequest({
                        entityType: 'TeamMembership',
                        action: 'getManyForTeam',
                        params: {
                            organizationId: raw.sys.id,
                            teamId,
                            query: createRequestConfig({ query }).params,
                        },
                    }).then((data) => wrapTeamMembershipCollection(makeRequest, data));
                }
                return makeRequest({
                    entityType: 'TeamMembership',
                    action: 'getManyForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapTeamMembershipCollection(makeRequest, data));
            },
            /**
             * Get all Team Space Memberships. If teamID is provided in the optional config object, it will return all Team Space Memberships in that team. By default, returns all team space memberships across all teams in the organization.
             * @returns Promise for a Team Space Membership Collection
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organizationId')
             * .then((organization) => organization.getTeamSpaceMemberships('teamId'))
             * .then((teamSpaceMemberships) => console.log(teamSpaceMemberships))
             * .catch(console.error)
             * ```
             */
            getTeamSpaceMemberships(opts = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'getManyForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query: opts.query || {} }).params,
                        teamId: opts.teamId,
                    },
                }).then((data) => wrapTeamSpaceMembershipCollection(makeRequest, data));
            },
            /**
             * Get a Team Space Membership with given teamSpaceMembershipId
             * @returns Promise for a Team Space Membership
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organizationId')
             * .then((organization) => organization.getTeamSpaceMembership('teamSpaceMembershipId'))
             * .then((teamSpaceMembership) => console.log(teamSpaceMembership))
             * .catch(console.error)]
             * ```
             */
            getTeamSpaceMembership(teamSpaceMembershipId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'TeamSpaceMembership',
                    action: 'getForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        teamSpaceMembershipId,
                    },
                }).then((data) => wrapTeamSpaceMembership(makeRequest, data));
            },
            /**
             * Gets an Space Membership in Organization
             * @param id - Organiztion Space Membership ID
             * @returns Promise for a Space Membership in an organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organization_id')
             * .then((organization) => organization.getOrganizationSpaceMembership('organizationSpaceMembership_id'))
             * .then((organizationMembership) => console.log(organizationMembership))
             * .catch(console.error)
             * ```
             */
            getOrganizationSpaceMembership(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'getForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        spaceMembershipId: id,
                    },
                }).then((data) => wrapSpaceMembership(makeRequest, data));
            },
            /**
             * Gets a collection Space Memberships in organization
             * @param query - Object with search parameters. Check the <a href="https://www.contentful.com/developers/docs/javascript/tutorials/using-js-cda-sdk/#retrieving-entries-with-search-parameters">JS SDK tutorial</a> and the <a href="https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters">REST API reference</a> for more details.
             * @returns Promise for a Space Membership collection across all spaces in the organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organization_id')
             * .then((organization) => organization.getOrganizationSpaceMemberships()) // you can add queries like 'limit': 100
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getOrganizationSpaceMemberships(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceMembership',
                    action: 'getManyForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapSpaceMembershipCollection(makeRequest, data));
            },
            /**
             * Gets a collection of Available Licenses for the organization
             * @param query - Object with search parameters. The API supports pagination with skip and limit parameters.
             * @returns Promise for a collection of Available Licenses
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('organization_id')
             * .then((organization) => organization.getAvailableLicenses({ limit: 10, skip: 0 }))
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getAvailableLicenses(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AvailableLicense',
                    action: 'getMany',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapAvailableLicenseCollection(makeRequest, data));
            },
            /**
             * Gets a collection of space add-ons across all spaces in the organization
             * @param query - Object with search parameters
             * @returns Promise for a collection of SpaceAddOnsOrganization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<organization_id>')
             * .then((organization) => organization.getSpaceAddOns())
             * .then((addOns) => console.log(addOns))
             * .catch(console.error)
             * ```
             */
            getSpaceAddOns(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SpaceAddOn',
                    action: 'getManyForOrganization',
                    params: {
                        organizationId: raw.sys.id,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapSpaceAddOnOrganizationCollection(makeRequest, data));
            },
            /**
             * Gets an Invitation in Organization
             * @returns Promise for a OrganizationInvitation in an organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((organization) => organization.getOrganizationInvitation('invitation_id'))
             * .then((invitation) => console.log(invitation))
             * .catch(console.error)
             * ```
             */
            getOrganizationInvitation(invitationId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OrganizationInvitation',
                    action: 'get',
                    params: {
                        organizationId: raw.sys.id,
                        invitationId,
                    },
                }).then((data) => wrapOrganizationInvitation(makeRequest, data));
            },
            /**
             * Create an Invitation in Organization
             * @returns Promise for a OrganizationInvitation in an organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             *  .then((organization) => organization.createOrganizationInvitation({
             *    email: 'user.email@example.com'
             *    firstName: 'User First Name'
             *    lastName: 'User Last Name'
             *    role: 'developer'
             *  })
             * .catch(console.error)
             * ```
             */
            createOrganizationInvitation(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OrganizationInvitation',
                    action: 'create',
                    params: {
                        organizationId: raw.sys.id,
                    },
                    payload: data,
                }).then((data) => wrapOrganizationInvitation(makeRequest, data));
            },
            /**
             * Gets a collection of Roles
             * @returns Promise for a collection of Roles
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getRoles())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getRoles(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Role',
                    action: 'getManyForOrganization',
                    params: { organizationId: raw.sys.id, query: createRequestConfig({ query }).params },
                }).then((data) => wrapRoleCollection(makeRequest, data));
            },
            /**
             * Creates an app definition
             * @param Object representation of the App Definition to be created
             * @returns Promise for the newly created AppDefinition
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.createAppDefinition({
             *    name: 'Example app',
             *    locations: [{ location: 'app-config' }],
             *    src: "http://my-app-host.com/my-app"
             *  }))
             * .then((appDefinition) => console.log(appDefinition))
             * .catch(console.error)
             * ```
             */
            createAppDefinition(data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'create',
                    params: { organizationId: raw.sys.id },
                    payload: data,
                }).then((data) => wrapAppDefinition(makeRequest, data));
            },
            /**
             * Gets all app definitions
             * @returns Promise for a collection of App Definitions
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinitions())
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getAppDefinitions(query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'getMany',
                    params: { organizationId: raw.sys.id, query: query },
                }).then((data) => wrapAppDefinitionCollection(makeRequest, data));
            },
            /**
             * Gets an app definition
             * @returns Promise for an App Definition
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDefinition('<app_definition_id>'))
             * .then((appDefinition) => console.log(appDefinition))
             * .catch(console.error)
             * ```
             */
            getAppDefinition(id) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId: id },
                }).then((data) => wrapAppDefinition(makeRequest, data));
            },
            /**
             * Gets an app upload
             * @returns Promise for an App Upload
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppUpload('<app_upload_id>'))
             * .then((appUpload) => console.log(appUpload))
             * .catch(console.error)
             * ```
             */
            getAppUpload(appUploadId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppUpload',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appUploadId },
                }).then((data) => wrapAppUpload(makeRequest, data));
            },
            /**
             * Creates an app upload
             * @returns Promise for an App Upload
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.createAppUpload('some_zip_file'))
             * .then((appUpload) => console.log(appUpload))
             * .catch(console.error)
             * ```
             */
            createAppUpload(file) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppUpload',
                    action: 'create',
                    params: { organizationId: raw.sys.id },
                    payload: { file },
                }).then((data) => wrapAppUpload(makeRequest, data));
            },
            /**
             * Creates or updates an app signing secret
             * @returns Promise for an App SigningSecret
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.upsertAppSigningSecret('app_definition_id', { value: 'tsren3s1....wn1e' }))
             * .then((appSigningSecret) => console.log(appSigningSecret))
             * .catch(console.error)
             * ```
             */
            upsertAppSigningSecret(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppSigningSecret',
                    action: 'upsert',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                    payload: data,
                }).then((payload) => wrapAppSigningSecret(makeRequest, payload));
            },
            /**
             * Gets an app signing secret
             * @returns Promise for an App SigningSecret
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppSigningSecret('app_definition_id'))
             * .then((appSigningSecret) => console.log(appSigningSecret))
             * .catch(console.error)
             * ```
             */
            getAppSigningSecret(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppSigningSecret',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then((payload) => wrapAppSigningSecret(makeRequest, payload));
            },
            /**
             * Deletes an app signing secret
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.deleteAppSigningSecret('app_definition_id'))
             * .then((result) => console.log(result))
             * .catch(console.error)
             * ```
             */
            deleteAppSigningSecret(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppSigningSecret',
                    action: 'delete',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then(() => {
                    /* noop*/
                });
            },
            /**
             * Creates or updates an app event subscription
             * @returns Promise for an App Event Subscription
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.upsertAppEventSubscription('app_definition_id', { targetUrl: '<target_url>', topics: ['<topic>'] }))
             * .then((appEventSubscription) => console.log(appEventSubscription))
             * .catch(console.error)
             * ```
             */
            upsertAppEventSubscription(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppEventSubscription',
                    action: 'upsert',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                    payload: data,
                }).then((payload) => wrapAppEventSubscription(makeRequest, payload));
            },
            /**
             * Gets an app event subscription
             * @returns Promise for an App Event Subscription
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppEventSubscription('app_definition_id'))
             * .then((appEventSubscription) => console.log(appEventSubscription))
             * .catch(console.error)
             * ```
             */
            getAppEventSubscription(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppEventSubscription',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then((payload) => wrapAppEventSubscription(makeRequest, payload));
            },
            /**
             * Deletes the current App Event Subscription for the given App
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.deleteAppEventSubscription('app_definition_id'))
             * .then((result) => console.log(result))
             * .catch(console.error)
             * ```
             */
            deleteAppEventSubscription(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppEventSubscription',
                    action: 'delete',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then(() => {
                    /* noop*/
                });
            },
            /**
             * Creates or updates an app event subscription
             * @returns Promise for an App Event Subscription
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // generate a new private key
             * client.getOrganization('<org_id>')
             * .then((org) => org.upsertAppEventSubscription('app_definition_id', { generate: true }))
             * .then((appEventSubscription) => console.log(appEventSubscription))
             * .catch(console.error)
             *
             * // or use an existing JSON Web Key
             * client.getOrganization('<org_id>')
             * .then((org) => org.upsertAppEventSubscription('app_definition_id', { jwk: 'jwk' }))
             * .then((appEventSubscription) => console.log(appEventSubscription))
             * .catch(console.error)
             * ```
             */
            createAppKey(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppKey',
                    action: 'create',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                    payload: data,
                }).then((payload) => wrapAppKey(makeRequest, payload));
            },
            /**
             * Gets an app key by fingerprint
             * @returns Promise for an App Key
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppKey('app_definition_id', 'fingerprint'))
             * .then((appKey) => console.log(appKey))
             * .catch(console.error)
             * ```
             */
            getAppKey(appDefinitionId, fingerprint) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppKey',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId, fingerprint },
                }).then((payload) => wrapAppKey(makeRequest, payload));
            },
            /**
             * Gets all keys for the given app
             * @returns Promise for an array of App Keys
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * // with default pagination
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppKeys('app_definition_id'))
             * .then((appKeys) => console.log(appKeys))
             * .catch(console.error)
             *
             * // with explicit pagination
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppKeys('app_definition_id', { skip: 'skip', limit: 'limit' }))
             * .then((appKeys) => console.log(appKeys))
             * .catch(console.error)
             * ```
             */
            getAppKeys(appDefinitionId, query = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppKey',
                    action: 'getMany',
                    params: {
                        organizationId: raw.sys.id,
                        appDefinitionId,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((payload) => wrapAppKeyCollection(makeRequest, payload));
            },
            /**
             * Deletes an app key by fingerprint.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.deleteAppKey('app_definition_id', 'fingerprint'))
             * .then((result) => console.log(result))
             * .catch(console.error)
             * ```
             */
            deleteAppKey(appDefinitionId, fingerprint) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppKey',
                    action: 'delete',
                    params: { organizationId: raw.sys.id, appDefinitionId, fingerprint },
                }).then(() => {
                    /* noop*/
                });
            },
            /**
             * Creates or updates an app details entity
             * @returns Promise for an App Details
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.upsertAppDetails('app_definition_id',
             *   { icon: { value: 'base_64_image', type: 'base64' }}
             *  ))
             * .then((appDetails) => console.log(appDetails))
             * .catch(console.error)
             * ```
             */
            upsertAppDetails(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDetails',
                    action: 'upsert',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                    payload: data,
                }).then((payload) => wrapAppDetails(makeRequest, payload));
            },
            /**
             * Gets an app details entity
             * @returns Promise for an App Details
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppDetails('app_definition_id'))
             * .then((appDetails) => console.log(appDetails))
             * .catch(console.error)
             * ```
             */
            getAppDetails(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDetails',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then((payload) => wrapAppDetails(makeRequest, payload));
            },
            /**
             * Deletes an app details entity.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.deleteAppDetails('app_definition_id'))
             * .then((result) => console.log(result))
             * .catch(console.error)
             * ```
             */
            deleteAppDetails(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppDetails',
                    action: 'delete',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then(() => {
                    /* noop*/
                });
            },
            /**
             * Creates an app action entity.
             * @returns Promise that resolves an App Action entity
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.createAppAction('app_definition_id', {
             *    type: 'endpoint',
             *    name: 'my nice new app action',
             *    url: 'https://www.somewhere.com/action'
             *  }))
             * .then((appAction) => console.log(appAction))
             * .catch(console.error)
             * ```
             */
            createAppAction(appDefinitionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAction',
                    action: 'create',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                    payload: data,
                }).then((payload) => wrapAppAction(makeRequest, payload));
            },
            /**
             * Updates an existing app action entity.
             * @returns Promise that resolves an App Action entity
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.updateAppAction('app_definition_id', 'app_action_id', {
             *    type: 'endpoint',
             *    name: 'my nice updated app action',
             *    url: 'https://www.somewhere-else.com/action'
             *  }))
             * .then((appAction) => console.log(appAction))
             * .catch(console.error)
             * ```
             */
            updateAppAction(appDefinitionId, appActionId, data) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAction',
                    action: 'update',
                    params: { organizationId: raw.sys.id, appDefinitionId, appActionId },
                    payload: data,
                }).then((payload) => wrapAppAction(makeRequest, payload));
            },
            /**
             * Deletes an app action entity.
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.deleteAppAction('app_definition_id', 'app_action_id'))
             * .then((result) => console.log(result))
             * .catch(console.error)
             * ```
             */
            deleteAppAction(appDefinitionId, appActionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAction',
                    action: 'delete',
                    params: { organizationId: raw.sys.id, appDefinitionId, appActionId },
                }).then(() => {
                    /* noop*/
                });
            },
            /**
             * Gets an existing app action entity.
             * @returns Promise that resolves an App Action entity
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppAction('app_definition_id', 'app_action_id'))
             * .then((appAction) => console.log(appAction))
             * .catch(console.error)
             * ```
             */
            getAppAction(appDefinitionId, appActionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAction',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId, appActionId },
                }).then((payload) => wrapAppAction(makeRequest, payload));
            },
            /**
             * Gets existing app actions for an App Definition.
             * @returns Promise that resolves an App Action entity
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => org.getAppActions('app_definition_id'))
             * .then((appActions) => console.log(appActions))
             * .catch(console.error)
             * ```
             */
            getAppActions(appDefinitionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'AppAction',
                    action: 'getMany',
                    params: { organizationId: raw.sys.id, appDefinitionId },
                }).then((payload) => wrapAppActionCollection(makeRequest, payload));
            },
            /**
             * Gets an app function
             * @param appDefinitionId
             * @param functionId
             * @returns Promise for a Function
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * const functions = await org.getFunction('<app_definition_id>', '<function_id>')
             */
            getFunction(appDefinitionId, functionId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Function',
                    action: 'get',
                    params: { organizationId: raw.sys.id, appDefinitionId, functionId },
                }).then((payload) => wrapFunction(makeRequest, payload));
            },
            /**
             * Gets a collection of app functions.
             * @param appDefinitionId
             * @param {import('../common-types').AcceptsQueryOptions} query  - optional query parameter for filtering functions by action
             * @returns Promise for a Function
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * const functions = await org.getFunctions('<app_definition_id>', { 'accepts[all]': '<action>' })
             */
            getFunctions(appDefinitionId, query) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'Function',
                    action: 'getMany',
                    params: { organizationId: raw.sys.id, appDefinitionId, query },
                }).then((payload) => wrapFunctionCollection(makeRequest, payload));
            },
            /**
             * Gets the semantic settings for the organization
             * @return Promise for ContentSemanticsSettings
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * const settings = await org.getSemanticSettings()
             */
            getSemanticSettings() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'SemanticSettings',
                    action: 'get',
                    params: { organizationId: raw.sys.id },
                }).then((data) => wrapContentSemanticsSettings(makeRequest, data));
            },
            /**
             * Gets all content semantics indexes for the organization
             * @return Promise for a collection of ContentSemanticsIndex
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * const indexes = await org.getContentSemanticsIndexes()
             */
            getContentSemanticsIndexes() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentSemanticsIndex',
                    action: 'getMany',
                    params: { organizationId: raw.sys.id },
                }).then((data) => wrapContentSemanticsIndexCollection(makeRequest, data));
            },
            /**
             * Gets a single content semantics index by ID
             * @param indexId - ID of the content semantics index
             * @return Promise for a ContentSemanticsIndex
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * const index = await org.getContentSemanticsIndex('<index_id>')
             */
            getContentSemanticsIndex(indexId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentSemanticsIndex',
                    action: 'get',
                    params: { organizationId: raw.sys.id, indexId },
                }).then((data) => wrapContentSemanticsIndex(makeRequest, data));
            },
            /**
             * Creates a new content semantics index for the organization
             * @param payload - Object containing spaceId and locale
             * @return Promise for the created ContentSemanticsIndex
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * const index = await org.createContentSemanticsIndex({ spaceId: '<space_id>', locale: 'en-US' })
             */
            createContentSemanticsIndex(payload) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentSemanticsIndex',
                    action: 'create',
                    params: { organizationId: raw.sys.id },
                    payload,
                }).then((data) => wrapContentSemanticsIndex(makeRequest, data));
            },
            /**
             * Deletes a content semantics index by ID
             * @param indexId - ID of the content semantics index to delete
             * @return Promise for the deletion
             * @example ```javascript
             * const contentful = require('contentful-management')
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * const org = await client.getOrganization('<org_id>')
             * await org.deleteContentSemanticsIndex('<index_id>')
             */
            deleteContentSemanticsIndex(indexId) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'ContentSemanticsIndex',
                    action: 'delete',
                    params: { organizationId: raw.sys.id, indexId },
                });
            },
        };
    }

    /**
     * This method creates the API for the given organization with all the methods for
     * reading and creating other entities. It also passes down a clone of the
     * http client with an organization id, so the base path for requests now has the
     * organization id already set.
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - API response for an Organization
     * @returns {Organization}
     */
    function wrapOrganization(makeRequest, data) {
        const org = toPlainObject(index$2(data));
        const orgApi = createOrganizationApi(makeRequest);
        const enhancedOrganization = enhanceWithMethods(org, orgApi);
        return freezeSys(enhancedOrganization);
    }
    /**
     * This method normalizes each organization in a collection.
     * @internal
     */
    const wrapOrganizationCollection = wrapCollection(wrapOrganization);

    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw data
     * @returns Normalized usage
     * @deprecated Use {@link wrapAggregatedUsage} / `usage.getAggregated()` instead. Sunset: 2027-02-28.
     */
    function wrapUsage(_makeRequest, data) {
        const usage = toPlainObject(index$2(data));
        const usageWithMethods = enhanceWithMethods(usage, {});
        return freezeSys(usageWithMethods);
    }
    /** @internal @deprecated */
    const wrapUsageCollection = wrapCollection(wrapUsage);
    /** @internal */
    function wrapAggregatedUsage(_makeRequest, data) {
        const item = toPlainObject(index$2(data));
        return freezeSys(enhanceWithMethods(item, {}));
    }
    /** @internal */
    const wrapAggregatedUsageCollection = wrapCollection(wrapAggregatedUsage);
    /** @internal */
    function wrapAssetBandwidthUsage(_makeRequest, data) {
        const item = toPlainObject(index$2(data));
        return freezeSys(enhanceWithMethods(item, {}));
    }
    /** @internal */
    function wrapAssetBandwidthUsageDetailedCollection(makeRequest, data) {
        const collectionData = toPlainObject(index$2(data));
        collectionData.items = collectionData.items.map((item) => wrapAssetBandwidthUsage(makeRequest, item));
        // @ts-expect-error items is reassigned above from AssetBandwidthUsageItemProps[] to AssetBandwidthUsage[]
        return collectionData;
    }

    /**
     * @internal
     */
    function createEnvironmentTemplateApi(makeRequest, organizationId) {
        return {
            /**
             * Updates a environment template
             * @returns Promise for new version of the template
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then((environmentTemplate) => {
             *   environmentTemplate.name = 'New name'
             *   return environmentTemplate.update()
             * })
             * .then((environmentTemplate) =>
             *   console.log(`Environment template ${environmentTemplate.sys.id} renamed.`)
             * ).catch(console.error)
             * ```
             */
            update: function updateEnvironmentTemplate() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'update',
                    params: { organizationId, environmentTemplateId: raw.sys.id },
                    payload: raw,
                }).then((data) => wrapEnvironmentTemplate(makeRequest, data, organizationId));
            },
            /**
             * Updates environment template version data
             * @param version.versionName - Name of the environment template version
             * @param version.versionDescription - Description of the environment template version
             * @returns Promise for an updated EnvironmentTemplate
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then((environmentTemplate) => {
             *   return environmentTemplate.updateVersion({
             *     versionName: 'New Name',
             *     versionDescription: 'New Description',
             *   })
             * })
             * .then((environmentTemplate) =>
             *   console.log(`Environment template version ${environmentTemplate.sys.id} renamed.`)
             * ).catch(console.error)
             * ```
             */
            updateVersion: function updateEnvironmentTemplateVersion({ versionName, versionDescription, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'versionUpdate',
                    params: { organizationId, environmentTemplateId: raw.sys.id, version: raw.sys.version },
                    payload: { versionName, versionDescription },
                }).then((data) => wrapEnvironmentTemplate(makeRequest, data, organizationId));
            },
            /**
             * Deletes the environment template
             * @returns Promise for the deletion. It contains no data, but the Promise error case should be handled.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             *   .then((environmentTemplate) => environmentTemplate.delete())
             *   .then(() => console.log('Environment template deleted.'))
             *   .catch(console.error)
             * ```
             */
            delete: function deleteEnvironmentTemplate() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'delete',
                    params: { organizationId, environmentTemplateId: raw.sys.id },
                });
            },
            /**
             * Gets a collection of all versions for the environment template
             * @returns Promise for a EnvironmentTemplate
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then((environmentTemplate) => environmentTemplate.getVersions())
             * .then((environmentTemplateVersions) => console.log(environmentTemplateVersions.items))
             * .catch(console.error)
             * ```
             */
            getVersions: function getEnvironmentTemplateVersions() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'versions',
                    params: {
                        organizationId,
                        environmentTemplateId: raw.sys.id,
                    },
                }).then((data) => wrapEnvironmentTemplateCollection(makeRequest, data, organizationId));
            },
            /**
             * Gets a collection of all installations for the environment template
             * @param [installationParams.spaceId] - Space ID to filter installations by space and environment
             * @param [installationParams.environmentId] - Environment ID to filter installations by space and environment
             * @param [installationParams.latestOnly] - Boolean flag to only return the latest installation per environment
             * @returns Promise for a collection of EnvironmentTemplateInstallations
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then((environmentTemplate) => environmentTemplate.getInstallations())
             * .then((environmentTemplateInstallations) =>
             *   console.log(environmentTemplateInstallations.items)
             * )
             * .catch(console.error)
             * ```
             */
            getInstallations: function getEnvironmentTemplateInstallations({ spaceId, environmentId, latestOnly, ...query } = {}) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplateInstallation',
                    action: 'getMany',
                    params: {
                        organizationId,
                        environmentTemplateId: raw.sys.id,
                        query: { ...createRequestConfig({ query }).params },
                        spaceId,
                        environmentId,
                        latestOnly,
                    },
                }).then((data) => wrapEnvironmentTemplateInstallationCollection(makeRequest, data));
            },
            /**
             * Validates an environment template against a given space and environment
             * @param params.spaceId - Space ID where the template should be installed into
             * @param params.environmentId - Environment ID where the template should be installed into
             * @param [params.version] - Version of the template
             * @param [params.installation.takeover] - Already existing Content types to takeover in the target environment
             * @param [params.changeSet] - Change set which should be applied
             * @returns Promise for a EnvironmentTemplateValidation
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then((environmentTemplate) => environmentTemplate.validate({
             *   spaceId: '<space_id>',
             *   environmentId: '<environment_id>',
             *   version: <version>,
             * }))
             * .then((validationResult) => console.log(validationResult))
             * .catch(console.error)
             * ```
             */
            validate: function validateEnvironmentTemplate({ spaceId, environmentId, version, takeover, changeSet, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'validate',
                    params: {
                        spaceId,
                        version,
                        environmentId,
                        environmentTemplateId: raw.sys.id,
                    },
                    payload: {
                        ...(takeover && { takeover }),
                        ...(changeSet && { changeSet }),
                    },
                });
            },
            /**
             * Installs a template against a given space and environment
             * @param params.spaceId - Space ID where the template should be installed into
             * @param params.environmentId - Environment ID where the template should be installed into
             * @param params.installation.version- Template version which should be installed
             * @param [params.installation.takeover] - Already existing Content types tp takeover in the target environment
             * @param [params.changeSet] - Change set which should be applied
             * @returns Promise for a EnvironmentTemplateInstallation
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then((environmentTemplate) => environmentTemplate.validate({
             *   spaceId: '<space_id>',
             *   environmentId: '<environment_id>',
             *   installation: {
             *     version: <version>,
             *   }
             * }))
             * .then((installation) => console.log(installation))
             * .catch(console.error)
             * ```
             */
            install: function installEnvironmentTemplate({ spaceId, environmentId, installation, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'install',
                    params: {
                        spaceId,
                        environmentId,
                        environmentTemplateId: raw.sys.id,
                    },
                    payload: installation,
                });
            },
            /**
             * Disconnects the template from a given environment
             * @param params.spaceId - Space ID where the template should be installed into
             * @param params.environmentId - Environment ID where the template should be installed into
             * @returns Promise for the disconnection with no data
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate('<organization_id>', '<environment_template_id>')
             * .then(environmentTemplate) => environmentTemplate.disconnected())
             * .then(() => console.log('Template disconnected'))
             * .catch(console.error)
             * ```
             */
            disconnect: function disconnectEnvironmentTemplate({ spaceId, environmentId, }) {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'disconnect',
                    params: {
                        spaceId,
                        environmentId,
                        environmentTemplateId: raw.sys.id,
                    },
                });
            },
        };
    }

    function wrapEnvironmentTemplate(makeRequest, data, organizationId) {
        const environmentTemplate = toPlainObject(index$2(data));
        const environmentTemplateApi = createEnvironmentTemplateApi(makeRequest, organizationId);
        const enhancedEnvironmentTemplate = enhanceWithMethods(environmentTemplate, environmentTemplateApi);
        return freezeSys(enhancedEnvironmentTemplate);
    }
    const wrapEnvironmentTemplateCollection = wrapCursorPaginatedCollection(wrapEnvironmentTemplate);

    var ScopeValues;
    (function (ScopeValues) {
        ScopeValues["Read"] = "content_management_read";
        ScopeValues["Manage"] = "content_management_manage";
    })(ScopeValues || (ScopeValues = {}));
    /**
     * @internal
     */
    function createOAuthApplicationApi(makeRequest, userId) {
        const getParams = (data) => ({
            userId,
            oauthApplicationId: data.sys.id,
        });
        return {
            /**
             * Updates an OAuth application
             * @returns Promise for the updated OAuth application
             */
            async update() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OAuthApplication',
                    action: 'update',
                    params: getParams(raw),
                    payload: raw,
                });
            },
            /**
             * Deletes an OAuth application
             * @returns Promise for the deleted OAuth application
             */
            async delete() {
                const raw = this.toPlainObject();
                return makeRequest({
                    entityType: 'OAuthApplication',
                    action: 'delete',
                    params: getParams(raw),
                });
            },
        };
    }
    /**
     * @internal
     * @param makeRequest - function to make requests via an adapter
     * @param data - Raw OAuth application data
     * @returns Wrapped OAuth application data
     */
    function wrapOAuthApplication(makeRequest, data, userId) {
        const oauthApplication = toPlainObject(index$2(data));
        const oauthApplicationWithMethods = enhanceWithMethods(oauthApplication, createOAuthApplicationApi(makeRequest, userId));
        return freezeSys(oauthApplicationWithMethods);
    }
    /**
     * @internal
     */
    const wrapOAuthApplicationCollection = wrapCursorPaginatedCollection(wrapOAuthApplication);

    /**
     * @internal
     */
    function createClientApi(makeRequest) {
        return {
            /**
             * Gets all environment templates for a given organization with the lasted version
             * @param organizationId - Organization ID
             * @returns Promise for a collection of EnvironmentTemplates
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplates('<organization_id>')
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getEnvironmentTemplates: function getEnvironmentTemplates(organizationId, query = {}) {
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'getMany',
                    params: { organizationId, query: createRequestConfig({ query }).params },
                }).then((data) => wrapEnvironmentTemplateCollection(makeRequest, data, organizationId));
            },
            /**
             * Gets the lasted version environment template if params.version is not specified
             * @param params.organizationId - Organization ID
             * @param params.environmentTemplateId - Environment template ID
             * @param [params.version] - Template version number to return a specific version of the environment template
             * @returns Promise for a EnvironmentTemplate
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getEnvironmentTemplate({
             *   organizationId: '<organization_id>',
             *   environmentTemplateId: '<environment_template_id>',
             *   version: version>
             * })
             * .then((space) => console.log(space))
             * .catch(console.error)
             * ```
             */
            getEnvironmentTemplate: function getEnvironmentTemplate({ organizationId, environmentTemplateId, version, query = {}, }) {
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'get',
                    params: {
                        organizationId,
                        environmentTemplateId,
                        version,
                        query: createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapEnvironmentTemplate(makeRequest, data, organizationId));
            },
            /**
             * Creates an environment template
             * @param organizationId - Organization ID
             * @param environmentTemplateData - Object representation of the environment template to be created
             * @returns Promise for the newly created EnvironmentTemplate
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.createEnvironmentTemplate('<organization_id>', {<environment_template_date>})
             * .then((environmentTemplate) => console.log(environmentTemplate))
             * .catch(console.error)
             * ```
             */
            createEnvironmentTemplate: function createEnvironmentTemplate(organizationId, environmentTemplateData) {
                return makeRequest({
                    entityType: 'EnvironmentTemplate',
                    action: 'create',
                    params: { organizationId },
                    payload: environmentTemplateData,
                }).then((data) => wrapEnvironmentTemplate(makeRequest, data, organizationId));
            },
            /**
             * Gets all spaces
             * @returns Promise for a collection of Spaces
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpaces()
             * .then((response) => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getSpaces: function getSpaces(query = {}, organizationId) {
                const { cursor, include, ...rest } = query;
                const normalizedQuery = cursor
                    ? normalizeCursorPaginationParameters(rest)
                    : rest;
                return makeRequest({
                    entityType: 'Space',
                    action: 'getMany',
                    params: {
                        query: createRequestConfig({ query: normalizedQuery }).params,
                        organizationId,
                        include,
                    },
                }).then((data) => 
                // makeRequest returns the union type; cursor determines which branch is present at runtime so the casts are required
                cursor
                    ? wrapSpaceCursorPaginatedCollection(makeRequest, normalizeCursorPaginationResponse(data))
                    : wrapSpaceCollection(makeRequest, data));
            },
            /**
             * Gets a space
             * @param spaceId - Space ID
             * @returns Promise for a Space
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpace('<space_id>')
             * .then((space) => console.log(space))
             * .catch(console.error)
             * ```
             */
            getSpace: function getSpace(spaceId, { include } = {}) {
                return makeRequest({
                    entityType: 'Space',
                    action: 'get',
                    params: { spaceId, include },
                }).then((data) => wrapSpace(makeRequest, data));
            },
            /**
             * Creates a space
             * @param spaceData - Object representation of the Space to be created
             * @param organizationId - Organization ID, if the associated token can manage more than one organization.
             * @returns Promise for the newly created Space
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.createSpace({
             *   name: 'Name of new space'
             * })
             * .then((space) => console.log(space))
             * .catch(console.error)
             * ```
             */
            createSpace: function createSpace(spaceData, organizationId) {
                return makeRequest({
                    entityType: 'Space',
                    action: 'create',
                    params: { organizationId },
                    payload: spaceData,
                }).then((data) => wrapSpace(makeRequest, data));
            },
            /**
             * Gets an organization
             * @param  id - Organization ID
             * @returns Promise for a Organization
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganization('<org_id>')
             * .then((org) => console.log(org))
             * .catch(console.error)
             * ```
             */
            getOrganization: function getOrganization(id) {
                return makeRequest({
                    entityType: 'Organization',
                    action: 'get',
                    params: { organizationId: id },
                }).then((data) => wrapOrganization(makeRequest, data));
            },
            /**
             * Gets a collection of Organizations
             * @returns Promise for a collection of Organizations
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganizations()
             * .then(result => console.log(result.items))
             * .catch(console.error)
             * ```
             */
            getOrganizations: function getOrganizations(query = {}) {
                return makeRequest({
                    entityType: 'Organization',
                    action: 'getMany',
                    params: { query: createRequestConfig({ query }).params },
                }).then((data) => wrapOrganizationCollection(makeRequest, data));
            },
            /**
             * Gets the authenticated user
             * @returns Promise for a User
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getCurrentUser()
             * .then(user => console.log(user.firstName))
             * .catch(console.error)
             * ```
             */
            getCurrentUser: function getCurrentUser(params) {
                return makeRequest({
                    entityType: 'User',
                    action: 'getCurrent',
                    params,
                }).then((data) => wrapUser(makeRequest, data));
            },
            /**
             *
             * @param params
             * @returns Promise of a OAuthApplication
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *  accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOAuthApplication({
             * userId: '<user_id>'
             * oauthApplicationId: '<oauth_application_id>'
             * }).then(oauthApplication => console.log(oauthApplication))
             * .catch(console.error)
             */
            getOAuthApplication: function getOAuthApplication(params) {
                const { userId } = params;
                return makeRequest({
                    entityType: 'OAuthApplication',
                    action: 'get',
                    params,
                }).then((data) => wrapOAuthApplication(makeRequest, data, userId));
            },
            /**
             *
             * @param params
             * @returns Promise of list of user's OAuthApplications
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *  accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOAuthApplications({
             * userId: '<user_id>'}).then(oauthApplications => console.log(oauthApplications))
             * .catch(console.error)
             */
            getOAuthApplications: function getOAuthApplications(params) {
                const { userId } = params;
                return makeRequest({
                    entityType: 'OAuthApplication',
                    action: 'getManyForUser',
                    params,
                }).then((data) => wrapOAuthApplicationCollection(makeRequest, data, userId));
            },
            /**
             *
             * @param params
             * @returns Promise of a new OAuth application.
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *  accessToken: '<content_management_api_key>'
             * })
             *
             * client.createOAuthApplication({
             * userId: '<user_id>'},
             * { name: '<name>',
             *   description: '<description>',
             *   scopes: ['scope'],
             *   redirectUri: '<redirectUri>',
             *   confidential: '<true/false>'}).then(oauthApplications => console.log(oauthApplications))
             * .catch(console.error)
             */
            createOAuthApplication: function createOAuthApplication(params, rawData) {
                const { userId } = params;
                return makeRequest({
                    entityType: 'OAuthApplication',
                    action: 'create',
                    params,
                    payload: rawData,
                }).then((data) => wrapOAuthApplication(makeRequest, data, userId));
            },
            /**
             * Gets App Definition
             * @returns Promise for App Definition
             * @param organizationId - Id of the organization where the app is installed
             * @param appDefinitionId - Id of the app that will be returned
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getAppDefinition(<'org_id'>, <'app_id'>)
             * .then(appDefinition => console.log(appDefinition.name))
             * .catch(console.error)
             * ```
             */
            getAppDefinition: function getAppDefinition(params) {
                return makeRequest({
                    entityType: 'AppDefinition',
                    action: 'get',
                    params,
                }).then((data) => wrapAppDefinition(makeRequest, data));
            },
            /**
             * Creates a personal access token
             * @param data - personal access token config
             * @returns Promise for a Token
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.createPersonalAccessToken(
             *  {
             *    "name": "My Token",
             *    "scope": [
             *      "content_management_manage"
             *    ]
             *  }
             * )
             * .then(personalAccessToken => console.log(personalAccessToken.token))
             * .catch(console.error)
             * ```
             */
            createPersonalAccessToken: function createPersonalAccessToken(data) {
                return makeRequest({
                    /**
                     * When the `PersonalAccessToken` entity is removed, replace the `entityType` with `AccessToken`
                     * and update the action to `createPersonalToken` to ultilize the new entity called AccessToken.
                     */
                    entityType: 'PersonalAccessToken',
                    action: 'create',
                    params: {},
                    payload: data,
                }).then((response) => wrapPersonalAccessToken(makeRequest, response));
            },
            /**
             * @deprecated - use getAccessToken instead
             *
             * Gets a personal access token
             * @param data - personal access token config
             * @returns Promise for a Token
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getPersonalAccessToken(tokenId)
             * .then(token => console.log(token.token))
             * .catch(console.error)
             * ```
             */
            getPersonalAccessToken: function getPersonalAccessToken(tokenId) {
                return makeRequest({
                    entityType: 'PersonalAccessToken',
                    action: 'get',
                    params: { tokenId },
                }).then((data) => wrapPersonalAccessToken(makeRequest, data));
            },
            /**
             * @deprecated - use getAccessTokens instead
             *
             * Gets all personal access tokens
             * @returns Promise for a Token
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getPersonalAccessTokens()
             * .then(response => console.log(response.items))
             * .catch(console.error)
             * ```
             */
            getPersonalAccessTokens: function getPersonalAccessTokens() {
                return makeRequest({
                    entityType: 'PersonalAccessToken',
                    action: 'getMany',
                    params: {},
                }).then((data) => wrapPersonalAccessTokenCollection(makeRequest, data));
            },
            /**
             * Gets a users access token
             * @param data - users access token config
             * @returns Promise for a Token
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getAccessToken(tokenId)
             * .then(token => console.log(token.token))
             * .catch(console.error)
             * ```
             */
            getAccessToken: function getAccessToken(tokenId) {
                return makeRequest({
                    entityType: 'AccessToken',
                    action: 'get',
                    params: { tokenId },
                }).then((data) => wrapAccessToken(makeRequest, data));
            },
            /**
             * Gets all user access tokens
             * @returns Promise for a Token
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getAccessTokens()
             * .then(response => console.log(reponse.items))
             * .catch(console.error)
             * ```
             */
            getAccessTokens: function getAccessTokens() {
                return makeRequest({
                    entityType: 'AccessToken',
                    action: 'getMany',
                    params: {},
                }).then((data) => wrapAccessTokenCollection(makeRequest, data));
            },
            /**
             * Retrieves a list of redacted versions of access tokens for an organization, accessible to owners or administrators of an organization.
             *
             * @returns Promise for a Token
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganizationAccessTokens(organizationId)
             * .then(response => console.log(reponse.items))
             * .catch(console.error)
             * ```
             */
            getOrganizationAccessTokens: function getOrganizationAccessTokens(organizationId, query = {}) {
                return makeRequest({
                    entityType: 'AccessToken',
                    action: 'getManyForOrganization',
                    params: { organizationId, query },
                }).then((data) => wrapAccessTokenCollection(makeRequest, data));
            },
            /**
             * Get organization usage grouped by {@link UsageMetricEnum metric}
             *
             * @param organizationId - Id of an organization
             * @param query - Query parameters
             * @returns Promise of a collection of usages
             * @deprecated Use {@link getUsageAggregated} instead, calling it once per metric key
             * (this method accepted multiple metrics per call via `metric[in]`; {@link getUsageAggregated}
             * is scoped to a single `metricKey` per request). Sunset: 2027-02-28.
             * @example ```javascript
             *
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getOrganizationUsage('<organizationId>', {
             *    'metric[in]': 'cma,gql',
             *    'dateRange.startAt': '2019-10-22',
             *    'dateRange.endAt': '2019-11-10'
             *    }
             * })
             * .then(result => console.log(result.items))
             * .catch(console.error)
             * ```
             */
            getOrganizationUsage: function getOrganizationUsage(organizationId, query = {}) {
                return makeRequest({
                    entityType: 'Usage',
                    action: 'getManyForOrganization',
                    params: { organizationId, query },
                }).then((data) => wrapUsageCollection(makeRequest, data));
            },
            /**
             * Get organization usage grouped by space and metric
             *
             * @param organizationId - Id of an organization
             * @param query - Query parameters
             * @returns Promise of a collection of usages
             * @deprecated Use {@link getUsageAggregated} instead, calling it once per metric key and
             * filtering by `filter[sys.dimensions.space.sys.id]` to scope to a space. Sunset: 2027-02-28.
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getSpaceUsage('<organizationId>', {
             *    skip: 0,
             *    limit: 10,
             *    'metric[in]': 'cda,cpa,gql',
             *    'dateRange.startAt': '2019-10-22',
             *    'dateRange.endAt': '2020-11-30'
             *    }
             * })
             * .then(result => console.log(result.items))
             * .catch(console.error)
             * ```
             */
            getSpaceUsage: function getSpaceUsage(organizationId, query = {}) {
                return makeRequest({
                    entityType: 'Usage',
                    action: 'getManyForSpace',
                    params: {
                        organizationId,
                        query,
                    },
                }).then((data) => wrapUsageCollection(makeRequest, data));
            },
            /**
             * Get aggregated usage for an organization metric.
             *
             * @param organizationId - Id of the organization
             * @param metricKey - Key of the metric, e.g. `"functions_invocations"`, `"asset_bandwidth"`, `"api_call_cma"`, `"api_call_cpa"`, `"api_call_cda"`, `"api_call_graphql"`, `"ai_action_invocation"`, `"ai_action_word_count"`, `"ai_consumption_unit"`, `"monthly_active_profiles"`
             * @param query - Query parameters (date range, granularity, grouping, pagination)
             * @returns Promise of an aggregated usage collection
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getUsageAggregated('<organizationId>', 'functions_invocations', {
             *   'date[gte]': '2025-01-01',
             *   'date[lte]': '2025-01-31',
             *   granularity: 'P1D',
             * })
             * .then(result => console.log(result.items))
             * .catch(console.error)
             * ```
             */
            getUsageAggregated: function getUsageAggregated(organizationId, metricKey, query) {
                return makeRequest({
                    entityType: 'Usage',
                    action: 'getAggregated',
                    params: { organizationId, metricKey, query },
                }).then((data) => wrapAggregatedUsageCollection(makeRequest, data));
            },
            /**
             * Get detailed asset-bandwidth usage for an organization.
             *
             * @param organizationId - Id of the organization
             * @param query - Query parameters (date range only)
             * @returns Promise of a detailed asset-bandwidth usage collection
             * @example ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.getUsageAssetBandwidthDetailed('<organizationId>', {
             *   'date[gte]': '2025-01-01',
             *   'date[lte]': '2025-01-31',
             * })
             * .then(result => console.log(result.items))
             * .catch(console.error)
             * ```
             */
            getUsageAssetBandwidthDetailed: function getUsageAssetBandwidthDetailed(organizationId, query) {
                return makeRequest({
                    entityType: 'Usage',
                    action: 'getAssetBandwidthUsageDetailed',
                    params: { organizationId, query },
                }).then((data) => wrapAssetBandwidthUsageDetailedCollection(makeRequest, data));
            },
            /**
             * Make a custom request to the Contentful management API's /spaces endpoint
             * @param opts - axios request options (https://github.com/mzabriskie/axios)
             * @returns Promise for the response data
             * ```javascript
             * const contentful = require('contentful-management')
             *
             * const client = contentful.createClient({
             *   accessToken: '<content_management_api_key>'
             * })
             *
             * client.rawRequest({
             *   method: 'GET',
             *   url: '/custom/path'
             * })
             * .then((responseData) => console.log(responseData))
             * .catch(console.error)
             * ```
             */
            rawRequest: function rawRequest({ url, ...config }) {
                return makeRequest({
                    entityType: 'Http',
                    action: 'request',
                    params: { url, config },
                });
            },
        };
    }

    /**
     * @internal
     */
    const wrap = ({ makeRequest, defaults }, entityType, action) => {
        // @ts-expect-error It's not really possible to make this type safe as we are overloading `makeRequest`. This missing typesafety is only within `wrap`. `wrap` has proper public types.
        return (params, payload, headers) => 
        // @ts-expect-error see above
        makeRequest({
            entityType,
            action,
            params: { ...defaults, ...params },
            payload,
            // Required after adding optional headers to a delete method for the first time
            headers,
        });
    };

    /**
     * @internal
     */
    const createPlainClient = (makeRequest, defaults) => {
        const wrapParams = { makeRequest, defaults };
        return {
            raw: {
                getDefaultParams: () => defaults,
                get: (url, config) => makeRequest({
                    entityType: 'Http',
                    action: 'get',
                    params: { url, config },
                }),
                patch: (url, payload, config) => makeRequest({
                    entityType: 'Http',
                    action: 'patch',
                    params: { url, config },
                    payload,
                }),
                post: (url, payload, config) => makeRequest({
                    entityType: 'Http',
                    action: 'post',
                    params: { url, config },
                    payload,
                }),
                put: (url, payload, config) => makeRequest({
                    entityType: 'Http',
                    action: 'put',
                    params: { url, config },
                    payload,
                }),
                delete: (url, config) => makeRequest({
                    entityType: 'Http',
                    action: 'delete',
                    params: { url, config },
                }),
                http: (url, config) => makeRequest({
                    entityType: 'Http',
                    action: 'request',
                    params: { url, config },
                }),
            },
            aiAction: {
                get: wrap(wrapParams, 'AiAction', 'get'),
                getMany: wrap(wrapParams, 'AiAction', 'getMany'),
                create: wrap(wrapParams, 'AiAction', 'create'),
                update: wrap(wrapParams, 'AiAction', 'update'),
                delete: wrap(wrapParams, 'AiAction', 'delete'),
                publish: wrap(wrapParams, 'AiAction', 'publish'),
                unpublish: wrap(wrapParams, 'AiAction', 'unpublish'),
                invoke: wrap(wrapParams, 'AiAction', 'invoke'),
            },
            aiActionInvocation: {
                get: wrap(wrapParams, 'AiActionInvocation', 'get'),
            },
            agent: {
                get: wrap(wrapParams, 'Agent', 'get'),
                getMany: wrap(wrapParams, 'Agent', 'getMany'),
                generate: wrap(wrapParams, 'Agent', 'generate'),
            },
            agentRun: {
                get: wrap(wrapParams, 'AgentRun', 'get'),
                getMany: wrap(wrapParams, 'AgentRun', 'getMany'),
                resumeRun: wrap(wrapParams, 'AgentRun', 'resumeRun'),
            },
            automationDefinition: {
                get: wrap(wrapParams, 'AutomationDefinition', 'get'),
                getMany: wrap(wrapParams, 'AutomationDefinition', 'getMany'),
                create: wrap(wrapParams, 'AutomationDefinition', 'create'),
                update: wrap(wrapParams, 'AutomationDefinition', 'update'),
                delete: wrap(wrapParams, 'AutomationDefinition', 'delete'),
            },
            automationExecution: {
                get: wrap(wrapParams, 'AutomationExecution', 'get'),
                getMany: wrap(wrapParams, 'AutomationExecution', 'getMany'),
                getForAutomationDefinition: wrap(wrapParams, 'AutomationExecution', 'getForAutomationDefinition'),
            },
            appAction: {
                get: wrap(wrapParams, 'AppAction', 'get'),
                getMany: wrap(wrapParams, 'AppAction', 'getMany'),
                getManyForEnvironment: wrap(wrapParams, 'AppAction', 'getManyForEnvironment'),
                delete: wrap(wrapParams, 'AppAction', 'delete'),
                create: wrap(wrapParams, 'AppAction', 'create'),
                update: wrap(wrapParams, 'AppAction', 'update'),
            },
            appActionCall: {
                create: wrap(wrapParams, 'AppActionCall', 'create'),
                getCallDetails: wrap(wrapParams, 'AppActionCall', 'getCallDetails'),
                createWithResponse: wrap(wrapParams, 'AppActionCall', 'createWithResponse'),
                get: wrap(wrapParams, 'AppActionCall', 'get'),
                createWithResult: wrap(wrapParams, 'AppActionCall', 'createWithResult'),
                getResponse: wrap(wrapParams, 'AppActionCall', 'getResponse'),
            },
            appBundle: {
                get: wrap(wrapParams, 'AppBundle', 'get'),
                getMany: wrap(wrapParams, 'AppBundle', 'getMany'),
                delete: wrap(wrapParams, 'AppBundle', 'delete'),
                create: wrap(wrapParams, 'AppBundle', 'create'),
            },
            appDetails: {
                upsert: wrap(wrapParams, 'AppDetails', 'upsert'),
                get: wrap(wrapParams, 'AppDetails', 'get'),
                delete: wrap(wrapParams, 'AppDetails', 'delete'),
            },
            appEventSubscription: {
                upsert: wrap(wrapParams, 'AppEventSubscription', 'upsert'),
                get: wrap(wrapParams, 'AppEventSubscription', 'get'),
                delete: wrap(wrapParams, 'AppEventSubscription', 'delete'),
            },
            appKey: {
                create: wrap(wrapParams, 'AppKey', 'create'),
                get: wrap(wrapParams, 'AppKey', 'get'),
                getMany: wrap(wrapParams, 'AppKey', 'getMany'),
                delete: wrap(wrapParams, 'AppKey', 'delete'),
            },
            appSignedRequest: {
                create: wrap(wrapParams, 'AppSignedRequest', 'create'),
            },
            appSigningSecret: {
                upsert: wrap(wrapParams, 'AppSigningSecret', 'upsert'),
                get: wrap(wrapParams, 'AppSigningSecret', 'get'),
                delete: wrap(wrapParams, 'AppSigningSecret', 'delete'),
            },
            appAccessToken: {
                create: wrap(wrapParams, 'AppAccessToken', 'create'),
            },
            concept: {
                create: wrap(wrapParams, 'Concept', 'create'),
                createWithId: wrap(wrapParams, 'Concept', 'createWithId'),
                get: wrap(wrapParams, 'Concept', 'get'),
                delete: wrap(wrapParams, 'Concept', 'delete'),
                patch: wrap(wrapParams, 'Concept', 'patch'),
                update: wrap(wrapParams, 'Concept', 'update'),
                getMany: wrap(wrapParams, 'Concept', 'getMany'),
                getDescendants: wrap(wrapParams, 'Concept', 'getDescendants'),
                getAncestors: wrap(wrapParams, 'Concept', 'getAncestors'),
                getTotal: wrap(wrapParams, 'Concept', 'getTotal'),
            },
            conceptScheme: {
                get: wrap(wrapParams, 'ConceptScheme', 'get'),
                getMany: wrap(wrapParams, 'ConceptScheme', 'getMany'),
                getTotal: wrap(wrapParams, 'ConceptScheme', 'getTotal'),
                delete: wrap(wrapParams, 'ConceptScheme', 'delete'),
                create: wrap(wrapParams, 'ConceptScheme', 'create'),
                createWithId: wrap(wrapParams, 'ConceptScheme', 'createWithId'),
                patch: wrap(wrapParams, 'ConceptScheme', 'patch'),
                update: wrap(wrapParams, 'ConceptScheme', 'update'),
            },
            function: {
                get: wrap(wrapParams, 'Function', 'get'),
                getMany: wrap(wrapParams, 'Function', 'getMany'),
                getManyForEnvironment: wrap(wrapParams, 'Function', 'getManyForEnvironment'),
            },
            functionLog: {
                get: wrap(wrapParams, 'FunctionLog', 'get'),
                getMany: wrap(wrapParams, 'FunctionLog', 'getMany'),
            },
            editorInterface: {
                get: wrap(wrapParams, 'EditorInterface', 'get'),
                getMany: wrap(wrapParams, 'EditorInterface', 'getMany'),
                update: wrap(wrapParams, 'EditorInterface', 'update'),
            },
            space: {
                get: wrap(wrapParams, 'Space', 'get'),
                getMany: wrap(wrapParams, 'Space', 'getMany'),
                getManyForOrganization: wrap(wrapParams, 'Space', 'getManyForOrganization'),
                update: wrap(wrapParams, 'Space', 'update'),
                delete: wrap(wrapParams, 'Space', 'delete'),
                create: wrap(wrapParams, 'Space', 'create'),
            },
            environment: {
                get: wrap(wrapParams, 'Environment', 'get'),
                getMany: wrap(wrapParams, 'Environment', 'getMany'),
                create: wrap(wrapParams, 'Environment', 'create'),
                createWithId: wrap(wrapParams, 'Environment', 'createWithId'),
                update: wrap(wrapParams, 'Environment', 'update'),
                delete: wrap(wrapParams, 'Environment', 'delete'),
            },
            environmentAlias: {
                get: wrap(wrapParams, 'EnvironmentAlias', 'get'),
                getMany: wrap(wrapParams, 'EnvironmentAlias', 'getMany'),
                createWithId: wrap(wrapParams, 'EnvironmentAlias', 'createWithId'),
                update: wrap(wrapParams, 'EnvironmentAlias', 'update'),
                delete: wrap(wrapParams, 'EnvironmentAlias', 'delete'),
            },
            environmentTemplate: {
                get: wrap(wrapParams, 'EnvironmentTemplate', 'get'),
                getMany: wrap(wrapParams, 'EnvironmentTemplate', 'getMany'),
                create: wrap(wrapParams, 'EnvironmentTemplate', 'create'),
                versionUpdate: wrap(wrapParams, 'EnvironmentTemplate', 'versionUpdate'),
                update: wrap(wrapParams, 'EnvironmentTemplate', 'update'),
                install: wrap(wrapParams, 'EnvironmentTemplate', 'install'),
                versions: wrap(wrapParams, 'EnvironmentTemplate', 'versions'),
                validate: wrap(wrapParams, 'EnvironmentTemplate', 'validate'),
                disconnect: wrap(wrapParams, 'EnvironmentTemplate', 'disconnect'),
                delete: wrap(wrapParams, 'EnvironmentTemplate', 'delete'),
            },
            environmentTemplateInstallation: {
                getMany: wrap(wrapParams, 'EnvironmentTemplateInstallation', 'getMany'),
                getForEnvironment: wrap(wrapParams, 'EnvironmentTemplateInstallation', 'getForEnvironment'),
            },
            bulkAction: {
                get: wrap(wrapParams, 'BulkAction', 'get'),
                publish: wrap(wrapParams, 'BulkAction', 'publish'),
                unpublish: wrap(wrapParams, 'BulkAction', 'unpublish'),
                validate: wrap(wrapParams, 'BulkAction', 'validate'),
                getV2: wrap(wrapParams, 'BulkAction', 'getV2'),
                publishV2: wrap(wrapParams, 'BulkAction', 'publishV2'),
                unpublishV2: wrap(wrapParams, 'BulkAction', 'unpublishV2'),
                validateV2: wrap(wrapParams, 'BulkAction', 'validateV2'),
            },
            comment: {
                get: wrap(wrapParams, 'Comment', 'get'),
                getMany: wrap(wrapParams, 'Comment', 'getMany'),
                create: wrap(wrapParams, 'Comment', 'create'),
                update: wrap(wrapParams, 'Comment', 'update'),
                delete: wrap(wrapParams, 'Comment', 'delete'),
            },
            componentType: {
                getMany: wrap(wrapParams, 'ComponentType', 'getMany'),
                get: wrap(wrapParams, 'ComponentType', 'get'),
                create: wrap(wrapParams, 'ComponentType', 'create'),
                upsert: wrap(wrapParams, 'ComponentType', 'upsert'),
                delete: wrap(wrapParams, 'ComponentType', 'delete'),
                publish: wrap(wrapParams, 'ComponentType', 'publish'),
                unpublish: wrap(wrapParams, 'ComponentType', 'unpublish'),
            },
            component: {
                getMany: wrap(wrapParams, 'Component', 'getMany'),
                get: wrap(wrapParams, 'Component', 'get'),
                create: wrap(wrapParams, 'Component', 'create'),
                upsert: wrap(wrapParams, 'Component', 'upsert'),
                delete: wrap(wrapParams, 'Component', 'delete'),
                publish: wrap(wrapParams, 'Component', 'publish'),
                unpublish: wrap(wrapParams, 'Component', 'unpublish'),
            },
            contentType: {
                get: wrap(wrapParams, 'ContentType', 'get'),
                getMany: wrap(wrapParams, 'ContentType', 'getMany'),
                getManyWithCursor: wrap(wrapParams, 'ContentType', 'getManyWithCursor'),
                update: wrap(wrapParams, 'ContentType', 'update'),
                delete: wrap(wrapParams, 'ContentType', 'delete'),
                publish: wrap(wrapParams, 'ContentType', 'publish'),
                unpublish: wrap(wrapParams, 'ContentType', 'unpublish'),
                create: wrap(wrapParams, 'ContentType', 'create'),
                createWithId: wrap(wrapParams, 'ContentType', 'createWithId'),
                omitAndDeleteField: (params, contentType, fieldId) => omitAndDeleteField(makeRequest, { ...{ ...defaults, ...params }, fieldId }, contentType),
            },
            dataAssembly: {
                getMany: wrap(wrapParams, 'DataAssembly', 'getMany'),
                getManyPublished: wrap(wrapParams, 'DataAssembly', 'getManyPublished'),
                getPublished: wrap(wrapParams, 'DataAssembly', 'getPublished'),
                get: wrap(wrapParams, 'DataAssembly', 'get'),
                create: wrap(wrapParams, 'DataAssembly', 'create'),
                update: wrap(wrapParams, 'DataAssembly', 'update'),
                delete: wrap(wrapParams, 'DataAssembly', 'delete'),
                publish: wrap(wrapParams, 'DataAssembly', 'publish'),
                unpublish: wrap(wrapParams, 'DataAssembly', 'unpublish'),
            },
            designToken: {
                getMany: wrap(wrapParams, 'DesignToken', 'getMany'),
                get: wrap(wrapParams, 'DesignToken', 'get'),
                upsert: wrap(wrapParams, 'DesignToken', 'upsert'),
                delete: wrap(wrapParams, 'DesignToken', 'delete'),
            },
            user: {
                getManyForSpace: wrap(wrapParams, 'User', 'getManyForSpace'),
                getForSpace: wrap(wrapParams, 'User', 'getForSpace'),
                getCurrent: wrap(wrapParams, 'User', 'getCurrent'),
                getForOrganization: wrap(wrapParams, 'User', 'getForOrganization'),
                getManyForOrganization: wrap(wrapParams, 'User', 'getManyForOrganization'),
            },
            task: {
                get: wrap(wrapParams, 'Task', 'get'),
                getMany: wrap(wrapParams, 'Task', 'getMany'),
                create: wrap(wrapParams, 'Task', 'create'),
                update: wrap(wrapParams, 'Task', 'update'),
                delete: wrap(wrapParams, 'Task', 'delete'),
            },
            entry: {
                getPublished: wrap(wrapParams, 'Entry', 'getPublished'),
                getPublishedWithCursor: wrap(wrapParams, 'Entry', 'getPublishedWithCursor'),
                getMany: wrap(wrapParams, 'Entry', 'getMany'),
                getManyWithCursor: wrap(wrapParams, 'Entry', 'getManyWithCursor'),
                get: wrap(wrapParams, 'Entry', 'get'),
                update: wrap(wrapParams, 'Entry', 'update'),
                patch: wrap(wrapParams, 'Entry', 'patch'),
                delete: wrap(wrapParams, 'Entry', 'delete'),
                publish: wrap(wrapParams, 'Entry', 'publish'),
                unpublish: wrap(wrapParams, 'Entry', 'unpublish'),
                archive: wrap(wrapParams, 'Entry', 'archive'),
                unarchive: wrap(wrapParams, 'Entry', 'unarchive'),
                create: wrap(wrapParams, 'Entry', 'create'),
                createWithId: wrap(wrapParams, 'Entry', 'createWithId'),
                references: wrap(wrapParams, 'Entry', 'references'),
            },
            asset: {
                getPublished: wrap(wrapParams, 'Asset', 'getPublished'),
                getPublishedWithCursor: wrap(wrapParams, 'Asset', 'getPublishedWithCursor'),
                getMany: wrap(wrapParams, 'Asset', 'getMany'),
                getManyWithCursor: wrap(wrapParams, 'Asset', 'getManyWithCursor'),
                get: wrap(wrapParams, 'Asset', 'get'),
                update: wrap(wrapParams, 'Asset', 'update'),
                delete: wrap(wrapParams, 'Asset', 'delete'),
                publish: wrap(wrapParams, 'Asset', 'publish'),
                unpublish: wrap(wrapParams, 'Asset', 'unpublish'),
                archive: wrap(wrapParams, 'Asset', 'archive'),
                unarchive: wrap(wrapParams, 'Asset', 'unarchive'),
                create: wrap(wrapParams, 'Asset', 'create'),
                createWithId: wrap(wrapParams, 'Asset', 'createWithId'),
                createFromFiles: wrap(wrapParams, 'Asset', 'createFromFiles'),
                processForAllLocales: (params, asset, options) => makeRequest({
                    entityType: 'Asset',
                    action: 'processForAllLocales',
                    params: {
                        ...{ ...defaults, ...params },
                        options,
                        asset,
                    },
                }),
                processForLocale: (params, asset, locale, options) => makeRequest({
                    entityType: 'Asset',
                    action: 'processForLocale',
                    params: {
                        ...{ ...defaults, ...params },
                        locale,
                        asset,
                        options,
                    },
                }),
            },
            appUpload: {
                get: wrap(wrapParams, 'AppUpload', 'get'),
                delete: wrap(wrapParams, 'AppUpload', 'delete'),
                create: wrap(wrapParams, 'AppUpload', 'create'),
            },
            assetKey: {
                create: wrap(wrapParams, 'AssetKey', 'create'),
            },
            upload: {
                get: wrap(wrapParams, 'Upload', 'get'),
                create: wrap(wrapParams, 'Upload', 'create'),
                delete: wrap(wrapParams, 'Upload', 'delete'),
            },
            uploadCredential: {
                create: wrap(wrapParams, 'UploadCredential', 'create'),
            },
            locale: {
                get: wrap(wrapParams, 'Locale', 'get'),
                getMany: wrap(wrapParams, 'Locale', 'getMany'),
                delete: wrap(wrapParams, 'Locale', 'delete'),
                update: wrap(wrapParams, 'Locale', 'update'),
                create: wrap(wrapParams, 'Locale', 'create'),
            },
            personalAccessToken: {
                get: wrap(wrapParams, 'PersonalAccessToken', 'get'),
                getMany: wrap(wrapParams, 'PersonalAccessToken', 'getMany'),
                create: (data, headers) => makeRequest({
                    entityType: 'PersonalAccessToken',
                    action: 'create',
                    params: {},
                    headers,
                    payload: data,
                }),
                revoke: wrap(wrapParams, 'PersonalAccessToken', 'revoke'),
            },
            accessToken: {
                get: wrap(wrapParams, 'AccessToken', 'get'),
                getMany: wrap(wrapParams, 'AccessToken', 'getMany'),
                createPersonalAccessToken: (data, headers) => makeRequest({
                    entityType: 'AccessToken',
                    action: 'createPersonalAccessToken',
                    params: {},
                    headers,
                    payload: data,
                }),
                revoke: wrap(wrapParams, 'AccessToken', 'revoke'),
                getManyForOrganization: wrap(wrapParams, 'AccessToken', 'getManyForOrganization'),
            },
            usage: {
                getManyForSpace: wrap(wrapParams, 'Usage', 'getManyForSpace'),
                getManyForOrganization: wrap(wrapParams, 'Usage', 'getManyForOrganization'),
                getAggregated: wrap(wrapParams, 'Usage', 'getAggregated'),
                getAssetBandwidthUsageDetailed: wrap(wrapParams, 'Usage', 'getAssetBandwidthUsageDetailed'),
            },
            release: {
                asset: {
                    get: wrap(wrapParams, 'ReleaseAsset', 'get'),
                    getMany: wrap(wrapParams, 'ReleaseAsset', 'getMany'),
                    update: wrap(wrapParams, 'ReleaseAsset', 'update'),
                    create: wrap(wrapParams, 'ReleaseAsset', 'create'),
                    createWithId: wrap(wrapParams, 'ReleaseAsset', 'createWithId'),
                    createFromFiles: wrap(wrapParams, 'ReleaseAsset', 'createFromFiles'),
                    processForAllLocales: (params, asset, options) => makeRequest({
                        entityType: 'ReleaseAsset',
                        action: 'processForAllLocales',
                        params: {
                            ...{ ...defaults, ...params },
                            options,
                            asset,
                        },
                    }),
                    processForLocale: (params, asset, locale, options) => makeRequest({
                        entityType: 'ReleaseAsset',
                        action: 'processForLocale',
                        params: {
                            ...{ ...defaults, ...params },
                            locale,
                            asset,
                            options,
                        },
                    }),
                },
                entry: {
                    get: wrap(wrapParams, 'ReleaseEntry', 'get'),
                    getMany: wrap(wrapParams, 'ReleaseEntry', 'getMany'),
                    update: wrap(wrapParams, 'ReleaseEntry', 'update'),
                    patch: wrap(wrapParams, 'ReleaseEntry', 'patch'),
                    create: wrap(wrapParams, 'ReleaseEntry', 'create'),
                    createWithId: wrap(wrapParams, 'ReleaseEntry', 'createWithId'),
                },
                archive: wrap(wrapParams, 'Release', 'archive'),
                get: wrap(wrapParams, 'Release', 'get'),
                query: wrap(wrapParams, 'Release', 'query'),
                create: wrap(wrapParams, 'Release', 'create'),
                update: wrap(wrapParams, 'Release', 'update'),
                delete: wrap(wrapParams, 'Release', 'delete'),
                publish: wrap(wrapParams, 'Release', 'publish'),
                unarchive: wrap(wrapParams, 'Release', 'unarchive'),
                unpublish: wrap(wrapParams, 'Release', 'unpublish'),
                validate: wrap(wrapParams, 'Release', 'validate'),
            },
            releaseAction: {
                get: wrap(wrapParams, 'ReleaseAction', 'get'),
                getMany: wrap(wrapParams, 'ReleaseAction', 'getMany'),
                queryForRelease: wrap(wrapParams, 'ReleaseAction', 'queryForRelease'),
            },
            role: {
                get: wrap(wrapParams, 'Role', 'get'),
                getMany: wrap(wrapParams, 'Role', 'getMany'),
                getManyForOrganization: wrap(wrapParams, 'Role', 'getManyForOrganization'),
                create: wrap(wrapParams, 'Role', 'create'),
                createWithId: wrap(wrapParams, 'Role', 'createWithId'),
                update: wrap(wrapParams, 'Role', 'update'),
                delete: wrap(wrapParams, 'Role', 'delete'),
            },
            scheduledActions: {
                get: wrap(wrapParams, 'ScheduledAction', 'get'),
                getMany: wrap(wrapParams, 'ScheduledAction', 'getMany'),
                create: wrap(wrapParams, 'ScheduledAction', 'create'),
                delete: wrap(wrapParams, 'ScheduledAction', 'delete'),
                update: wrap(wrapParams, 'ScheduledAction', 'update'),
            },
            previewApiKey: {
                get: wrap(wrapParams, 'PreviewApiKey', 'get'),
                getMany: wrap(wrapParams, 'PreviewApiKey', 'getMany'),
            },
            apiKey: {
                get: wrap(wrapParams, 'ApiKey', 'get'),
                getMany: wrap(wrapParams, 'ApiKey', 'getMany'),
                create: wrap(wrapParams, 'ApiKey', 'create'),
                createWithId: wrap(wrapParams, 'ApiKey', 'createWithId'),
                update: wrap(wrapParams, 'ApiKey', 'update'),
                delete: wrap(wrapParams, 'ApiKey', 'delete'),
            },
            appDefinition: {
                get: wrap(wrapParams, 'AppDefinition', 'get'),
                getMany: wrap(wrapParams, 'AppDefinition', 'getMany'),
                create: wrap(wrapParams, 'AppDefinition', 'create'),
                update: wrap(wrapParams, 'AppDefinition', 'update'),
                delete: wrap(wrapParams, 'AppDefinition', 'delete'),
                getInstallationsForOrg: wrap(wrapParams, 'AppDefinition', 'getInstallationsForOrg'),
            },
            appInstallation: {
                get: wrap(wrapParams, 'AppInstallation', 'get'),
                getMany: wrap(wrapParams, 'AppInstallation', 'getMany'),
                getForOrganization: wrap(wrapParams, 'AppInstallation', 'getForOrganization'),
                upsert: wrap(wrapParams, 'AppInstallation', 'upsert'),
                delete: wrap(wrapParams, 'AppInstallation', 'delete'),
            },
            resource: {
                getMany: wrap(wrapParams, 'Resource', 'getMany'),
            },
            resourceProvider: {
                get: wrap(wrapParams, 'ResourceProvider', 'get'),
                upsert: wrap(wrapParams, 'ResourceProvider', 'upsert'),
                delete: wrap(wrapParams, 'ResourceProvider', 'delete'),
            },
            resourceType: {
                get: wrap(wrapParams, 'ResourceType', 'get'),
                getMany: wrap(wrapParams, 'ResourceType', 'getMany'),
                upsert: wrap(wrapParams, 'ResourceType', 'upsert'),
                delete: wrap(wrapParams, 'ResourceType', 'delete'),
                getForEnvironment: wrap(wrapParams, 'ResourceType', 'getForEnvironment'),
            },
            extension: {
                get: wrap(wrapParams, 'Extension', 'get'),
                getMany: wrap(wrapParams, 'Extension', 'getMany'),
                create: wrap(wrapParams, 'Extension', 'create'),
                createWithId: wrap(wrapParams, 'Extension', 'createWithId'),
                update: wrap(wrapParams, 'Extension', 'update'),
                delete: wrap(wrapParams, 'Extension', 'delete'),
            },
            webhook: {
                get: wrap(wrapParams, 'Webhook', 'get'),
                getMany: wrap(wrapParams, 'Webhook', 'getMany'),
                getHealthStatus: wrap(wrapParams, 'Webhook', 'getHealthStatus'),
                getCallDetails: wrap(wrapParams, 'Webhook', 'getCallDetails'),
                getSigningSecret: wrap(wrapParams, 'Webhook', 'getSigningSecret'),
                getRetryPolicy: wrap(wrapParams, 'Webhook', 'getRetryPolicy'),
                getManyCallDetails: wrap(wrapParams, 'Webhook', 'getManyCallDetails'),
                create: wrap(wrapParams, 'Webhook', 'create'),
                update: wrap(wrapParams, 'Webhook', 'update'),
                upsertSigningSecret: wrap(wrapParams, 'Webhook', 'upsertSigningSecret'),
                upsertRetryPolicy: wrap(wrapParams, 'Webhook', 'upsertRetryPolicy'),
                delete: wrap(wrapParams, 'Webhook', 'delete'),
                deleteSigningSecret: wrap(wrapParams, 'Webhook', 'deleteSigningSecret'),
                deleteRetryPolicy: wrap(wrapParams, 'Webhook', 'deleteRetryPolicy'),
            },
            snapshot: {
                getManyForEntry: wrap(wrapParams, 'Snapshot', 'getManyForEntry'),
                getForEntry: wrap(wrapParams, 'Snapshot', 'getForEntry'),
                getManyForContentType: wrap(wrapParams, 'Snapshot', 'getManyForContentType'),
                getForContentType: wrap(wrapParams, 'Snapshot', 'getForContentType'),
            },
            tag: {
                get: wrap(wrapParams, 'Tag', 'get'),
                getMany: wrap(wrapParams, 'Tag', 'getMany'),
                createWithId: wrap(wrapParams, 'Tag', 'createWithId'),
                update: wrap(wrapParams, 'Tag', 'update'),
                delete: wrap(wrapParams, 'Tag', 'delete'),
            },
            organization: {
                getAll: wrap(wrapParams, 'Organization', 'getMany'),
                get: wrap(wrapParams, 'Organization', 'get'),
            },
            organizationInvitation: {
                get: wrap(wrapParams, 'OrganizationInvitation', 'get'),
                create: wrap(wrapParams, 'OrganizationInvitation', 'create'),
            },
            organizationMembership: {
                get: wrap(wrapParams, 'OrganizationMembership', 'get'),
                getMany: wrap(wrapParams, 'OrganizationMembership', 'getMany'),
                update: wrap(wrapParams, 'OrganizationMembership', 'update'),
                delete: wrap(wrapParams, 'OrganizationMembership', 'delete'),
            },
            oauthApplication: {
                get: wrap(wrapParams, 'OAuthApplication', 'get'),
                getManyForUser: wrap(wrapParams, 'OAuthApplication', 'getManyForUser'),
                update: wrap(wrapParams, 'OAuthApplication', 'update'),
                delete: wrap(wrapParams, 'OAuthApplication', 'delete'),
                create: wrap(wrapParams, 'OAuthApplication', 'create'),
            },
            semanticDuplicates: {
                get: wrap(wrapParams, 'SemanticDuplicates', 'get'),
            },
            semanticRecommendations: {
                get: wrap(wrapParams, 'SemanticRecommendations', 'get'),
            },
            semanticReferenceSuggestions: {
                get: wrap(wrapParams, 'SemanticReferenceSuggestions', 'get'),
            },
            semanticSearch: {
                get: wrap(wrapParams, 'SemanticSearch', 'get'),
            },
            semanticSettings: {
                get: wrap(wrapParams, 'SemanticSettings', 'get'),
            },
            contentSemanticsIndex: {
                get: wrap(wrapParams, 'ContentSemanticsIndex', 'get'),
                getMany: wrap(wrapParams, 'ContentSemanticsIndex', 'getMany'),
                getManyForEnvironment: wrap(wrapParams, 'ContentSemanticsIndex', 'getManyForEnvironment'),
                create: wrap(wrapParams, 'ContentSemanticsIndex', 'create'),
                delete: wrap(wrapParams, 'ContentSemanticsIndex', 'delete'),
            },
            spaceMember: {
                get: wrap(wrapParams, 'SpaceMember', 'get'),
                getMany: wrap(wrapParams, 'SpaceMember', 'getMany'),
            },
            spaceMembership: {
                get: wrap(wrapParams, 'SpaceMembership', 'get'),
                getMany: wrap(wrapParams, 'SpaceMembership', 'getMany'),
                getForOrganization: wrap(wrapParams, 'SpaceMembership', 'getForOrganization'),
                getManyForOrganization: wrap(wrapParams, 'SpaceMembership', 'getManyForOrganization'),
                create: wrap(wrapParams, 'SpaceMembership', 'create'),
                createWithId: wrap(wrapParams, 'SpaceMembership', 'createWithId'),
                update: wrap(wrapParams, 'SpaceMembership', 'update'),
                delete: wrap(wrapParams, 'SpaceMembership', 'delete'),
            },
            team: {
                get: wrap(wrapParams, 'Team', 'get'),
                getMany: wrap(wrapParams, 'Team', 'getMany'),
                getManyForSpace: wrap(wrapParams, 'Team', 'getManyForSpace'),
                create: wrap(wrapParams, 'Team', 'create'),
                update: wrap(wrapParams, 'Team', 'update'),
                delete: wrap(wrapParams, 'Team', 'delete'),
            },
            teamMembership: {
                get: wrap(wrapParams, 'TeamMembership', 'get'),
                getManyForOrganization: wrap(wrapParams, 'TeamMembership', 'getManyForOrganization'),
                getManyForTeam: wrap(wrapParams, 'TeamMembership', 'getManyForTeam'),
                create: wrap(wrapParams, 'TeamMembership', 'create'),
                update: wrap(wrapParams, 'TeamMembership', 'update'),
                delete: wrap(wrapParams, 'TeamMembership', 'delete'),
            },
            teamSpaceMembership: {
                get: wrap(wrapParams, 'TeamSpaceMembership', 'get'),
                getMany: wrap(wrapParams, 'TeamSpaceMembership', 'getMany'),
                getForOrganization: wrap(wrapParams, 'TeamSpaceMembership', 'getForOrganization'),
                getManyForOrganization: wrap(wrapParams, 'TeamSpaceMembership', 'getManyForOrganization'),
                create: wrap(wrapParams, 'TeamSpaceMembership', 'create'),
                update: wrap(wrapParams, 'TeamSpaceMembership', 'update'),
                delete: wrap(wrapParams, 'TeamSpaceMembership', 'delete'),
            },
            fragment: {
                getMany: wrap(wrapParams, 'Fragment', 'getMany'),
                get: wrap(wrapParams, 'Fragment', 'get'),
                create: wrap(wrapParams, 'Fragment', 'create'),
                upsert: wrap(wrapParams, 'Fragment', 'upsert'),
                delete: wrap(wrapParams, 'Fragment', 'delete'),
                publish: wrap(wrapParams, 'Fragment', 'publish'),
                unpublish: wrap(wrapParams, 'Fragment', 'unpublish'),
            },
            template: {
                getMany: wrap(wrapParams, 'Template', 'getMany'),
                get: wrap(wrapParams, 'Template', 'get'),
                create: wrap(wrapParams, 'Template', 'create'),
                upsert: wrap(wrapParams, 'Template', 'upsert'),
                delete: wrap(wrapParams, 'Template', 'delete'),
                publish: wrap(wrapParams, 'Template', 'publish'),
                unpublish: wrap(wrapParams, 'Template', 'unpublish'),
            },
            uiConfig: {
                get: wrap(wrapParams, 'UIConfig', 'get'),
                update: wrap(wrapParams, 'UIConfig', 'update'),
            },
            userUIConfig: {
                get: wrap(wrapParams, 'UserUIConfig', 'get'),
                update: wrap(wrapParams, 'UserUIConfig', 'update'),
            },
            experience: {
                getMany: wrap(wrapParams, 'Experience', 'getMany'),
                get: wrap(wrapParams, 'Experience', 'get'),
                create: wrap(wrapParams, 'Experience', 'create'),
                upsert: wrap(wrapParams, 'Experience', 'upsert'),
                delete: wrap(wrapParams, 'Experience', 'delete'),
                publish: wrap(wrapParams, 'Experience', 'publish'),
                unpublish: wrap(wrapParams, 'Experience', 'unpublish'),
            },
            experienceVariant: {
                getMany: wrap(wrapParams, 'ExperienceVariant', 'getMany'),
                get: wrap(wrapParams, 'ExperienceVariant', 'get'),
                create: wrap(wrapParams, 'ExperienceVariant', 'create'),
                upsert: wrap(wrapParams, 'ExperienceVariant', 'upsert'),
                delete: wrap(wrapParams, 'ExperienceVariant', 'delete'),
                publish: wrap(wrapParams, 'ExperienceVariant', 'publish'),
                unpublish: wrap(wrapParams, 'ExperienceVariant', 'unpublish'),
                archive: wrap(wrapParams, 'ExperienceVariant', 'archive'),
                unarchive: wrap(wrapParams, 'ExperienceVariant', 'unarchive'),
            },
            experienceFragment: {
                getMany: wrap(wrapParams, 'ExperienceFragment', 'getMany'),
                get: wrap(wrapParams, 'ExperienceFragment', 'get'),
                create: wrap(wrapParams, 'ExperienceFragment', 'create'),
                upsert: wrap(wrapParams, 'ExperienceFragment', 'upsert'),
                delete: wrap(wrapParams, 'ExperienceFragment', 'delete'),
                publish: wrap(wrapParams, 'ExperienceFragment', 'publish'),
                unpublish: wrap(wrapParams, 'ExperienceFragment', 'unpublish'),
            },
            experienceTemplate: {
                getMany: wrap(wrapParams, 'ExperienceTemplate', 'getMany'),
                get: wrap(wrapParams, 'ExperienceTemplate', 'get'),
                create: wrap(wrapParams, 'ExperienceTemplate', 'create'),
                upsert: wrap(wrapParams, 'ExperienceTemplate', 'upsert'),
                delete: wrap(wrapParams, 'ExperienceTemplate', 'delete'),
                publish: wrap(wrapParams, 'ExperienceTemplate', 'publish'),
                unpublish: wrap(wrapParams, 'ExperienceTemplate', 'unpublish'),
            },
            experienceFragmentVariant: {
                getMany: wrap(wrapParams, 'ExperienceFragmentVariant', 'getMany'),
                get: wrap(wrapParams, 'ExperienceFragmentVariant', 'get'),
                create: wrap(wrapParams, 'ExperienceFragmentVariant', 'create'),
                upsert: wrap(wrapParams, 'ExperienceFragmentVariant', 'upsert'),
                delete: wrap(wrapParams, 'ExperienceFragmentVariant', 'delete'),
                publish: wrap(wrapParams, 'ExperienceFragmentVariant', 'publish'),
                unpublish: wrap(wrapParams, 'ExperienceFragmentVariant', 'unpublish'),
                archive: wrap(wrapParams, 'ExperienceFragmentVariant', 'archive'),
                unarchive: wrap(wrapParams, 'ExperienceFragmentVariant', 'unarchive'),
            },
            workflowDefinition: {
                get: wrap(wrapParams, 'WorkflowDefinition', 'get'),
                getMany: wrap(wrapParams, 'WorkflowDefinition', 'getMany'),
                create: wrap(wrapParams, 'WorkflowDefinition', 'create'),
                update: wrap(wrapParams, 'WorkflowDefinition', 'update'),
                delete: wrap(wrapParams, 'WorkflowDefinition', 'delete'),
            },
            workflow: {
                get: wrap(wrapParams, 'Workflow', 'get'),
                getMany: wrap(wrapParams, 'Workflow', 'getMany'),
                create: wrap(wrapParams, 'Workflow', 'create'),
                update: wrap(wrapParams, 'Workflow', 'update'),
                delete: wrap(wrapParams, 'Workflow', 'delete'),
                complete: wrap(wrapParams, 'Workflow', 'complete'),
            },
            workflowsChangelog: {
                getMany: wrap(wrapParams, 'WorkflowsChangelog', 'getMany'),
            },
        };
    };

    var WidgetNamespace;
    (function (WidgetNamespace) {
        WidgetNamespace["BUILTIN"] = "builtin";
        WidgetNamespace["EXTENSION"] = "extension";
        WidgetNamespace["SIDEBAR_BUILTIN"] = "sidebar-builtin";
        WidgetNamespace["APP"] = "app";
        WidgetNamespace["EDITOR_BUILTIN"] = "editor-builtin";
    })(WidgetNamespace || (WidgetNamespace = {}));
    const DEFAULT_EDITOR_ID = 'default-editor';
    /**
     * @internal
     */
    const in_ = (key, object) => key in object;

    const SidebarWidgetTypes = {
        USERS: 'users-widget',
        CONTENT_PREVIEW: 'content-preview-widget',
        TRANSLATION: 'translation-widget',
        INCOMING_LINKS: 'incoming-links-widget',
        PUBLICATION: 'publication-widget',
        RELEASES: 'releases-widget',
        VERSIONS: 'versions-widget'};
    const Publication = {
        widgetId: SidebarWidgetTypes.PUBLICATION,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Publish & Status',
        description: 'Built-in - View entry status, publish, etc.',
    };
    const Releases = {
        widgetId: SidebarWidgetTypes.RELEASES,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Release',
        description: 'Built-in - View release, add to it, etc.',
    };
    const ContentPreview = {
        widgetId: SidebarWidgetTypes.CONTENT_PREVIEW,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Preview',
        description: 'Built-in - Displays preview functionality.',
    };
    const Links = {
        widgetId: SidebarWidgetTypes.INCOMING_LINKS,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Links',
        description: 'Built-in - Shows where an entry is linked.',
    };
    const Translation = {
        widgetId: SidebarWidgetTypes.TRANSLATION,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Translation',
        description: 'Built-in - Manage which translations are visible.',
    };
    const Versions = {
        widgetId: SidebarWidgetTypes.VERSIONS,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Versions',
        description: 'Built-in - View previously published versions. Available only for master environment.',
    };
    const Users = {
        widgetId: SidebarWidgetTypes.USERS,
        widgetNamespace: WidgetNamespace.SIDEBAR_BUILTIN,
        name: 'Users',
        description: 'Built-in - Displays users on the same entry.',
    };
    const SidebarEntryConfiguration = [
        Publication,
        Releases,
        ContentPreview,
        Links,
        Translation,
        Versions,
        Users,
    ];
    const SidebarAssetConfiguration = [Publication, Releases, Links, Translation, Users];

    const EntryEditorWidgetTypes = {
        DEFAULT_EDITOR: {
            name: 'Editor',
            id: DEFAULT_EDITOR_ID},
        REFERENCE_TREE: {
            name: 'References',
            id: 'reference-tree'},
        TAGS_EDITOR: {
            name: 'Tags',
            id: 'tags-editor'},
    };
    const DefaultEntryEditor = {
        widgetId: EntryEditorWidgetTypes.DEFAULT_EDITOR.id,
        widgetNamespace: WidgetNamespace.EDITOR_BUILTIN,
        name: EntryEditorWidgetTypes.DEFAULT_EDITOR.name,
    };
    const ReferencesEntryEditor = {
        widgetId: EntryEditorWidgetTypes.REFERENCE_TREE.id,
        widgetNamespace: WidgetNamespace.EDITOR_BUILTIN,
        name: EntryEditorWidgetTypes.REFERENCE_TREE.name,
    };
    const TagsEditor = {
        widgetId: EntryEditorWidgetTypes.TAGS_EDITOR.id,
        widgetNamespace: WidgetNamespace.EDITOR_BUILTIN,
        name: EntryEditorWidgetTypes.TAGS_EDITOR.name,
    };
    const EntryConfiguration = [DefaultEntryEditor, ReferencesEntryEditor, TagsEditor];

    const DROPDOWN_TYPES = ['Text', 'Symbol', 'Integer', 'Number', 'Boolean'];
    const INTERNAL_TO_API = {
        Symbol: { type: 'Symbol' },
        Text: { type: 'Text' },
        RichText: { type: 'RichText' },
        Integer: { type: 'Integer' },
        Number: { type: 'Number' },
        Boolean: { type: 'Boolean' },
        Date: { type: 'Date' },
        Location: { type: 'Location' },
        Object: { type: 'Object' },
        File: { type: 'File' },
        Entry: { type: 'Link', linkType: 'Entry' },
        Asset: { type: 'Link', linkType: 'Asset' },
        Resource: { type: 'ResourceLink' },
        Symbols: { type: 'Array', items: { type: 'Symbol' } },
        Entries: { type: 'Array', items: { type: 'Link', linkType: 'Entry' } },
        Assets: { type: 'Array', items: { type: 'Link', linkType: 'Asset' } },
        Resources: { type: 'Array', items: { type: 'ResourceLink' } },
    };
    const FIELD_TYPES = Object.keys(INTERNAL_TO_API);
    /**
     * Returns an internal string identifier for an API field object.
     *
     * We use this string as a simplified reference to field types.
     * Possible values are:
     *
     * - Symbol
     * - Symbols
     * - Text
     * - RichText
     * - Integer
     * - Number
     * - Boolean
     * - Date
     * - Location
     * - Object
     * - Entry
     * - Entries
     * - Asset
     * - Assets
     * - File
     */
    function toInternalFieldType(api) {
        return FIELD_TYPES.find((key) => {
            const internalApi = INTERNAL_TO_API[key];
            const stripped = {
                type: api.type,
                linkType: api.linkType,
                items: api.items,
            };
            if (stripped.items) {
                stripped.items = { type: stripped.items.type, linkType: stripped.items.linkType };
            }
            if (internalApi.type === 'Link') {
                return internalApi.linkType === stripped.linkType;
            }
            if (internalApi.type === 'Array' && internalApi.items && stripped.items) {
                if (internalApi.items.type === 'Link') {
                    return internalApi.items.linkType === stripped.items.linkType;
                }
                return internalApi.items.type === stripped.items.type;
            }
            return internalApi.type === stripped.type;
        });
    }
    const DEFAULTS_WIDGET = {
        Text: { widgetId: 'markdown' },
        Symbol: { widgetId: 'singleLine' },
        Integer: { widgetId: 'numberEditor' },
        Number: { widgetId: 'numberEditor' },
        Boolean: { widgetId: 'boolean' },
        Date: { widgetId: 'datePicker' },
        Location: { widgetId: 'locationEditor' },
        Object: { widgetId: 'objectEditor' },
        RichText: { widgetId: 'richTextEditor' },
        Entry: { widgetId: 'entryLinkEditor' },
        Asset: { widgetId: 'assetLinkEditor' },
        Symbols: { widgetId: 'tagEditor' },
        Entries: { widgetId: 'entryLinksEditor' },
        Assets: { widgetId: 'assetLinksEditor' },
        File: { widgetId: 'fileEditor' },
        Resource: { widgetId: 'resourceLinkEditor' },
        Resources: { widgetId: 'resourceLinksEditor' },
    };
    const DEFAULTS_SETTINGS = {
        Boolean: {
            falseLabel: 'No',
            helpText: null,
            trueLabel: 'Yes',
        },
        Date: {
            helpText: null,
            ampm: '24',
            format: 'timeZ',
        },
        Entry: {
            helpText: null,
            showCreateEntityAction: true,
            showLinkEntityAction: true,
        },
        Asset: {
            helpText: null,
            showCreateEntityAction: true,
            showLinkEntityAction: true,
        },
        Entries: {
            helpText: null,
            bulkEditing: false,
            showCreateEntityAction: true,
            showLinkEntityAction: true,
        },
        Assets: {
            helpText: null,
            showCreateEntityAction: true,
            showLinkEntityAction: true,
        },
    };
    function getDefaultWidget(field, fieldId) {
        const defaultWidget = {
            ...DEFAULTS_WIDGET[field],
            settings: {
                helpText: null,
            },
            widgetNamespace: 'builtin',
            fieldId,
        };
        if (in_(field, DEFAULTS_SETTINGS)) {
            defaultWidget.settings = {
                ...defaultWidget.settings,
                ...DEFAULTS_SETTINGS[field],
            };
        }
        return defaultWidget;
    }
    /*
     * Gets the default widget ID for a field:
     * - If a field allows predefined values then `dropdown` widget is used
     *   in the presence of the `in` validation.
     * - If a Text field is a title then the `singleLine` widget is used.
     * - Otherwise a simple type-to-editor mapping is used.
     */
    function getDefaultControlOfField(field) {
        const fieldType = toInternalFieldType(field);
        if (!fieldType) {
            throw new Error('Invalid field type');
        }
        const hasInValidation = (field.validations || []).find((v) => 'in' in v);
        if (hasInValidation && DROPDOWN_TYPES.includes(fieldType)) {
            return {
                widgetId: 'dropdown',
                fieldId: field.id,
                widgetNamespace: 'builtin',
            };
        }
        return getDefaultWidget(fieldType, field.id);
    }

    var index = {
        SidebarEntryConfiguration,
        SidebarAssetConfiguration,
        EntryConfiguration,
        getDefaultControlOfField,
    };

    var index$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        default: index
    });

    const asIterator = (fn, params) => {
        return {
            [Symbol.asyncIterator]() {
                let options = index$2(params);
                const get = () => fn(index$2(options));
                let currentResult = get();
                return {
                    current: 0,
                    async next() {
                        const { total = 0, items = [], skip = 0, limit = 100 } = await currentResult;
                        if (total === this.current) {
                            return { done: true, value: null };
                        }
                        const value = items[this.current++ - skip];
                        const endOfPage = this.current % limit === 0;
                        const endOfList = this.current === total;
                        if (endOfPage && !endOfList) {
                            options = {
                                ...options,
                                query: {
                                    ...options.query,
                                    skip: skip + limit,
                                },
                            };
                            currentResult = get();
                        }
                        return { done: false, value };
                    },
                };
            },
        };
    };

    function isOffsetBasedCollection(collection) {
        return 'total' in collection;
    }
    function isCursorBasedCollection(collection) {
        return 'pages' in collection;
    }
    function getSearchParam(url, paramName) {
        const searchIndex = url.indexOf('?');
        if (searchIndex < 0) {
            return null;
        }
        const rawSearchParams = url.slice(searchIndex + 1);
        const searchParams = new URLSearchParams(rawSearchParams);
        return searchParams.get(paramName);
    }
    function range(from, to) {
        return Array.from(Array(Math.abs(to - from)), (_, i) => from + i);
    }
    /**
     * Parameters for endpoint methods that can be paginated are inconsistent, `fetchAll` will only
     * work with the more common version of supplying the limit, skip, and pageNext parameters via a distinct `query` property in the
     * parameters.
     */
    async function fetchAll(fetchFn, params) {
        const response = await fetchFn({ ...params });
        if (isOffsetBasedCollection(response)) {
            const { total, limit, items } = response;
            const hasMorePages = total > items.length;
            if (!hasMorePages) {
                return items;
            }
            const pageCount = Math.ceil(total / limit);
            const promises = range(1, pageCount).map((page) => fetchFn({
                ...params,
                query: {
                    ...params.query,
                    limit,
                    skip: page * limit,
                },
            }).then((result) => result.items));
            const remainingItems = await Promise.all(promises);
            return [...items, ...remainingItems.flat(1)];
        }
        if (isCursorBasedCollection(response)) {
            const { pages, items } = response;
            if (!pages.next) {
                return items;
            }
            const pageNext = getSearchParam(pages.next, 'pageNext');
            if (!pageNext) {
                throw new Error('Missing "pageNext" query param from pages.next from response.');
            }
            return [
                ...items,
                ...(await fetchAll(fetchFn, {
                    ...params,
                    query: {
                        ...params.query,
                        pageNext,
                    },
                })),
            ];
        }
        throw new Error(`Can not determine collection type of response, neither property "total" nor "pages" are present.`);
    }

    exports.WorkflowStepPermissionType = void 0;
    (function (WorkflowStepPermissionType) {
        WorkflowStepPermissionType["EntityPermission"] = "entity_permission";
        WorkflowStepPermissionType["WorkflowPermission"] = "workflow_permission";
    })(exports.WorkflowStepPermissionType || (exports.WorkflowStepPermissionType = {}));
    exports.WorkflowStepPermissionAction = void 0;
    (function (WorkflowStepPermissionAction) {
        WorkflowStepPermissionAction["Edit"] = "edit";
        WorkflowStepPermissionAction["Publish"] = "publish";
        WorkflowStepPermissionAction["Delete"] = "delete";
    })(exports.WorkflowStepPermissionAction || (exports.WorkflowStepPermissionAction = {}));
    exports.WorkflowStepPermissionEffect = void 0;
    (function (WorkflowStepPermissionEffect) {
        WorkflowStepPermissionEffect["Allow"] = "allow";
        WorkflowStepPermissionEffect["Deny"] = "deny";
    })(exports.WorkflowStepPermissionEffect || (exports.WorkflowStepPermissionEffect = {}));
    /* Workflow Step Action */
    var WorkflowStepActionType;
    (function (WorkflowStepActionType) {
        WorkflowStepActionType["App"] = "app";
        WorkflowStepActionType["Email"] = "email";
        WorkflowStepActionType["Task"] = "task";
    })(WorkflowStepActionType || (WorkflowStepActionType = {}));

    /**
     * Contentful Management API SDK. Allows you to create instances of a client
     * with access to the Contentful Content Management API.
     * @packageDocumentation
     */
    // Usually, overloads with more specific signatures should come first but some IDEs are often not able to handle overloads with separate TSDocs correctly
    function createClient(clientOptions, opts = {}) {
        const sdkMain = opts.type === 'legacy' ? 'contentful-management.js' : 'contentful-management-plain.js';
        const userAgent = getUserAgentHeader(
        // @ts-expect-error "0.0.0-determined-by-semantic-release" is injected by rollup at build time
        `${sdkMain}/${"0.0.0-determined-by-semantic-release"}`, clientOptions.application, clientOptions.integration, clientOptions.feature);
        const adapter = createAdapter({ ...clientOptions, userAgent });
        // @ts-expect-error Parameters<?> and ReturnType<?> only return the types of the last overload (https://github.com/microsoft/TypeScript/issues/26591)
        const makeRequest = (options) => adapter.makeRequest({ ...options, userAgent });
        if (opts.type === 'legacy') {
            console.warn('[contentful-management] The nested (legacy) client is deprecated and will be removed in the next major version. Please migrate to the plain client. See the README for migration guidance.');
            return createClientApi(makeRequest);
        }
        else {
            return createPlainClient(makeRequest, opts.defaults);
        }
    }

    exports.RestAdapter = RestAdapter;
    exports.asIterator = asIterator;
    exports.createClient = createClient;
    exports.editorInterfaceDefaults = index$1;
    exports.fetchAll = fetchAll;
    exports.isDraft = isDraft;
    exports.isPublished = isPublished;
    exports.isUpdated = isUpdated;
    exports.makeRequest = makeRequest;

    return exports;

})({});
//# sourceMappingURL=index.js.map