"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const cases_1 = __importDefault(require("./cases"));
const lead_1 = __importDefault(require("./lead"));
const opportunity_1 = __importDefault(require("./opportunity"));
const customObject_1 = __importDefault(require("./customObject"));
const contact_1 = __importDefault(require("./contact"));
const account_1 = __importDefault(require("./account"));
const sf_operations_1 = require("./sf-operations");
const lead2_1 = __importDefault(require("./lead2"));
const contact2_1 = __importDefault(require("./contact2"));
const cases2_1 = __importDefault(require("./cases2"));
const opportunity2_1 = __importDefault(require("./opportunity2"));
const account2_1 = __importDefault(require("./account2"));
const customObject2_1 = __importDefault(require("./customObject2"));
const destination = {
    name: 'Salesforce (Actions)',
    slug: 'actions-salesforce',
    mode: 'cloud',
    authentication: {
        scheme: 'oauth2',
        fields: {
            instanceUrl: {
                label: 'Instance URL',
                description: 'The user specific instance URL returned by Salesforce Oauth. This setting is hidden to the user and set by Oauth Service.',
                type: 'string',
                required: true
            },
            isSandbox: {
                label: 'Sandbox Instance',
                description: 'Enable to authenticate into a sandbox instance. You can log in to a sandbox by appending the sandbox name to your Salesforce username. For example, if a username for a production org is user@acme.com and the sandbox is named test, the username to log in to the sandbox is user@acme.com.test. If you are already authenticated, please disconnect and reconnect with your sandbox username.',
                type: 'boolean',
                default: false
            },
            username: {
                label: 'Username',
                description: 'The username of the Salesforce account you want to connect to. When all three of username, password, and security token are provided, a username-password flow is used to authenticate. This field is hidden to all users except those who have opted in to the username+password flow.',
                type: 'string'
            },
            auth_password: {
                label: 'Password',
                description: 'The password of the Salesforce account you want to connect to. When all three of username, password, and security token are provided, a username-password flow is used to authenticate. This field is hidden to all users except those who have opted in to the username+password flow.',
                type: 'password'
            },
            security_token: {
                label: 'Security Token',
                description: 'The security token of the Salesforce account you want to connect to. When all three of username, password, and security token are provided, a username-password flow is used to authenticate. This value will be appended to the password field to construct the credential used for authentication. This field is hidden to all users except those who have opted in to the username+password flow.',
                type: 'password'
            }
        },
        refreshAccessToken: async (request, { auth, settings }) => {
            if (settings.username && settings.auth_password) {
                const { accessToken } = await (0, sf_operations_1.authenticateWithPassword)(settings.username, settings.auth_password, settings.security_token, settings.isSandbox);
                return { accessToken };
            }
            const baseUrl = settings.isSandbox ? 'https://test.salesforce.com' : 'https://login.salesforce.com';
            const res = await request(`${baseUrl}/services/oauth2/token`, {
                method: 'POST',
                body: new URLSearchParams({
                    refresh_token: auth.refreshToken,
                    client_id: auth.clientId,
                    client_secret: auth.clientSecret,
                    grant_type: 'refresh_token'
                }),
                throwHttpErrors: false
            });
            if (res.ok) {
                return { accessToken: res.data?.access_token };
            }
            if (res.status == 400 &&
                res.data?.error === 'invalid_grant' &&
                res.data?.error_description &&
                ['token request is already being processed', 'expired authorization code'].includes(res.data?.error_description)) {
                throw new actions_core_1.RetryableError('Concurrent token refresh error. This request will be retried');
            }
            throw new actions_core_1.APIError(res.data?.error_description ?? 'Failed to refresh access token', res.status);
        }
    },
    extendRequest({ auth }) {
        return {
            headers: {
                authorization: `Bearer ${auth?.accessToken}`
            }
        };
    },
    actions: {
        lead: lead_1.default,
        customObject: customObject_1.default,
        cases: cases_1.default,
        contact: contact_1.default,
        opportunity: opportunity_1.default,
        account: account_1.default,
        lead2: lead2_1.default,
        customObject2: customObject2_1.default,
        account2: account2_1.default,
        opportunity2: opportunity2_1.default,
        contact2: contact2_1.default,
        cases2: cases2_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map