UNPKG

contentful-management

Version:
15,907 lines 608 kB
'use strict';

var contentfulSdkCore = require('contentful-sdk-core');
var axios = require('axios');
var copy = require('fast-copy');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var axios__default = /*#__PURE__*/_interopDefault(axios);
var copy__default = /*#__PURE__*/_interopDefault(copy);

/* 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, contentfulSdkCore.errorHandler);
}
function patch$5(http, url, payload, config) {
    return http
        .patch(url, payload, {
        baseURL: getBaseUrl$D(http),
        ...config,
    })
        .then((response) => response.data, contentfulSdkCore.errorHandler);
}
function post$1(http, url, payload, config) {
    return http
        .post(url, payload, {
        baseURL: getBaseUrl$D(http),
        ...config,
    })
        .then((response) => response.data, contentfulSdkCore.errorHandler);
}
function put$1(http, url, payload, config) {
    return http
        .put(url, payload, {
        baseURL: getBaseUrl$D(http),
        ...config,
    })
        .then((response) => response.data, contentfulSdkCore.errorHandler);
}
function del$S(http, url, config) {
    return http
        .delete(url, {
        baseURL: getBaseUrl$D(http),
        ...config,
    })
        .then((response) => response.data, contentfulSdkCore.errorHandler);
}
function http(http, url, config) {
    return http(url, {
        baseURL: getBaseUrl$D(http),
        ...config,
    }).then((response) => response.data, contentfulSdkCore.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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$C(params), data, {
        headers,
    });
};
const update$z = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$y(params), data);
};
const update$w = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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(contentfulSdkCore.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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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(contentfulSdkCore.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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$u(params), data, { headers });
};
const upsert$b = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$t(params), data, { headers });
};
const upsert$a = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$s(params), data, { headers });
};
const createWithId$9 = (http, params, rawData, headers) => {
    const data = copy__default.default(rawData);
    return put$1(http, getContentTypeUrl$1(params), data, { headers });
};
const update$q = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$r(params), data, { headers });
};
const update$p = (http, params, rawData, headers) => {
    const data = copy__default.default(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 } = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, `/spaces/${params.spaceId}/environments`, data, {
        headers,
    });
};
const createWithId$6 = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(rawData);
    return put$1(http, getEnvironmentAliasUrl(params), data, {
        headers: headers,
    });
};
const update$k = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return put$1(http, getExtensionUrl(params), data, { headers });
};
const update$i = async (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$l(params), data, { headers });
};
const upsert$8 = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = /*#__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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$e(params), data);
};
const update$8 = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$a(params), data, { headers });
};
const upsert$5 = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$9(params), data, {
        headers: {
            ...ExperienceAlphaHeaders,
            ...headers,
        },
    });
};
const upsert$4 = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$8(params), data, {
        headers: {
            ...ExperienceAlphaHeaders,
            ...headers,
        },
    });
};
const upsert$3 = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$7(params), data, { headers });
};
const upsert$2 = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$6(params), data, { headers });
};
const upsert$1 = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$5(params), data, { headers });
};
const upsert = (http, params, rawData, headers) => {
    const { sys, ...body } = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$3(params), data, { headers });
};
const createWithId = (http, params, rawData, headers) => {
    const data = copy__default.default(rawData);
    return put$1(http, getWebhookUrl(params), data, { headers });
};
const update$2 = async (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(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 = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$2(params), data, {
        headers,
    });
};
const update$1 = (http, params, rawData, headers) => {
    const data = copy__default.default(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 = copy__default.default(rawData);
    return post$1(http, getBaseUrl$1(params), data, {
        headers,
    });
};
const update = (http, params, rawData, headers) => {
    const data = copy__default.default(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,
    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 = copy__default.default(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 = contentfulSdkCore.createHttpClient(axios__default.default, {
            ...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 contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const releaseActionWithApiMethods = enhanceWithMethods(releaseAction, createReleaseActionApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const releaseWithApiMethods = enhanceWithMethods(release, createReleaseApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const tagWithMethods = enhanceWithMethods(tag, createTagApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const userWithMethods = enhanceWithMethods(user, createUIConfigApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const userWithMethods = enhanceWithMethods(user, createUserUIConfigApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const funcWithMethods = enhanceWithMethods(func, createFunctionApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const editorInterfaceWithMethods = enhanceWithMethods(editorInterface, createEditorInterfaceApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const snapshotWithMethods = enhanceWithMethods(snapshot, createSnapshotApi());
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const contentTypeWithMethods = enhanceWithMethods(contentType, createContentTypeApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const taskWithMethods = enhanceWithMethods(task, createTaskApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const commentWithMethods = enhanceWithMethods(comment, createCommentApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const entryWithMethods = enhanceWithMethods(entry, createEntryApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const assetWithMethods = enhanceWithMethods(asset, createAssetApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const localeWithMethods = enhanceWithMethods(locale, createLocaleApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const uploadWithMethods = enhanceWithMethods(upload, createUploadApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const extensionWithMethods = enhanceWithMethods(extension, createExtensionApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const appInstallationWithMethods = enhanceWithMethods(appInstallation, createAppInstallationApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const bulkActionWithApiMethods = enhanceWithMethods(bulkAction, createBulkActionApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const ResourceTypeWithMethods = enhanceWithMethods(resourceType, createResourceTypeApi(makeRequest));
    return contentfulSdkCore.freezeSys(ResourceTypeWithMethods);
}
function wrapResourceTypeforEnvironment(makeRequest, data) {
    const resourceType = contentfulSdkCore.toPlainObject(data);
    return contentfulSdkCore.freezeSys(resourceType);
}
const wrapResourceTypesForEnvironmentCollection = wrapCursorPaginatedCollection(wrapResourceTypeforEnvironment);

function wrapResource(makeRequest, data) {
    const resource = contentfulSdkCore.toPlainObject(data);
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(invocation);
}

function wrapAgentRun(_makeRequest, data) {
    const agentRun = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(agentRun);
}
function wrapAgentGenerateResponse(_makeRequest, data) {
    const response = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const agentWithMethods = enhanceWithMethods(agent, createAgentApi(makeRequest));
    return contentfulSdkCore.freezeSys(agentWithMethods);
}
const wrapAgentCollection = wrapCollection(wrapAgent);

function wrapSemanticDuplicates(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(result);
}

function wrapSemanticRecommendations(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(result);
}

function wrapSemanticReferenceSuggestions(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(result);
}

function wrapSemanticSearch(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(result);
}

function wrapContentSemanticsIndex(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(result);
}
function wrapContentSemanticsIndexCollection(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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 ? contentfulSdkCore.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: contentfulSdkCore.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: { ...contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const environmentApi = createEnvironmentApi(makeRequest);
    const enhancedEnvironment = enhanceWithMethods(environment, environmentApi);
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const webhookWithMethods = enhanceWithMethods(webhook, createWebhookApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const roleWithMethods = enhanceWithMethods(role, createRoleApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const userWithMethods = enhanceWithMethods(user, {});
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const spaceAddOnWithMethods = enhanceWithMethods(spaceAddOn, {});
    return contentfulSdkCore.freezeSys(spaceAddOnWithMethods);
}
/**
 * @internal
 */
const wrapSpaceAddOnCollection = wrapCollection(wrapSpaceAddOn);
/**
 * @internal
 */
function wrapSpaceAddOnOrganization(makeRequest, data) {
    const orgAddOn = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const orgAddOnWithMethods = enhanceWithMethods(orgAddOn, {});
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const spaceMembershipWithMethods = enhanceWithMethods(spaceMembership, createSpaceMembershipApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const teamSpaceMembershipWithMethods = enhanceWithMethods(teamSpaceMembership, createTeamSpaceMembershipApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const teamWithMethods = enhanceWithMethods(team, createTeamApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const apiKeyWithMethods = enhanceWithMethods(apiKey, createApiKeyApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const enhancedAlias = enhanceWithMethods(alias, createEnvironmentAliasApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const previewApiKeyWithMethods = enhanceWithMethods(previewApiKey, createPreviewApiKeyApi());
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const scheduledActionWithMethods = enhanceWithMethods(scheduledAction, getInstanceMethods(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const aiActionWithMethods = enhanceWithMethods(aiAction, createAiActionApi(makeRequest));
    return contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const spaceApi = createSpaceApi(makeRequest);
    const enhancedSpace = enhanceWithMethods(space, spaceApi);
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const personalAccessTokenWithMethods = enhanceWithMethods(personalAccessToken, {
        revoke: function () {
            return makeRequest({
                entityType: 'PersonalAccessToken',
                action: 'revoke',
                params: { tokenId: data.sys.id },
            }).then((data) => wrapPersonalAccessToken(makeRequest, data));
        },
    });
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const accessTokenWithMethods = enhanceWithMethods(AccessToken, {
        revoke: function () {
            return makeRequest({
                entityType: 'AccessToken',
                action: 'revoke',
                params: { tokenId: data.sys.id },
            }).then((data) => wrapAccessToken(makeRequest, data));
        },
    });
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const appBundleWithMethods = enhanceWithMethods(appBundle, createAppBundleApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const ResourceProviderWithMethods = enhanceWithMethods(resourceProvider, createResourceProviderApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const appDefinitionWithMethods = enhanceWithMethods(appDefinition, createAppDefinitionApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const organizationMembershipWithMethods = enhanceWithMethods(organizationMembership, createOrganizationMembershipApi(makeRequest, organizationId));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const teamMembershipWithMethods = enhanceWithMethods(teamMembership, createTeamMembershipApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const appUploadWithMethods = enhanceWithMethods(appUpload, createAppUploadApi(makeRequest));
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const appActionWithMethods = enhanceWithMethods(appAction, createAppActionApi(makeRequest));
    return contentfulSdkCore.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 contentfulSdkCore.toPlainObject(copy__default.default(data));
}
/**
 * @internal
 */
const wrapAvailableLicenseCollection = wrapCollection(wrapAvailableLicense);

function wrapContentSemanticsSettings(_makeRequest, data) {
    const result = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.createRequestConfig({ query }).params,
                    },
                }).then((data) => wrapTeamMembershipCollection(makeRequest, data));
            }
            return makeRequest({
                entityType: 'TeamMembership',
                action: 'getManyForOrganization',
                params: {
                    organizationId: raw.sys.id,
                    query: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const orgApi = createOrganizationApi(makeRequest);
    const enhancedOrganization = enhanceWithMethods(org, orgApi);
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const usageWithMethods = enhanceWithMethods(usage, {});
    return contentfulSdkCore.freezeSys(usageWithMethods);
}
/** @internal @deprecated */
const wrapUsageCollection = wrapCollection(wrapUsage);
/** @internal */
function wrapAggregatedUsage(_makeRequest, data) {
    const item = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(enhanceWithMethods(item, {}));
}
/** @internal */
const wrapAggregatedUsageCollection = wrapCollection(wrapAggregatedUsage);
/** @internal */
function wrapAssetBandwidthUsage(_makeRequest, data) {
    const item = contentfulSdkCore.toPlainObject(copy__default.default(data));
    return contentfulSdkCore.freezeSys(enhanceWithMethods(item, {}));
}
/** @internal */
function wrapAssetBandwidthUsageDetailedCollection(makeRequest, data) {
    const collectionData = contentfulSdkCore.toPlainObject(copy__default.default(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: { ...contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const environmentTemplateApi = createEnvironmentTemplateApi(makeRequest, organizationId);
    const enhancedEnvironmentTemplate = enhanceWithMethods(environmentTemplate, environmentTemplateApi);
    return contentfulSdkCore.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 = contentfulSdkCore.toPlainObject(copy__default.default(data));
    const oauthApplicationWithMethods = enhanceWithMethods(oauthApplication, createOAuthApplicationApi(makeRequest, userId));
    return contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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: contentfulSdkCore.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"`
         * @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 = copy__default.default(params);
            const get = () => fn(copy__default.default(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 = contentfulSdkCore.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;
//# sourceMappingURL=index.cjs.map